text stringlengths 81 112k |
|---|
By default we use the referer that was stuffed in our
form when it was created
def get_success_url(self):
"""
By default we use the referer that was stuffed in our
form when it was created
"""
if self.success_url:
# if our smart url references an object, pass... |
We override this, using only those fields specified if they are specified.
Otherwise we include all fields in a standard ModelForm.
def get_form_kwargs(self):
"""
We override this, using only those fields specified if they are specified.
Otherwise we include all fields in a standard M... |
Derives our title from our object
def derive_title(self):
"""
Derives our title from our object
"""
if not self.title:
return _("Create %s") % force_text(self.model._meta.verbose_name).title()
else:
return self.title |
Returns the permission to use for the passed in action
def permission_for_action(self, action):
"""
Returns the permission to use for the passed in action
"""
return "%s.%s_%s" % (self.app_name.lower(), self.model_name.lower(), action) |
Returns the template to use for the passed in action
def template_for_action(self, action):
"""
Returns the template to use for the passed in action
"""
return "%s/%s_%s.html" % (self.module_name.lower(), self.model_name.lower(), action) |
Returns the reverse name for this action
def url_name_for_action(self, action):
"""
Returns the reverse name for this action
"""
return "%s.%s_%s" % (self.module_name.lower(), self.model_name.lower(), action) |
Returns the appropriate view class for the passed in action
def view_for_action(self, action):
"""
Returns the appropriate view class for the passed in action
"""
# this turns replace_foo into ReplaceFoo and read into Read
class_name = "".join([word.capitalize() for word in acti... |
Returns the URL pattern for the passed in action.
def pattern_for_view(self, view, action):
"""
Returns the URL pattern for the passed in action.
"""
# if this view knows how to define a URL pattern, call that
if getattr(view, 'derive_url_pattern', None):
return view... |
Creates the appropriate URLs for this object.
def as_urlpatterns(self):
"""
Creates the appropriate URLs for this object.
"""
urls = []
# for each of our actions
for action in self.actions:
view_class = self.view_for_action(action)
view_pattern =... |
Loads all migrations in the order they would be applied to a clean database
def load_migrations(self): # pragma: no cover
"""
Loads all migrations in the order they would be applied to a clean database
"""
executor = MigrationExecutor(connection=None)
# create the forwards pla... |
Extract SQL operations from the given migrations
def extract_operations(self, migrations):
"""
Extract SQL operations from the given migrations
"""
operations = []
for migration in migrations:
for operation in migration.operations:
if isinstance(oper... |
Removes redundant SQL operations - e.g. a CREATE X followed by a DROP X
def normalize_operations(self, operations):
"""
Removes redundant SQL operations - e.g. a CREATE X followed by a DROP X
"""
normalized = OrderedDict()
for operation in operations:
op_key = (oper... |
Splits the list of SQL operations by type and dumps these to separate files
def write_type_dumps(self, operations, preserve_order, output_dir):
"""
Splits the list of SQL operations by type and dumps these to separate files
"""
by_type = {SqlType.INDEX: [], SqlType.FUNCTION: [], SqlType... |
Returns this Widget rendered as HTML, as a Unicode string.
The 'value' given is not guaranteed to be valid input, so subclass
implementations should program defensively.
def render(self, name, value, attrs=None, renderer=None):
"""
Returns this Widget rendered as HTML, as a Unicode str... |
Add the atomic data to the DataTransferInterface.
:param data_api the data api from where to get the data
:param data_setters the class to push the data to
:param atom_nams the list of atom names for the group
:param element_names the list of element names for this group
:param atom_charges the list... |
Add the bonds for this group.
:param data_setters the class to push the data to
:param bond_indices the indices of the atoms in the group that
are bonded (in pairs)
:param bond_orders the orders of the bonds
def add_group_bonds(data_setters, bond_indices, bond_orders):
"""Add the bonds for this gro... |
Add the data for a whole group.
:param data_api the data api from where to get the data
:param data_setters the class to push the data to
:param group_index the index for this group
def add_group(data_api, data_setters, group_index):
"""Add the data for a whole group.
:param data_api the data api f... |
Add the data for a whole chain.
:param data_api the data api from where to get the data
:param data_setters the class to push the data to
:param chain_index the index for this chain
def add_chain_info(data_api, data_setters, chain_index):
"""Add the data for a whole chain.
:param data_api the data ... |
Add all the structural information.
:param data_api the data api from where to get the data
:param data_setters the class to push the data to
def add_atomic_information(data_api, data_setters):
"""Add all the structural information.
:param data_api the data api from where to get the data
:param dat... |
Generate the bioassembly data.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
def generate_bio_assembly(data_api, struct_inflator):
"""Generate the bioassembly data.
:param data_api the interface to the decoded data
:par... |
Generate inter group bonds.
Bond indices are specified within the whole structure and start at 0.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
def add_inter_group_bonds(data_api, struct_inflator):
""" Generate inter group bonds... |
Add ancilliary header information to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
def add_header_info(data_api, struct_inflator):
""" Add ancilliary header information to the structure.
:param data_api the interfa... |
Add the crystallographic data to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
def add_xtalographic_info(data_api, struct_inflator):
""" Add the crystallographic data to the structure.
:param data_api the interfac... |
Add the entity info to the structure.
:param data_api the interface to the decoded data
:param struct_inflator the interface to put the data into the client object
def add_entity_info( data_api, struct_inflator):
"""Add the entity info to the structure.
:param data_api the interface to the decoded data... |
Utility function to get indices (in pairs) of the bonds.
def get_bonds(input_group):
"""Utility function to get indices (in pairs) of the bonds."""
out_list = []
for i in range(len(input_group.bond_order_list)):
out_list.append((input_group.bond_atom_list[i * 2], input_group.bond_atom_list[i * 2 + ... |
Function to get a unique list of groups.
def get_unique_groups(input_list):
"""Function to get a unique list of groups."""
out_list = []
for item in input_list:
if item not in out_list:
out_list.append(item)
return out_list |
Convert the group object to an appropriate DICT
def convert_to_dict(self):
"""Convert the group object to an appropriate DICT"""
out_dict = {}
out_dict["groupName"] = self.group_name
out_dict["atomNameList"] = self.atom_name_list
out_dict["elementList"] = self.element_list
... |
Create an atom object an set the information.
:param atom_name: the atom name, e.g. CA for this atom
:param serial_number: the serial id of the atom (e.g. 1)
:param alternative_location_id: the alternative location id for the atom, if present
:param x: the x coordiante of the atom
... |
Set the information for a group
:param group_name: the name of this group,e.g. LYS
:param group_number: the residue number of this group
:param insertion_code: the insertion code for this group
:param group_type: a string indicating the type of group (as found in the chemcomp dictionary.... |
Sets the header information.
:param r_free: the measured R-Free for the structure
:param r_work: the measure R-Work for the structure
:param resolution: the resolution of the structure
:param title: the title of the structure
:param deposition_date: the deposition date of the str... |
Encode the data back into a dict.
def encode_data(self):
"""Encode the data back into a dict."""
output_data = {}
output_data["groupTypeList"] = encode_array(self.group_type_list, 4, 0)
output_data["xCoordList"] = encode_array(self.x_coord_list, 10, 1000)
output_data["yCoordList... |
Initialise the structure object.
:param total_num_bonds: the number of bonds in the structure
:param total_num_atoms: the number of atoms in the structure
:param total_num_groups: the number of groups in the structure
:param total_num_chains: the number of chains in the structure
... |
Create an atom object an set the information.
:param atom_name: the atom name, e.g. CA for this atom
:param serial_number: the serial id of the atom (e.g. 1)
:param alternative_location_id: the alternative location id for the atom, if present
:param x: the x coordiante of the atom
... |
Set the chain information.
:param chain_id: the asym chain id from mmCIF
:param chain_name: the auth chain id from mmCIF
:param num_groups: the number of groups this chain has
def set_chain_info(self, chain_id, chain_name, num_groups):
"""Set the chain information.
:param chain_... |
Set the entity level information for the structure.
:param chain_indices: the indices of the chains for this entity
:param sequence: the one letter code sequence for this entity
:param description: the description for this entity
:param entity_type: the entity type (polymer,non-polymer,w... |
Set the information for a group
:param group_name: the name of this group,e.g. LYS
:param group_number: the residue number of this group
:param insertion_code: the insertion code for this group
:param group_type: a string indicating the type of group (as found in the chemcomp dictionary.... |
Set the crystallographic information for the structure
:param space_group: the space group name, e.g. "P 21 21 21"
:param unit_cell: an array of length 6 with the unit cell parameters in order: a, b, c, alpha, beta, gamma
def set_xtal_info(self, space_group, unit_cell):
"""Set the crystallograp... |
Sets the header information.
:param r_free: the measured R-Free for the structure
:param r_work: the measure R-Work for the structure
:param resolution: the resolution of the structure
:param title: the title of the structure
:param deposition_date: the deposition date of the str... |
Set the Bioassembly transformation information. A single bioassembly can have multiple transforms,
:param bio_assembly_index: the integer index of the bioassembly
:param input_chain_indices: the list of integer indices for the chains of this bioassembly
:param input_transformation: the list of d... |
Any functions needed to cleanup the structure.
def finalize_structure(self):
"""Any functions needed to cleanup the structure."""
self.group_list.append(self.current_group)
group_set = get_unique_groups(self.group_list)
for item in self.group_list:
self.group_type_list.appen... |
Add bonds within a group.
:param atom_index_one: the integer atom index (in the group) of the first partner in the bond
:param atom_index_two: the integer atom index (in the group) of the second partner in the bond
:param bond_order: the integer bond order
def set_group_bond(self, atom_index_on... |
Add bonds between groups.
:param atom_index_one: the integer atom index (in the structure) of the first partner in the bond
:param atom_index_two: the integer atom index (in the structure) of the second partner in the bond
:param bond_order the bond order
def set_inter_group_bond(self, atom_ind... |
A function to run length decode an int array.
:param in_array: the inptut array of integers
:return the encoded integer array
def run_length_encode(in_array):
"""A function to run length decode an int array.
:param in_array: the inptut array of integers
:return the encoded integer array"""
if... |
A function to delta decode an int array.
:param in_array: the inut array to be delta encoded
:return the encoded integer array
def delta_encode(in_array):
"""A function to delta decode an int array.
:param in_array: the inut array to be delta encoded
:return the encoded integer array"""
if(le... |
Parse the header of an input byte array and then decode using the input array,
the codec and the appropirate parameter.
:param input_array: the array to be decoded
:return the decoded array
def decode_array(input_array):
"""Parse the header of an input byte array and then decode using the input array,... |
Encode the array using the method and then add the header to this array.
:param input_array: the array to be encoded
:param codec: the integer index of the codec to use
:param param: the integer parameter to use in the function
:return an array with the header added to the fornt
def encode_array(input... |
A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array
def run_length_decode(in_array):
"""A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array"""
switch=False
out_a... |
A function to delta decode an int array.
:param in_array: the input array of integers
:return the decoded array
def delta_decode(in_array):
"""A function to delta decode an int array.
:param in_array: the input array of integers
:return the decoded array"""
if len(in_array) == 0:
retu... |
Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The numbe... |
Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the input bytes
:return the decoded list of strings
def decode_chain_list(in_bytes):
"""Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the inp... |
Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding
def recursive_index_decode(int_array, max=32767, min=-32768):
"... |
Utility function to get the coordinates as a single list of tuples.
def get_coords(self):
"""Utility function to get the coordinates as a single list of tuples."""
out_list = []
for i in range(len(self.x_coord_list)):
out_list.append((self.x_coord_list[i],self.y_coord_list[i],self.z... |
Function to decode the input data and place it onto the class.
:param input_data: the input data as a dict
def decode_data(self, input_data):
"""Function to decode the input data and place it onto the class.
:param input_data: the input data as a dict"""
self.group_type_list = decode_ar... |
Write the data from the getters to the setters.
:param data_setters: a series of functions that can fill a chemical
data structure
:type data_setters: DataTransferInterface
def pass_data_on(self, data_setters):
"""Write the data from the getters to the setters.
:param data_set... |
Check to see if the internet is on by pinging a set address.
:param address: the IP or address to hit
:return: a boolean - true if can be reached, false if not.
def _internet_on(address):
"""
Check to see if the internet is on by pinging a set address.
:param address: the IP or address to hit
:... |
API function to write data as MMTF to a file
:param file_path the path of the file to write
:param input_data the input data in any user format
:param input_function a function to converte input_data to an output format. Must contain all methods in TemplateEncoder
def write_mmtf(file_path, input_data, inp... |
Get the msgpack unpacked data given a PDB id.
:param pdb_id: the input PDB id
:return the unpacked data (a dict)
def get_raw_data_from_url(pdb_id, reduced=False):
"""" Get the msgpack unpacked data given a PDB id.
:param pdb_id: the input PDB id
:return the unpacked data (a dict) """
url = ge... |
Return a decoded API to the data from a file path.
:param file_path: the input file path. Data is not entropy compressed (e.g. gzip)
:return an API to decoded data
def parse(file_path):
"""Return a decoded API to the data from a file path.
:param file_path: the input file path. Data is not entropy co... |
Return a decoded API to the data from a file path. File is gzip compressed.
:param file_path: the input file path. Data is gzip compressed.
:return an API to decoded data
def parse_gzip(file_path):
"""Return a decoded API to the data from a file path. File is gzip compressed.
:param file_path: the inpu... |
Return a string of data after gzip decoding
:param the input gziped data
:return the gzip decoded data
def ungzip_data(input_data):
"""Return a string of data after gzip decoding
:param the input gziped data
:return the gzip decoded data"""
buf = StringIO(input_data)
f = gzip.GzipFile(f... |
Parse the header and return it along with the input array minus the header.
:param input_array the array to parse
:return the codec, the length of the decoded array, the parameter and the remainder
of the array
def parse_header(input_array):
"""Parse the header and return it along with the input array ... |
Add the header to the appropriate array.
:param the encoded array to add the header to
:param the codec being used
:param the length of the decoded array
:param the parameter to add to the header
:return the prepended encoded byte array
def add_header(input_array, codec, length, param):
"""Add ... |
Convert a byte array into an integer array. The number of bytes forming an integer
is defined by num
:param in_bytes: the input bytes
:param num: the number of bytes per int
:return the integer array
def convert_bytes_to_ints(in_bytes, num):
"""Convert a byte array into an integer array. The number... |
Convert an integer array into a byte arrays. The number of bytes forming an integer
is defined by num
:param in_ints: the input integers
:param num: the number of bytes per int
:return the integer array
def convert_ints_to_bytes(in_ints, num):
"""Convert an integer array into a byte arrays. The nu... |
Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the input bytes
:return the decoded list of strings
def decode_chain_list(in_bytes):
"""Convert a list of bytes to a list of strings. Each string is of length mmtf.CHAIN_LEN
:param in_bytes: the inp... |
Convert a list of strings to a list of byte arrays.
:param in_strings: the input strings
:return the encoded list of byte arrays
def encode_chain_list(in_strings):
"""Convert a list of strings to a list of byte arrays.
:param in_strings: the input strings
:return the encoded list of byte arrays""... |
Pack an integer array using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index encoding
def recursive_index_encode(int_array, max=32767, min=-32768):
"""Pack... |
Unpack an array of integers using recursive indexing.
:param int_array: the input array of integers
:param max: the maximum integer size
:param min: the minimum integer size
:return the array of integers after recursive index decoding
def recursive_index_decode(int_array, max=32767, min=-32768):
""... |
A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array
def run_length_decode(in_array):
"""A function to run length decode an int array.
:param in_array: the input array of integers
:return the decoded array"""
switch=False
out... |
Build and return an optimizer for the rosenbrock function.
In downhill, an optimizer can be constructed using the build() top-level
function. This function requires several Theano quantities such as the loss
being optimized and the parameters to update during optimization.
def build(algo, init):
'''Bu... |
Run an optimizer on the rosenbrock function. Return xs, ys, and losses.
In downhill, optimization algorithms can be iterated over to progressively
minimize the loss. At each iteration, the optimizer yields a dictionary of
monitor values that were computed during that iteration. Here we build an
optimiz... |
Minimize a loss function with respect to some symbolic parameters.
Additional keyword arguments are passed to the underlying :class:`Optimizer
<downhill.base.Optimizer>` instance.
Parameters
----------
loss : Theano expression
Loss function to minimize. This must be a scalar-valued express... |
Create a legend label for an optimization run.
def make_label(loss, key):
'''Create a legend label for an optimization run.'''
algo, rate, mu, half, reg = key
slots, args = ['{:.3f}', '{}', 'm={:.3f}'], [loss, algo, mu]
if algo in 'SGD NAG RMSProp Adam ESGD'.split():
slots.append('lr={:.2e}')
... |
Iterate over batches in the dataset.
This method generates ``iteration_size`` batches from the dataset and
then returns.
Parameters
----------
shuffle : bool, optional
Shuffle the batches in this dataset if the iteration reaches the end
of the batch list... |
Create a Theano shared variable like an existing parameter.
Parameters
----------
param : Theano variable
Theano variable to use for shape information.
suffix : str
Suffix to append to the parameter's name for the new variable.
init : float or ndarray, optional
Initial value... |
Walk a computation graph and extract root variables.
Parameters
----------
node : Theano expression
A symbolic Theano expression to walk.
Returns
-------
inputs : list Theano variables
A list of candidate inputs for this graph. Inputs are nodes in the graph
with no pare... |
Log a message to the console.
Parameters
----------
msg : str
A string to display on the console. This can contain {}-style
formatting commands; the remaining positional and keyword arguments
will be used to fill them in.
def log(msg, *args, **kwargs):
'''Log a message to the c... |
Log a parameter value to the console.
Parameters
----------
name : str
Name of the parameter being logged.
value : any
Value of the parameter being logged.
def log_param(name, value):
'''Log a parameter value to the console.
Parameters
----------
name : str
Nam... |
Load the MNIST digits dataset.
def load_mnist():
'''Load the MNIST digits dataset.'''
mnist = skdata.mnist.dataset.MNIST()
mnist.meta # trigger download if needed.
def arr(n, dtype):
arr = mnist.arrays[n]
return arr.reshape((len(arr), -1)).astype(dtype)
train_images = arr('train_i... |
Construct an optimizer by name.
Parameters
----------
algo : str
The name of the optimization algorithm to build.
loss : Theano expression
Loss function to minimize. This must be a scalar-valued expression.
params : list of Theano variables, optional
Symbolic variables to ad... |
Compile the Theano functions for evaluating and updating our model.
def _compile(self, **kwargs):
'''Compile the Theano functions for evaluating and updating our model.
'''
util.log('compiling evaluation function')
self.f_eval = theano.function(self._inputs,
... |
Get parameter update expressions for performing optimization.
Keyword arguments can be applied here to set any of the global
optimizer attributes.
Yields
------
updates : (parameter, expression) tuples
A sequence of parameter updates to be applied during optimizatio... |
Return a sequence of gradients for our parameters.
If this optimizer has been configured with a gradient norm limit, or
with elementwise gradient clipping, this method applies the appropriate
rescaling and clipping operations before returning the gradient.
Parameters
----------... |
Set the values of the parameters to the given target values.
Parameters
----------
targets : sequence of ndarray, optional
Arrays for setting the parameters of our model. If this is not
provided, the current best parameters for this optimizer will be
used.
d... |
Log the state of the optimizer on the console.
Parameters
----------
monitors : OrderedDict
A dictionary of monitor names mapped to values. These names and
values are what is being logged.
iteration : int
Optimization iteration that we are logging.
... |
Evaluate the current model parameters on a dataset.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A set of data to use for evaluating the model.
Returns
-------
monitors : OrderedDict
A dictionary mapping monitor nam... |
Set up properties for optimization.
This method can be overridden by base classes to provide parameters that
are specific to a particular optimization technique (e.g., setting up a
learning rate value).
def _prepare(self, **kwargs):
'''Set up properties for optimization.
This ... |
r'''Optimize a loss iteratively using a training and validation dataset.
This method yields a series of monitor values to the caller. After every
optimization epoch, a pair of monitor dictionaries is generated: one
evaluated on the training dataset during the epoch, and another
evaluate... |
Optimize our loss exhaustively.
This method is a thin wrapper over the :func:`iterate` method. It simply
exhausts the iterative optimization process and returns the final
monitor values.
Returns
-------
train_monitors : dict
A dictionary mapping monitor name... |
Advance the state of the optimizer by one step.
Parameters
----------
dataset : :class:`Dataset <downhill.dataset.Dataset>`
A dataset for optimizing the model.
Returns
-------
train_monitors : dict
A dictionary mapping monitor names to values.
d... |
Returns True if the given method will accept the given number of arguments
method: the method to perform introspection on
number_of_arguments: the number_of_arguments
def accept_arguments(method, number_of_arguments=1):
"""Returns True if the given method will accept the given number of arguments
... |
Emits a signal, causing all slot methods connected with the signal to be called (optionally w/ related value)
signal: the name of the signal to emit, must be defined in the classes 'signals' list.
value: the value to pass to all connected slot methods.
gather: if set, causes emit to re... |
Defines a connection between this objects signal and another objects slot
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be called
slot: the slot method to call
transform: an optional value ov... |
Removes connection(s) between this objects signal and connected slot(s)
signal: the signal this class will emit, to cause the slot method to be called
receiver: the object containing the slot method to be called
slot: the slot method or function to call
transform: an optiona... |
Returns context data for a given app, can be an ID or a case insensitive name
def get(self, key):
""" Returns context data for a given app, can be an ID or a case insensitive name """
keystr = str(key)
res = None
try:
res = self.ctx[keystr]
except KeyError:
... |
The URL-friendly identifier for the item. Generates its own approximation if one isn't available
def hash_name(self):
""" The URL-friendly identifier for the item. Generates its own approximation if one isn't available """
name = self._item.get("market_hash_name")
if not name:
name... |
Can't really trust presence of a schema here, but there is an ID sometimes
def quality(self):
""" Can't really trust presence of a schema here, but there is an ID sometimes """
try:
qid = int((self.tool_metadata or {}).get("quality", 0))
except:
qid = 0
# We mig... |
Get the current API key.
if one has not been given via 'set' the env var STEAMODD_API_KEY will
be checked instead.
def get(cls):
"""Get the current API key.
if one has not been given via 'set' the env var STEAMODD_API_KEY will
be checked instead.
"""
apikey = cls... |
Make the API call again and fetch fresh data.
def call(self):
""" Make the API call again and fetch fresh data. """
data = self._downloader.download()
# Only try to pass errors arg if supported
if sys.version >= "2.7":
data = data.decode("utf-8", errors="ignore")
el... |
Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID
def _attribute_definition(self, attrid):
""" Returns the attribute definition dict of a given attribute
ID, can be the name or the integer ID """
attrs = self._schema["attributes"]
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.