code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# print ("-" + line + "-") if line == '': line = 'None' if self.is_lower: line = line.lower() if line == "user ": # for slurm which has "user" and "user " line = "userid" for convert in self.change: line = line.replace(con...
def clean(self, line)
:param line: cleans the string :return:
5.924534
6.041411
0.980654
header = self.lines[0] self.lines = self.lines[1:] self.headers = \ [self.clean(h) for h in header.split(self.seperator)] if self.is_strip: self.headers = self.headers[1:-1] return self.headers
def _get_headers(self)
assumes comment have been stripped with extract :return:
4.804458
4.214108
1.140089
d = tempfile.mkdtemp(*args, **kwargs) try: yield d finally: shutil.rmtree(d)
def tempdir(*args, **kwargs)
A contextmanager to work in an auto-removed temporary directory Arguments are passed through to tempfile.mkdtemp example: >>> with tempdir() as path: ... pass
2.671066
3.083612
0.866213
sleeptime_ms = 500 while True: if fn(): return True else: print('Sleeping {} ms'.format(sleeptime_ms)) time.sleep(sleeptime_ms / 1000.0) sleeptime_ms *= 2 if sleeptime_ms / 1000.0 > sleeptime_s_max: return False
def exponential_backoff(fn, sleeptime_s_max=30 * 60)
Calls `fn` until it returns True, with an exponentially increasing wait time between calls
2.277949
2.151385
1.058829
p = pattern.replace("*", ".*") test = re.compile(p) result = [] for l in lines: if test.search(l): result.append(l) return result
def search(lines, pattern)
return all lines that match the pattern #TODO: we need an example :param lines: :param pattern: :return:
2.79051
2.860748
0.975448
try: # for line in file # if line matches pattern: # return line return next((L for L in open(filename) if L.find(pattern) >= 0)) except StopIteration: return ''
def grep(pattern, filename)
Very simple grep that returns the first matching line in a file. String matching only, does not do REs as currently implemented.
5.117185
4.886104
1.047294
result = os.path.expandvars(os.path.expanduser(text)) # template = Template(text) # result = template.substitute(os.environ) if result.startswith("."): result = result.replace(".", os.getcwd(), 1) return result
def path_expand(text)
returns a string with expanded variable. :param text: the path to be expanded, which can include ~ and environment $ variables :param text: string
3.220556
3.845129
0.837568
# if isinstance(data, basestring): if isinstance(data, str): return str(data) elif isinstance(data, collectionsAbc.Mapping): return dict(map(convert_from_unicode, data.items())) elif isinstance(data, collectionsAbc.Iterable): return type(data)(map(convert_from_unicode, data...
def convert_from_unicode(data)
converts unicode data to a string :param data: the data to convert :return:
2.110463
2.194583
0.961669
# http://stackoverflow.com/questions/3041986/python-command-line-yes-no-input""" choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N' if tries is None: choice = input("%s (%s) " % (message, choices)) values = ('y', 'yes', '') if default == 'y' else ('y', 'yes') return T...
def yn_choice(message, default='y', tries=None)
asks for a yes/no question. :param tries: the number of tries :param message: the message containing the question :param default: the default answer
2.528167
2.508583
1.007807
output = "" if debug: output = "\n" output += "# " + 70 * c + "\n" if label is not None: output += "# " + label + "\n" output += "# " + 70 * c + "\n" if txt is not None: for line in txt.split("\n"): output += "# " + line + ...
def banner(txt=None, c="#", debug=True, label=None, color=None)
prints a banner of the form with a frame of # around the txt:: ############################ # txt ############################ :param color: prints in the given color :param label: adds a label :param debug: prints only if debug is true :param txt: a text message to be printed :t...
2.618369
2.769132
0.945556
line = "" if debug: line += "\n" line += "# " + str(70 * c) if txt is not None: line += "# " + txt line += "# " + str(70 * c) return line
def str_banner(txt=None, c="#", debug=True)
prints a banner of the form with a frame of # around the txt:: ############################ # txt ############################ :param debug: return "" if not in debug :type debug: boolean :param txt: a text message to be printed :type txt: string :param c: the character used inst...
3.990343
4.470442
0.892606
frame = inspect.getouterframes(inspect.currentframe()) filename = frame[1][1].replace(os.getcwd(), "") line = frame[1][2] - 1 method = frame[1][3] msg = "{}\n# {} {} {}".format(txt, method, filename, line) print() banner(msg, c=c)
def HEADING(txt=None, c="#")
Prints a message to stdout with #### surrounding it. This is useful for nosetests to better distinguish them. :param c: uses the given char to wrap the header :param txt: a text message to be printed :type txt: string
4.398634
4.725827
0.930765
location = path_expand(filename) n = 0 found = True backup = None while found: n += 1 backup = "{0}.bak.{1}".format(location, n) found = os.path.isfile(backup) return backup
def backup_name(filename)
:param filename: given a filename creates a backup name of the form filename.bak.1. If the filename already exists the number will be increased as much as needed so the file does not exist in the given location. The filename can consis...
3.705971
3.600321
1.029345
version_filename = Path( "{classname}/{filename}".format(classname=class_name, filename=filename)) with open(version_filename, "r") as f: content = f.read() if content != '__version__ = "{0}"'.format(version): banner("Updating version to ...
def auto_create_version(class_name, version, filename="__init__.py")
creates a version number in the __init__.py file. it can be accessed with __version__ :param class_name: :param version: :param filename: :return:
2.880091
2.982601
0.965631
with open(path_expand(filename), 'r') as f: content = f.read() return content
def readfile(filename)
returns the content of a file :param filename: the filename :return:
4.164052
5.662739
0.735342
with open(path_expand(filename), 'w') as outfile: outfile.write(content)
def writefile(filename, content)
writes the content into the file :param filename: the filename :param content: teh content :return:
4.395842
6.494404
0.676866
lletters = "abcdefghijklmnopqrstuvwxyz" uletters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # This doesn't guarantee both lower and upper cases will show up alphabet = lletters + uletters digit = "0123456789" mypw = "" def _random_character(texts): return texts[random.randrange(len(texts))...
def generate_password(length=8, lower=True, upper=True, number=True)
generates a simple password. We should not really use this in production. :param length: the length of the password :param lower: True of lower case characters are allowed :param upper: True if upper case characters are allowed :param number: True if numbers are allowed :return:
3.567205
3.535004
1.009109
file_contains_tabs = False with open(filename) as f: lines = f.read().split("\n") line_no = 1 for line in lines: if "\t" in line: file_contains_tabs = True location = [ i for i in range(len(line)) if line.startswith('\t', i)] if v...
def check_file_for_tabs(filename, verbose=True)
identifies if the file contains tabs and returns True if it does. It also prints the location of the lines and columns. If verbose is set to False, the location is not printed. :param verbose: if true prints information about issues :param filename: the filename :rtype: True if there are tabs in th...
3.211359
3.203642
1.002409
# noinspection PyClassHasNoInit class OrderedLoader(Loader): pass def construct_mapping(loader, node): loader.flatten_mapping(node) return object_pairs_hook(loader.construct_pairs(node)) OrderedLoader.add_constructor( yaml.resolver.BaseResolver.D...
def ordered_load(stream, Loader=yaml.Loader, object_pairs_hook=OrderedDict)
Loads an ordered dict into a yaml while preserving the order :param stream: the name of the stream :param Loader: the yam loader (such as yaml.SafeLoader) :param object_pairs_hook: the ordered dict
1.736719
2.086541
0.832344
location = filename if location is not None: location = path_expand(location) if not os.path.exists(location) and not check: return None if check and os.path.exists(location): # test for tab in yaml file if check_file_for_tabs(location): log.error("The...
def read_yaml_config(filename, check=True, osreplace=True, exit=True)
reads in a yaml file from the specified filename. If check is set to true the code will fail if the file does not exist. However if it is set to false and the file does not exist, None is returned. :param exit: if true is exist with sys exit :param osreplace: if true replaces environment variables from...
3.289561
3.36469
0.977671
for key, value in data_structure.items(): print("\n%s%s:" % (' ' * attribute_indent * indent, str(key)), end=' ') if isinstance(value, OrderedDict): custom_print(value, indent + 1) elif isinstance(value, dict): custom_print(value, indent + 1) else: ...
def custom_print(data_structure, indent)
prints a given data structure such as a dict or ordered dict at a given indentation level :param data_structure: :param indent: :return:
2.324497
2.397475
0.96956
if isinstance(o, OrderedDict): return "{" + ",\n ".join([self.encode(k) + ":" + self.encode(v, depth + 1) for (k, v) in o.items()]) + "}\n" else: return simplejson.JSONEncoder.encode(self, o)
def encode(self, o, depth=0)
encode the json object at given depth :param o: the object :param depth: the depth :return: the json encoding
2.783068
2.913888
0.955105
for v in ["filename", "location", "prefix"]: if "meta" not in self: self["meta"] = {} self["meta"][v] = self[v] del self[v]
def _update_meta(self)
internal function to define the metadata regarding filename, location, and prefix.
4.610983
3.189882
1.445503
self._set_filename(filename) if os.path.isfile(self['location']): # d = OrderedDict(read_yaml_config(self['location'], check=True)) d = read_yaml_config(self['location'], check=True) with open(self['location']) as myfile: document = myfile.r...
def load(self, filename)
Loads the yaml file with the given filename. :param filename: the name of the yaml file
4.581124
4.667973
0.981395
try: log.error("Filename: {0}".format(self['meta']['location'])) except: log.error("Filename: {0}".format(self['location'])) log.error("Key '{0}' does not exist".format('.'.join(keys))) indent = "" last_index = len(keys) - 1 for i, k in en...
def error_keys_not_found(self, keys)
Check if the requested keys are found in the dict. :param keys: keys to be looked for
3.666515
3.91009
0.937706
return ordered_dump(OrderedDict(self), Dumper=yaml.SafeDumper, default_flow_style=False)
def yaml(self)
returns the yaml output of the dict.
5.242913
4.4271
1.184277
if keys is None: return self if "." in keys[0]: keys = keys[0].split('.') element = self for v in keys: try: element = element[v] except KeyError: self.error_keys_not_found(keys) # s...
def get(self, *keys)
returns the dict of the information as read from the yaml file. To access the file safely, you can use the keys in the order of the access. Example: get("provisioner","policy") will return the value of config["provisioner"]["policy"] from the yaml file if it does not exists an er...
4.056227
4.301588
0.94296
element = self if keys is None: return self if '.' in keys[0]: keys = keys[0].split(".") nested_str = ''.join(["['{0}']".format(x) for x in keys]) # Safely evaluate an expression to see if it is one of the Python # literal structures: s...
def set(self, value, *keys)
Sets the dict of the information as read from the yaml file. To access the file safely, you can use the keys in the order of the access. Example: set("{'project':{'fg82':[i0-i10]}}", "provisioner","policy") will set the value of config["provisioner"]["policy"] in the yaml file if it does...
5.269274
5.106217
1.031933
if self['meta']['prefix'] is None: k = keys else: k = self['meta']['prefix'] + "." + keys return self.get(k)
def attribute(self, keys)
TODO: document this method :param keys:
4.904025
5.825177
0.841867
flat = flatten(table, sep=sep) return Printer.write(flat, sort_keys=sort_keys, order=order, header=header, output=output)
def flatwrite(cls, table, order=None, header=None, output="table", sort_keys=True, show_none="", sep="." )
writes the information given in the table :param table: the table of values :param order: the order of the columns :param header: the header for the columns :param output: the format (default is table, values are raw, csv, json, yaml, dict :param sort_keys: if true the table is s...
4.25196
6.427778
0.661498
if output == "raw": return table elif table is None: return None elif type(table) in [dict, dotdict]: return cls.dict(table, order=order, header=header, output=output,...
def write(cls, table, order=None, header=None, output="table", sort_keys=True, show_none="" )
writes the information given in the table :param table: the table of values :param order: the order of the columns :param header: the header for the columns :param output: the format (default is table, values are raw, csv, json, yaml, dict :param sort_keys: if true the table is s...
2.351774
2.328771
1.009877
d = {} count = 0 for entry in l: name = str(count) d[name] = entry count += 1 return cls.dict(d, order=order, header=header, sort_keys=sort_keys, o...
def list(cls, l, order=None, header=None, output="table", sort_keys=True, show_none="" )
:param l: l is a list not a dict :param order: :param header: :param output: :param sort_keys: :param show_none: :return:
2.500415
2.625317
0.952424
if output == "table": if d == {}: return None else: return cls.dict_table(d, order=order, header=header, sort_keys=sort_keys) ...
def dict(cls, d, order=None, header=None, output="table", sort_keys=True, show_none="")
TODO :param d: A a dict with dicts of the same type. :type d: dict :param order:The order in which the columns are printed. The order is specified by the key names of the dict. :type order: :param header: The Header of each of the columns :type header:...
2.253848
2.211755
1.019031
first_element = list(d)[0] def _keys(): return list(d[first_element]) # noinspection PyBroadException def _get(element, key): try: tmp = str(d[element][key]) except: tmp = ' ' return tmp i...
def csv(cls, d, order=None, header=None, sort_keys=True)
prints a table in csv format :param d: A a dict with dicts of the same type. :type d: dict :param order:The order in which the columns are printed. The order is specified by the key names of the dict. :type order: :param header: The Header of each of the colu...
2.789816
2.777371
1.004481
def _keys(): all_keys = [] for e in d: keys = d[e].keys() all_keys.extend(keys) return list(set(all_keys)) # noinspection PyBroadException def _get(item, key): try: tmp = str(d[item][key]) ...
def dict_table(cls, d, order=None, header=None, sort_keys=True, show_none="", max_width=40)
prints a pretty table from an dict of dicts :param d: A a dict with dicts of the same type. Each key will be a column :param order: The order in which the columns are printed. The order is specified by the key names of the dict. :param header: The Hea...
2.20965
2.133852
1.035521
if header is None: header = ["Attribute", "Value"] if output == "table": x = PrettyTable(header) if order is not None: sorted_list = order else: sorted_list = list(d) if sort_keys: sorte...
def attribute(cls, d, header=None, order=None, sort_keys=True, output="table")
prints a attribute/key value table :param d: A a dict with dicts of the same type. Each key will be a column :param order: The order in which the columns are printed. The order is specified by the key names of the dict. :param header: The Header...
2.317348
2.413861
0.960017
def dict_from_list(l): d = dict([(idx, item) for idx, item in enumerate(l)]) return d if output == 'table': x = PrettyTable(["Index", "Host"]) for (idx, item) in enumerate(l): x.add_row([idx, item]) x.ali...
def print_list(cls, l, output='table')
prints a list :param l: the list :param output: the output, default is a table :return:
2.015519
2.064374
0.976334
# header header = list(d) x = PrettyTable(labels) if order is None: order = header for key in order: value = d[key] if type(value) == list: x.add_row([key, value[0]]) for element in value[1:]: ...
def row_table(cls, d, order=None, labels=None)
prints a pretty table from data in the dict. :param d: A dict to be printed :param order: The order in which the columns are printed. The order is specified by the key names of the dict. :param labels: The array of labels for the column
2.087914
2.147658
0.972182
# TODO: why is there a tmpdir? with tempdir() as workdir: key = os.path.join(workdir, 'key.pub') with open(key, 'w') as fd: fd.write(pubkey) cmd = [ 'ssh-keygen', '-l', '-f', key, ] p = Subprocess(cmd) output...
def get_fingerprint_from_public_key(pubkey)
Generate the fingerprint of a public key :param str pubkey: the value of the public key :returns: fingerprint :rtype: str
3.503131
3.403259
1.029346
auth = cls() with open(path) as fd: for pubkey in itertools.imap(str.strip, fd): # skip empty lines if not pubkey: continue auth.add(pubkey) return auth
def load(cls, path)
load the keys from a path :param path: the filename (path) in which we find the keys :return:
4.816525
5.137063
0.937603
f = get_fingerprint_from_public_key(pubkey) if f not in self._keys: self._order[len(self._keys)] = f self._keys[f] = pubkey
def add(self, pubkey)
add a public key. :param pubkey: the filename to the public key :return:
4.295472
4.630311
0.927685
format, created = Format.objects.get_or_create(name='newman_thumb', defaults={ 'max_width': 100, 'max_height': 100, 'flexible_height': False, 'stretch': False, 'nocrop': True, }) ...
def thumb(self, obj)
Generates html and thumbnails for admin site.
4.776693
4.714796
1.013128
if not as_string: startmessage = '\nStarting analysis of %s\n' % pdbfile.split('/')[-1] else: startmessage = "Starting analysis from stdin.\n" write_message(startmessage) write_message('='*len(startmessage)+'\n') mol = PDBComplex() mol.output_path = outpath mol.load_pdb(...
def process_pdb(pdbfile, outpath, as_string=False, outputprefix='report')
Analysis of a single PDB file. Can generate textual reports XML, PyMOL session files and images as output.
5.201052
5.084146
1.022994
try: if len(inputpdbid) != 4 or extract_pdbid(inputpdbid.lower()) == 'UnknownProtein': sysexit(3, 'Invalid PDB ID (Wrong format)\n') pdbfile, pdbid = fetch_pdb(inputpdbid.lower()) pdbpath = tilde_expansion('%s/%s.pdb' % (config.BASEPATH.rstrip('/'), pdbid)) create_fo...
def download_structure(inputpdbid)
Given a PDB ID, downloads the corresponding PDB structure. Checks for validity of ID and handles error while downloading. Returns the path of the downloaded file.
5.3578
5.31273
1.008483
unique = list(set(slist)) difference = len(slist) - len(unique) if difference == 1: write_message("Removed one duplicate entry from input list.\n") if difference > 1: write_message("Removed %i duplicate entries from input list.\n" % difference) return unique
def remove_duplicates(slist)
Checks input lists for duplicates and returns a list with unique entries
3.000167
3.092954
0.970001
pdbid, pdbpath = None, None # #@todo For multiprocessing, implement better stacktracing for errors # Print title and version title = "* Protein-Ligand Interaction Profiler v%s *" % __version__ write_message('\n' + '*' * len(title) + '\n') write_message(title) write_message('\n' + '*' * ...
def main(inputstructs, inputpdbids)
Main function. Calls functions for processing, report generation and visualization.
3.679825
3.602409
1.02149
data = self.cleaned_data photo = data['photo'] if ( (data['crop_left'] > photo.width) or (data['crop_top'] > photo.height) or ((data['crop_left'] + data['crop_width']) > photo.width) or ((data['crop_top'] + data['crop_height']) > photo.hei...
def clean(self)
Validation function that checks the dimensions of the crop whether it fits into the original and the format.
2.656643
2.423647
1.096134
data = self.cleaned_data formats = Format.objects.filter(name=data['name']) if self.instance: formats = formats.exclude(pk=self.instance.pk) exists_sites = [] for f in formats: for s in f.sites.all(): if s in data['sites']: ...
def clean(self)
Check format name uniqueness for sites :return: cleaned_data
3.205411
2.755124
1.163436
"Used in admin image 'crop tool'." try: photo = get_cached_object(Photo, pk=photo) format = get_cached_object(Format, pk=format) content = { 'error': False, 'image':settings.MEDIA_URL + photo.image, 'width':photo.width, ...
def format_photo_json(self, request, photo, format)
Used in admin image 'crop tool'.
3.935493
3.114506
1.263601
self.update_model_dict() self.rc("background solid white") self.rc("setattr g display 0") # Hide all pseudobonds self.rc("~display #%i & :/isHet & ~:%s" % (self.model_dict[self.plipname], self.hetid))
def set_initial_representations(self)
Set the initial representations
33.350643
32.418709
1.028747
dct = {} models = self.chimera.openModels for md in models.list(): dct[md.name] = md.id self.model_dict = dct
def update_model_dict(self)
Updates the model dictionary
6.006602
5.730928
1.048103
atm_by_snum = {} for atom in self.model.atoms: atm_by_snum[atom.serialNumber] = atom return atm_by_snum
def atom_by_serialnumber(self)
Provides a dictionary mapping serial numbers to their atom objects.
3.183443
2.824841
1.126946
grp = self.getPseudoBondGroup("Hydrophobic Interactions-%i" % self.tid, associateWith=[self.model]) grp.lineType = self.chimera.Dash grp.lineWidth = 3 grp.color = self.colorbyname('gray') for i in self.plcomplex.hydrophobic_contacts.pairs_ids: self.bs_res_ids...
def show_hydrophobic(self)
Visualizes hydrophobic contacts.
17.34882
15.519883
1.117845
grp = self.getPseudoBondGroup("Hydrogen Bonds-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i in self.plcomplex.hbonds.ldon_id: b = grp.newPseudoBond(self.atoms[i[0]], self.atoms[i[1]]) b.color = self.colorbyname('blue') self.bs_re...
def show_hbonds(self)
Visualizes hydrogen bonds.
4.80586
4.640824
1.035562
grp = self.getPseudoBondGroup("HalogenBonds-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i in self.plcomplex.halogen_bonds: b = grp.newPseudoBond(self.atoms[i[0]], self.atoms[i[1]]) b.color = self.colorbyname('turquoise') self.bs...
def show_halogen(self)
Visualizes halogen bonds.
11.907072
10.673741
1.115548
grp = self.getPseudoBondGroup("pi-Stacking-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, stack in enumerate(self.plcomplex.pistacking): m = self.model r = m.newResidue("pseudoatoms", " ", 1, " ") ...
def show_stacking(self)
Visualizes pi-stacking interactions.
6.129849
5.711775
1.073195
grp = self.getPseudoBondGroup("Cation-Pi-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, cat in enumerate(self.plcomplex.pication): m = self.model r = m.newResidue("pseudoatoms", " ", 1, " ") ...
def show_cationpi(self)
Visualizes cation-pi interactions
6.188074
5.977813
1.035174
# Salt Bridges grp = self.getPseudoBondGroup("Salt Bridges-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 grp.lineType = self.chimera.Dash for i, sbridge in enumerate(self.plcomplex.saltbridges): m = self.model r = m.newResidue("ps...
def show_sbridges(self)
Visualizes salt bridges.
5.163919
4.981814
1.036554
grp = self.getPseudoBondGroup("Water Bridges-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i, wbridge in enumerate(self.plcomplex.waterbridges): c = grp.newPseudoBond(self.atoms[wbridge.water_id], self.atoms[wbridge.acc_id]) c.color = self.col...
def show_wbridges(self)
Visualizes water bridges
5.144268
4.949739
1.039301
grp = self.getPseudoBondGroup("Metal Coordination-%i" % self.tid, associateWith=[self.model]) grp.lineWidth = 3 for i, metal in enumerate(self.plcomplex.metal_complexes): c = grp.newPseudoBond(self.atoms[metal.metal_id], self.atoms[metal.target_id]) c.color = sel...
def show_metal(self)
Visualizes metal coordination.
10.076994
9.411375
1.070725
if not len(self.water_ids) == 0: # Hide all non-interacting water molecules water_selection = [] for wid in self.water_ids: water_selection.append('serialNumber=%i' % wid) self.rc("~display :HOH") self.rc("display :@/%s" % " o...
def cleanup(self)
Clean up the visualization.
9.041387
8.811095
1.026137
self.rc("center #%i & :%s" % (self.model_dict[self.plipname], self.hetid))
def zoom_to_ligand(self)
Centers the view on the ligand and its binding site residues.
42.846928
39.701969
1.079214
self.rc("setattr a color gray @CENTROID") self.rc("setattr a radius 0.3 @CENTROID") self.rc("represent sphere @CENTROID") self.rc("setattr a color orange @CHARGE") self.rc("setattr a radius 0.4 @CHARGE") self.rc("represent sphere @CHARGE") self.rc("displa...
def refinements(self)
Details for the visualization.
7.839466
7.829103
1.001324
"Write your forwards methods here." if not db.dry_run: for pl in orm['core.Placement'].objects.all(): pl.listing_set.update(publishable=pl.publishable) publishable = pl.publishable publishable.publish_from = pl.publish_from publ...
def forwards(self, orm)
Write your forwards methods here.
5.697133
5.416038
1.0519
if hasattr(self.image, '_getexif'): self.rotate_exif() crop_box = self.crop_to_ratio() self.resize() return self.image, crop_box
def format(self)
Crop and resize the supplied image. Return the image and the crop_box used. If the input format is JPEG and in EXIF there is information about rotation, use it and rotate resulting image.
8.692067
4.074081
2.133504
f = self.fmt if f.flexible_height and f.flexible_max_height: flexw, flexh = self.fw, f.flexible_max_height flex_ratio = float(flexw) / flexh if abs(flex_ratio - self.image_ratio) < abs(self.format_ratio - self.image_ratio): self.fh = flexh ...
def set_format(self)
Check if the format has a flexible height, if so check if the ratio of the flexible format is closer to the actual ratio of the image. If so use that instead of the default values (f.max_width, f.max_height).
5.141628
3.440133
1.494601
# check if the flexible height option is active and applies self.set_format() if self.fmt.nocrop: # cropping not allowed return if self.crop_box: # crop coordinates passed in explicitely return self.crop_box iw, ih = s...
def get_crop_box(self)
Get coordinates of the rectangle defining the new image boundaries. It takes into acount any specific wishes from the model (explicitely passed in crop_box), the desired format and it's options (flexible_height, nocrop) and mainly it's ratio. After dimensions of the format were specified...
3.787252
3.319593
1.140878
if not self.important_box: return crop_box # shortcuts ib = self.important_box cl, ct, cr, cb = crop_box iw, ih = self.image.size # compute the move of crop center onto important center move_horiz = (ib[0] + ib[2]) // 2 - (cl + cr) // 2 ...
def center_important_part(self, crop_box)
If important_box was specified, make sure it lies inside the crop box.
2.31687
2.210384
1.048175
" Get crop coordinates and perform the crop if we get any. " crop_box = self.get_crop_box() if not crop_box: return crop_box = self.center_important_part(crop_box) iw, ih = self.image.size # see if we want to crop something from outside of the image ...
def crop_to_ratio(self)
Get crop coordinates and perform the crop if we get any.
3.432797
3.117042
1.1013
f = self.fmt iw, ih = self.image.size if not f.stretch and iw <= self.fw and ih <= self.fh: return if self.image_ratio == self.format_ratio: # same ratio, just resize return (self.fw, self.fh) elif self.image_ratio < self.format_rat...
def get_resized_size(self)
Get target size for the stretched or shirnked image to fit within the target dimensions. Do not stretch images if not format.stretch. Note that this method is designed to operate on already cropped image.
3.143265
2.887981
1.088395
resized_size = self.get_resized_size() if not resized_size: return self.image = self.image.resize(resized_size, Image.ANTIALIAS)
def resize(self)
Get target size for a cropped image and do the resizing if we got anything usable.
3.194054
2.755544
1.159137
exif = self.image._getexif() or {} rotation = exif.get(TAGS['Orientation'], 1) rotations = { 6: -90, 3: -180, 8: -270, } if rotation not in rotations: return self.image = self.image.rotate(rotations[rotation])
def rotate_exif(self)
Rotate image via exif information. Only 90, 180 and 270 rotations are supported.
2.836003
2.689578
1.054442
idlist = list(set(idlist)) # Remove duplicates if not selection_exists: cmd.select(selname, 'None') # Empty selection first idchunks = [idlist[i:i+chunksize] for i in range(0, len(idlist), chunksize)] for idchunk in idchunks: cmd.select(selname, '%s or (id %s)' % (selname, '+'.joi...
def select_by_ids(selname, idlist, selection_exists=False, chunksize=20, restrict=None)
Selection with a large number of ids concatenated into a selection list can cause buffer overflow in PyMOL. This function takes a selection name and and list of IDs (list of integers) as input and makes a careful step-by-step selection (packages of 20 by default)
2.319483
2.151895
1.077879
try: ct = CONTENT_TYPE_MAPPING[ct_name] except KeyError: for model in models.get_models(): if ct_name == slugify(model._meta.verbose_name_plural): ct = ContentType.objects.get_for_model(model) CONTENT_TYPE_MAPPING[ct_name] = ct bre...
def get_content_type(ct_name)
A helper function that returns ContentType object based on its slugified verbose_name_plural. Results of this function is cached to improve performance. :Parameters: - `ct_name`: Slugified verbose_name_plural of the target model. :Exceptions: - `Http404`: if no matching ContentType is fo...
2.246647
2.22804
1.008351
def category_templates(category, incomplete_template, params): paths = [] parts = category.path.split('/') for i in reversed(range(1, len(parts) + 1)): params.update({'pth': '/'.join(parts[:i])}) paths.append(incomplete_template % params) return paths ...
def get_templates(name, slug=None, category=None, app_label=None, model_label=None)
Returns templates in following format and order: * ``'page/category/%s/content_type/%s.%s/%s/%s' % (<CATEGORY_PART>, app_label, model_label, slug, name)`` * ``'page/category/%s/content_type/%s.%s/%s' % (<CATEGORY_PART>, app_label, model_label, name)`` * ``'page/category/%s/%s' % (<CATEGORY_PART>, name)`` ...
2.153973
1.969241
1.093809
slug = publishable.slug category = publishable.category app_label = publishable.content_type.app_label model_label = publishable.content_type.model return get_templates(name, slug, category, app_label, model_label)
def get_templates_from_publishable(name, publishable)
Returns the same template list as `get_templates` but gets values from `Publishable` instance.
2.627758
2.411276
1.089779
t_list = [] if name: t_list.append('page/export/%s.html' % name) t_list.append('page/export/banner.html') try: cat = Category.objects.get_by_tree_path('') except Category.DoesNotExist: raise Http404() listing = Listing.objects.get_listing(count=count, category=cat) ...
def export(request, count, name='', content_type=None)
Export banners. :Parameters: - `count`: number of objects to pass into the template - `name`: name of the template ( page/export/banner.html is default ) - `models`: list of Model classes to include
3.834966
3.639838
1.053609
" Extract parameters for `get_templates` from the context. " if not template_name: template_name = self.template_name kw = {} if 'object' in context: o = context['object'] kw['slug'] = o.slug if context.get('content_type', False): ...
def get_templates(self, context, template_name=None)
Extract parameters for `get_templates` from the context.
3.635131
2.964647
1.22616
" Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category " year = getattr(settings, 'ARCHIVE_ENTRY_YEAR', None) if not year: n = now() try: year = Listing.objects.filter( category__site__id=sett...
def _archive_entry_year(self, category)
Return ARCHIVE_ENTRY_YEAR from settings (if exists) or year of the newest object in category
5.065922
3.338864
1.517259
if not self.width or not self.height: self.width, self.height = self.image.width, self.image.height # prefill the slug with the ID, it requires double save if not self.id: img = self.image # store dummy values first... w, h = self.width,...
def save(self, **kwargs)
Overrides models.Model.save. - Generates slug. - Saves image file.
4.998115
4.848816
1.030791
if photos_settings.DEBUG: return self.get_placeholder_img() out = { 'blank': True, 'width': self.max_width, 'height': self.max_height, 'url': photos_settings.EMPTY_IMAGE_SITE_PREFIX + 'img/empty/%s.png' % (self.name), } ...
def get_blank_img(self)
Return fake ``FormatedPhoto`` object to be used in templates when an error occurs in image generation.
5.408048
5.153828
1.049326
pars = { 'width': self.max_width, 'height': self.max_height } out = { 'placeholder': True, 'width': self.max_width, 'height': self.max_height, 'url': photos_settings.DEBUG_PLACEHOLDER_PROVIDER_TEMPLATE % pars ...
def get_placeholder_img(self)
Returns fake ``FormatedPhoto`` object grabbed from image placeholder generator service for the purpose of debugging when images are not available but we still want to see something.
4.490426
3.769634
1.19121
if self.id: for f_photo in self.formatedphoto_set.all(): f_photo.delete() super(Format, self).save(**kwargs)
def save(self, **kwargs)
Overrides models.Model.save. - Delete formatted photos if format save and not now created (because of possible changes)
7.180316
3.657134
1.963373
stretched_photo, crop_box = self._generate_img() # set crop_box to (0,0,0,0) if photo not cropped if not crop_box: crop_box = 0, 0, 0, 0 self.crop_left, self.crop_top, right, bottom = crop_box self.crop_width = right - self.crop_left self.crop_heigh...
def generate(self, save=True)
Generates photo file in current format. If ``save`` is ``True``, file is saved too.
3.860421
3.760967
1.026444
self.remove_file() if not self.image: self.generate(save=False) else: self.image.name = self.file() super(FormatedPhoto, self).save(**kwargs)
def save(self, **kwargs)
Overrides models.Model.save - Removes old file from the FS - Generates new file.
6.985986
6.166306
1.132929
if photos_settings.FORMATED_PHOTO_FILENAME is not None: return photos_settings.FORMATED_PHOTO_FILENAME(self) source_file = path.split(self.photo.image.name) return path.join(source_file[0], str(self.format.id) + '-' + source_file[1])
def file(self)
Method returns formated photo path - derived from format.id and source Photo filename
5.575099
3.409494
1.635169
''' get category from template variable or from tree_path ''' cat = template_var.resolve(context) if isinstance(cat, basestring): cat = Category.objects.get_by_tree_path(cat) return cat
def _get_category_from_pars_var(template_var, context)
get category from template variable or from tree_path
5.394299
3.020342
1.785989
bits = token.split_contents() nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() return _parse_position_tag(bits, nodelist)
def position(parser, token)
Render a given position for category. If some position is not defined for first category, position from its parent category is used unless nofallback is specified. Syntax:: {% position POSITION_NAME for CATEGORY [nofallback] %}{% endposition %} {% position POSITION_NAME for CATEGORY using ...
2.740235
4.5036
0.608454
bits = list(token.split_contents()) end_tag = 'end' + bits[0] nofallback = False if bits[-1] == 'nofallback': nofallback = True bits.pop() if len(bits) >= 4 and bits[-2] == 'for': category = template.Variable(bits.pop()) pos_names = bits[1:-1] else: ...
def ifposition(parser, token)
Syntax:: {% ifposition POSITION_NAME ... for CATEGORY [nofallback] %} {% else %} {% endifposition %}
2.476175
2.016989
1.227659
if not config.INTRA: return pairings filtered1_pairings = [p for p in pairings if (p.resnr, p.reschain) != (p.resnr_l, p.reschain_l)] already_considered = [] filtered2_pairings = [] for contact in filtered1_pairings: try: dist = 'D{}'.format(round(contact.distance, 2...
def filter_contacts(pairings)
Filter interactions by two criteria: 1. No interactions between the same residue (important for intra mode). 2. No duplicate interactions (A with B and B with A, also important for intra mode).
3.087933
2.885758
1.07006
data = namedtuple('hydroph_interaction', 'bsatom bsatom_orig_idx ligatom ligatom_orig_idx ' 'distance restype resnr reschain restype_l, resnr_l, reschain_l') pairings = [] for a, b in itertools.product(atom_set_a, atom_set_b): if a.orig_idx == b.orig...
def hydrophobic_interactions(atom_set_a, atom_set_b)
Detection of hydrophobic pliprofiler between atom_set_a (binding site) and atom_set_b (ligand). Definition: All pairs of qualified carbon atoms within a distance of HYDROPH_DIST_MAX
2.676915
2.596105
1.031128
data = namedtuple('hbond', 'a a_orig_idx d d_orig_idx h distance_ah distance_ad angle type protisdon resnr ' 'restype reschain resnr_l restype_l reschain_l sidechain atype dtype') pairings = [] for acc, don in itertools.product(acceptors, donor_pairs): if not typ ...
def hbonds(acceptors, donor_pairs, protisdon, typ)
Detection of hydrogen bonds between sets of acceptors and donor pairs. Definition: All pairs of hydrogen bond acceptor and donors with donor hydrogens and acceptor showing a distance within HBOND DIST MIN and HBOND DIST MAX and donor angles above HBOND_DON_ANGLE_MIN
2.857415
2.768798
1.032006
data = namedtuple( 'pistack', 'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l') pairings = [] for r, l in itertools.product(rings_bs, rings_lig): # DISTANCE AND RING ANGLE CALCULATION d = euclidean3d(r.center, l.center) ...
def pistacking(rings_bs, rings_lig)
Return all pi-stackings between the given aromatic ring systems in receptor and ligand.
3.098796
3.086699
1.003919
data = namedtuple( 'pication', 'ring charge distance offset type restype resnr reschain restype_l resnr_l reschain_l protcharged') pairings = [] if len(rings) == 0 or len(pos_charged) == 0: return pairings for ring in rings: c = ring.center for p in pos_charged: ...
def pication(rings, pos_charged, protcharged)
Return all pi-Cation interaction between aromatic rings and positively charged groups. For tertiary and quaternary amines, check also the angle between the ring and the nitrogen.
2.874685
2.751164
1.044898
data = namedtuple( 'saltbridge', 'positive negative distance protispos resnr restype reschain resnr_l restype_l reschain_l') pairings = [] for pc, nc in itertools.product(poscenter, negcenter): if not config.MIN_DIST < euclidean3d(pc.center, nc.center) < config.SALTBRIDGE_DIST_MAX: ...
def saltbridge(poscenter, negcenter, protispos)
Detect all salt bridges (pliprofiler between centers of positive and negative charge)
2.486015
2.448573
1.015292
data = namedtuple('halogenbond', 'acc acc_orig_idx don don_orig_idx distance don_angle acc_angle restype ' 'resnr reschain restype_l resnr_l reschain_l donortype acctype sidechain') pairings = [] for acc, don in itertools.product(acceptor, donor): dist = euc...
def halogen(acceptor, donor)
Detect all halogen bonds of the type Y-O...X-C
2.836025
2.795705
1.014422
found = tree.xpath('%s/text()' % location) if not found: return None else: data = found[0] if force_string: return data if data == 'True': return True elif data == 'False': return False else: ...
def getdata(self, tree, location, force_string=False)
Gets XML data from a specific element and handles types.
2.253089
2.179292
1.033863
return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
def getcoordinates(self, tree, location)
Gets coordinates from a specific element in PLIP XML
7.631668
6.449932
1.183217
# Atom mappings smiles_to_pdb_mapping = self.bindingsite.xpath('mappings/smiles_to_pdb/text()') if smiles_to_pdb_mapping == []: self.mappings = {'smiles_to_pdb': None, 'pdb_to_smiles': None} else: smiles_to_pdb_mapping = {int(y[0]): int(y[1]) for y in [x....
def get_atom_mapping(self)
Parses the ligand atom mapping.
2.777321
2.680603
1.036081
hbondsback = len([hb for hb in self.hbonds if not hb.sidechain]) counts = {'hydrophobics': len(self.hydrophobics), 'hbonds': len(self.hbonds), 'wbridges': len(self.wbridges), 'sbridges': len(self.sbridges), 'pistacks': len(self.pi_stacks), 'pications': len(s...
def get_counts(self)
counts the interaction types and backbone hydrogen bonding in a binding site
2.588573
2.426456
1.066812