Search is not available for this dataset
text
stringlengths
75
104k
def get_context_data(self, **kwargs): """ We supplement the normal context data by adding our fields and labels. """ context = super(SmartView, self).get_context_data(**kwargs) # derive our field config self.field_config = self.derive_field_config() # add our fi...
def render_to_response(self, context, **response_kwargs): """ Overloaded to deal with _format arguments. """ # should we actually render in json? if '_format' in self.request.GET and self.request.GET['_format'] == 'json': return JsonResponse(self.as_json(context), saf...
def derive_fields(self): """ Derives our fields. We first default to using our 'fields' variable if available, otherwise we figure it out from our object. """ if self.fields: return list(self.fields) else: fields = [] for field in sel...
def get_context_data(self, **kwargs): """ Add in the field to use for the name field """ context = super(SmartDeleteView, self).get_context_data(**kwargs) context['name_field'] = self.name_field context['cancel_url'] = self.get_cancel_url() return context
def derive_title(self): """ Derives our title from our list """ title = super(SmartListView, self).derive_title() if not title: return force_text(self.model._meta.verbose_name_plural).title() else: return title
def derive_link_fields(self, context): """ Used to derive which fields should be linked. This should return a set() containing the names of those fields which should be linkable. """ if self.link_fields is not None: return self.link_fields else: ...
def lookup_field_orderable(self, field): """ Returns whether the passed in field is sortable or not, by default all 'raw' fields, that is fields that are part of the model are sortable. """ try: self.model._meta.get_field_by_name(field) return True ...
def get_context_data(self, **kwargs): """ Add in what fields are linkable """ context = super(SmartListView, self).get_context_data(**kwargs) # our linkable fields self.link_fields = self.derive_link_fields(context) # stuff it all in our context context[...
def derive_queryset(self, **kwargs): """ Derives our queryset. """ # get our parent queryset queryset = super(SmartListView, self).get_queryset(**kwargs) # apply any filtering search_fields = self.derive_search_fields() search_query = self.request.GET.get...
def get_queryset(self, **kwargs): """ Gets our queryset. This takes care of filtering if there are any fields to filter by. """ queryset = self.derive_queryset(**kwargs) return self.order_queryset(queryset)
def derive_ordering(self): """ Returns what field should be used for ordering (using a prepended '-' to indicate descending sort). If the default order of the queryset should be used, returns None """ if '_order' in self.request.GET: return self.request.GET['_order']...
def order_queryset(self, queryset): """ Orders the passed in queryset, returning a new queryset in response. By default uses the _order query parameter. """ order = self.derive_ordering() # if we get our order from the request # make sure it is a valid field in ...
def derive_fields(self): """ Derives our fields. """ if self.fields: return self.fields else: fields = [] for field in self.object_list.model._meta.fields: if field.name != 'id': fields.append(field.name) ...
def render_to_response(self, context, **response_kwargs): """ Overloaded to deal with _format arguments. """ # is this a select2 format response? if self.request.GET.get('_format', 'html') == 'select2': results = [] for obj in context['object_list']: ...
def get_form(self): """ Returns an instance of the form to be used in this view. """ self.form = super(SmartFormMixin, self).get_form() fields = list(self.derive_fields()) # apply our field filtering on our form class exclude = self.derive_exclude() excl...
def customize_form_field(self, name, field): """ Allows views to customize their form fields. By default, Smartmin replaces the plain textbox date input with it's own DatePicker implementation. """ if isinstance(field, forms.fields.DateField) and isinstance(field.widget, forms.w...
def lookup_field_label(self, context, field, default=None): """ Figures out what the field label should be for the passed in field name. We overload this so as to use our form to see if there is label set there. If so then we'll pass that as the default instead of having our parent der...
def lookup_field_help(self, field, default=None): """ Looks up the help text for the passed in field. This is overloaded so that we can check whether our form has help text set explicitely. If so, we will pass this as the default to our parent function. """ default = No...
def derive_readonly(self): """ Figures out what fields should be readonly. We iterate our field_config to find all that have a readonly of true """ readonly = list(self.readonly) for key, value in self.field_config.items(): if 'readonly' in value and value['r...
def derive_fields(self): """ Derives our fields. """ if self.fields is not None: fields = list(self.fields) else: form = self.form fields = [] for field in form: fields.append(field.name) # this is sligh...
def get_form_class(self): """ Returns the form class to use in this view """ if self.form_class: form_class = self.form_class else: if self.model is not None: # If a model has been explicitly provided, use it model = self.m...
def get_factory_kwargs(self): """ Let's us specify any extra parameters we might want to call for our form factory. These can include: 'form', 'fields', 'exclude' or 'formfield_callback' """ params = dict() exclude = self.derive_exclude() exclude += self.derive_...
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 that in if self.success_url.find('@') > 0: return smart_url...
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 ModelForm. """ kwargs = super(SmartFormMixin, self).get_form_kwargs() kwargs['initial'] = self.derive_initial() ...
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
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)
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)
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)
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 action.split("_")]) view = None # see if we have...
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.derive_url_pattern(self.path, action) # o...
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 = self.pattern_for_view(view_class, action) ...
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 plan Django would follow on an empty database plan = executor.migration_...
def extract_operations(self, migrations): """ Extract SQL operations from the given migrations """ operations = [] for migration in migrations: for operation in migration.operations: if isinstance(operation, RunSQL): statements = s...
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 = (operation.sql_type, operation.obj_name) # do we already have an ...
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.TRIGGER: []} for operation in operations: by_type[operat...
def render(self, name, value, attrs=None, renderer=None): """ 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. """ html = '' html += '%s' % va...
def add_atom_data(data_api, data_setters, atom_names, element_names, atom_charges, group_atom_ind): """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 t...
def add_group_bonds(data_setters, bond_indices, bond_orders): """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""" for bond_index in ra...
def add_group(data_api, data_setters, group_index): """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""" group_type_ind = data_api.group_type_list[group_index] a...
def add_chain_info(data_api, data_setters, chain_index): """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""" chain_id = data_api.chain_id_list[chain_index] chai...
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 data_setters the class to push the data to""" for model_chains in data_api.chains_per_model: data_setters.set_model_info(data_api.model_counte...
def generate_bio_assembly(data_api, struct_inflator): """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""" bioassembly_count = 0 for bioassembly in data_api.bio_assembly: bioassembly...
def add_inter_group_bonds(data_api, struct_inflator): """ 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""" for i in range(len(d...
def add_header_info(data_api, struct_inflator): """ 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 """ struct_inflator.set_header_info(data_api.r_free, ...
def add_xtalographic_info(data_api, struct_inflator): """ 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""" if data_api.unit_cell == None and data_api.space_group is not None: ...
def add_entity_info( data_api, struct_inflator): """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 """ for entity in data_api.entity_list: struct_inflator.set_entity_info(enti...
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 + 1],)) return out_list
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
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 out_dict["bondOrderList"] = self.bond_order_li...
def set_atom_info(self, atom_name, serial_number, alternative_location_id, x, y, z, occupancy, temperature_factor, element, charge): """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 o...
def set_group_info(self, group_name, group_number, insertion_code, group_type, atom_count, bond_count, single_letter_code, sequence_index, secondary_structure_type): """Set the information for a group :param group_name: the name of this group,e.g. LYS ...
def set_header_info(self, r_free, r_work, resolution, title, deposition_date, release_date, experimental_methods): """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 resol...
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"] = encode_array(self.y_coord_list...
def init_structure(self, total_num_bonds, total_num_atoms, total_num_groups, total_num_chains, total_num_models, structure_id): """Initialise the structure object. :param total_num_bonds: the number of bonds in the structure :param total_num_atoms: t...
def set_atom_info(self, atom_name, serial_number, alternative_location_id, x, y, z, occupancy, temperature_factor, element, charge): """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 o...
def set_chain_info(self, chain_id, chain_name, num_groups): """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 """ self.chain_id_list.append(cha...
def set_entity_info(self, chain_indices, sequence, description, entity_type): """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 descr...
def set_group_info(self, group_name, group_number, insertion_code, group_type, atom_count, bond_count, single_letter_code, sequence_index, secondary_structure_type): """Set the information for a group :param group_name: the name of this group,e.g. LYS ...
def set_xtal_info(self, space_group, unit_cell): """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 """ se...
def set_header_info(self, r_free, r_work, resolution, title, deposition_date, release_date, experimental_methods): """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 resol...
def set_bio_assembly_trans(self, bio_assembly_index, input_chain_indices, input_transform): """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 o...
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.append(group_set.index(item)) self.group_list...
def set_group_bond(self, atom_index_one, atom_index_two, bond_order): """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 ...
def set_inter_group_bond(self, atom_index_one, atom_index_two, bond_order): """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...
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(len(in_array)==0): return [] curr_ans = in_array[0] out_array = [curr_ans] counter = 1 for in_int in in_array[1...
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(len(in_array)==0): return [] curr_ans = in_array[0] out_array = [curr_ans] for in_int in in_array[1:]: out_arra...
def decode_array(input_array): """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""" codec, length, param, input_array = parse_header(input_array) return...
def encode_array(input_array, codec, param): """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 t...
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_array=[] for item in in_array: if switch==False: this_item = item switch=True else:...
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: return [] this_ans = in_array[0] out_array = [this_ans] for i in range(1, len(in_array)): this_ans += in_a...
def convert_bytes_to_ints(in_bytes, num): """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""" dt = numpy.dtype('>i' + str(num)) return nu...
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 input bytes :return the decoded list of strings""" bstrings = numpy.frombuffer(in_bytes, numpy.dtype('S' + str(mmtf.utils.constants.CHAIN_LEN))) return [s.d...
def recursive_index_decode(int_array, max=32767, min=-32768): """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 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_coord_list[i],)) return out_list
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_array(input_data["groupTypeList"]) self.x_coord_list = decode_array(input_data["xCoordList"]) self.y_c...
def pass_data_on(self, data_setters): """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 """ data_setters.init_structure(self.num_bonds, len(self....
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 :return: a boolean - true if can be reached, false if not. """ try: urllib2.urlopen(address, timeout=1) return True except urllib2.URLError as ...
def write_mmtf(file_path, input_data, input_function): """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...
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 = get_url(pdb_id,reduced) request = urllib2.Request(url) request.add_header('Accept-encoding', 'gzip') response = u...
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 compressed (e.g. gzip) :return an API to decoded data """ newDecoder = MMTFDecoder() with open(file_path, "rb") as fh: newDecoder.decode_data(_unpack(fh)) ...
def parse_gzip(file_path): """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""" newDecoder = MMTFDecoder() newDecoder.decode_data(_unpack(gzip.open(file_path, "rb"))) retur...
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(fileobj=buf) return f
def parse_header(input_array): """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""" codec = struct.unpack(mmtf.utils.constants.NUM_DICT[...
def add_header(input_array, codec, length, param): """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 convert_bytes_to_ints(in_bytes, num): """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""" out_arr = [] for i in range(len(in_bytes)//n...
def convert_ints_to_bytes(in_ints, num): """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""" out_bytes= b"" for val in in_ints: ...
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 input bytes :return the decoded list of strings""" tot_strings = len(in_bytes) // mmtf.utils.constants.CHAIN_LEN out_strings = [] for i in range(tot_str...
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""" out_bytes = b"" for in_s in in_strings: out_bytes+=in_s.encode('ascii') for i in range(mmtf.utils.constants.CHAIN...
def recursive_index_encode(int_array, max=32767, min=-32768): """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_decode(int_array, max=32767, min=-32768): """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 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_array=[] in_array = in_array.tolist() for item in in_array: if switch==False: this_item = item ...
def build(algo, init): '''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_and_trace(algo, init, limit=100, **kwargs): '''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...
def minimize(loss, train, valid=None, params=None, inputs=None, algo='rmsprop', updates=(), monitors=(), monitor_gradients=False, batch_size=32, train_batches=None, valid_batches=None, **kwargs): '''Minimize a loss function with respect to some symbolic parameters. Additional keyword ...
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}') args.append(rate) if algo in 'RMSProp...
def iterate(self, shuffle=True): '''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 r...
def shared_like(param, suffix, init=0): '''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 : f...
def find_inputs_and_params(node): '''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 ar...
def log(msg, *args, **kwargs): '''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. ''' now = datet...
def log_param(name, value): '''Log a parameter value to the console. Parameters ---------- name : str Name of the parameter being logged. value : any Value of the parameter being logged. ''' log('setting {} = {}', click.style(str(name)), click.style(str(value), fg='y...