id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
4,700
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.show_stacking
def show_stacking(self): """Visualizes pi-stacking interactions.""" 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, " ") centroid_prot = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.proteinring_center centroid_prot.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_prot) centroid_lig = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.ligandring_center centroid_lig.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_lig) b = grp.newPseudoBond(centroid_lig, centroid_prot) b.color = self.colorbyname('forest green') self.bs_res_ids += stack.proteinring_atoms
python
def show_stacking(self): 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, " ") centroid_prot = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.proteinring_center centroid_prot.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_prot) centroid_lig = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = stack.ligandring_center centroid_lig.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid_lig) b = grp.newPseudoBond(centroid_lig, centroid_prot) b.color = self.colorbyname('forest green') self.bs_res_ids += stack.proteinring_atoms
[ "def", "show_stacking", "(", "self", ")", ":", "grp", "=", "self", ".", "getPseudoBondGroup", "(", "\"pi-Stacking-%i\"", "%", "self", ".", "tid", ",", "associateWith", "=", "[", "self", ".", "model", "]", ")", "grp", ".", "lineWidth", "=", "3", "grp", ...
Visualizes pi-stacking interactions.
[ "Visualizes", "pi", "-", "stacking", "interactions", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L90-L112
4,701
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.show_cationpi
def show_cationpi(self): """Visualizes cation-pi interactions""" 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, " ") chargecenter = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = cat.charge_center chargecenter.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter) centroid = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = cat.ring_center centroid.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid) b = grp.newPseudoBond(centroid, chargecenter) b.color = self.colorbyname('orange') if cat.protcharged: self.bs_res_ids += cat.charge_atoms else: self.bs_res_ids += cat.ring_atoms
python
def show_cationpi(self): 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, " ") chargecenter = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = cat.charge_center chargecenter.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter) centroid = m.newAtom("CENTROID", self.chimera.Element("CENTROID")) x, y, z = cat.ring_center centroid.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(centroid) b = grp.newPseudoBond(centroid, chargecenter) b.color = self.colorbyname('orange') if cat.protcharged: self.bs_res_ids += cat.charge_atoms else: self.bs_res_ids += cat.ring_atoms
[ "def", "show_cationpi", "(", "self", ")", ":", "grp", "=", "self", ".", "getPseudoBondGroup", "(", "\"Cation-Pi-%i\"", "%", "self", ".", "tid", ",", "associateWith", "=", "[", "self", ".", "model", "]", ")", "grp", ".", "lineWidth", "=", "3", "grp", "....
Visualizes cation-pi interactions
[ "Visualizes", "cation", "-", "pi", "interactions" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L114-L139
4,702
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.show_sbridges
def show_sbridges(self): """Visualizes salt bridges.""" # 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("pseudoatoms", " ", 1, " ") chargecenter1 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.positive_center chargecenter1.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter1) chargecenter2 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.negative_center chargecenter2.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter2) b = grp.newPseudoBond(chargecenter1, chargecenter2) b.color = self.colorbyname('yellow') if sbridge.protispos: self.bs_res_ids += sbridge.positive_atoms else: self.bs_res_ids += sbridge.negative_atoms
python
def show_sbridges(self): # 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("pseudoatoms", " ", 1, " ") chargecenter1 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.positive_center chargecenter1.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter1) chargecenter2 = m.newAtom("CHARGE", self.chimera.Element("CHARGE")) x, y, z = sbridge.negative_center chargecenter2.setCoord(self.chimera.Coord(x, y, z)) r.addAtom(chargecenter2) b = grp.newPseudoBond(chargecenter1, chargecenter2) b.color = self.colorbyname('yellow') if sbridge.protispos: self.bs_res_ids += sbridge.positive_atoms else: self.bs_res_ids += sbridge.negative_atoms
[ "def", "show_sbridges", "(", "self", ")", ":", "# Salt Bridges", "grp", "=", "self", ".", "getPseudoBondGroup", "(", "\"Salt Bridges-%i\"", "%", "self", ".", "tid", ",", "associateWith", "=", "[", "self", ".", "model", "]", ")", "grp", ".", "lineWidth", "=...
Visualizes salt bridges.
[ "Visualizes", "salt", "bridges", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L141-L167
4,703
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.show_wbridges
def show_wbridges(self): """Visualizes water bridges""" 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.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) b = grp.newPseudoBond(self.atoms[wbridge.don_id], self.atoms[wbridge.water_id]) b.color = self.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) if wbridge.protisdon: self.bs_res_ids.append(wbridge.don_id) else: self.bs_res_ids.append(wbridge.acc_id)
python
def show_wbridges(self): 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.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) b = grp.newPseudoBond(self.atoms[wbridge.don_id], self.atoms[wbridge.water_id]) b.color = self.colorbyname('cornflower blue') self.water_ids.append(wbridge.water_id) if wbridge.protisdon: self.bs_res_ids.append(wbridge.don_id) else: self.bs_res_ids.append(wbridge.acc_id)
[ "def", "show_wbridges", "(", "self", ")", ":", "grp", "=", "self", ".", "getPseudoBondGroup", "(", "\"Water Bridges-%i\"", "%", "self", ".", "tid", ",", "associateWith", "=", "[", "self", ".", "model", "]", ")", "grp", ".", "lineWidth", "=", "3", "for", ...
Visualizes water bridges
[ "Visualizes", "water", "bridges" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L169-L183
4,704
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.show_metal
def show_metal(self): """Visualizes metal coordination.""" 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 = self.colorbyname('magenta') if metal.location == 'water': self.water_ids.append(metal.target_id) if metal.location.startswith('protein'): self.bs_res_ids.append(metal.target_id)
python
def show_metal(self): 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 = self.colorbyname('magenta') if metal.location == 'water': self.water_ids.append(metal.target_id) if metal.location.startswith('protein'): self.bs_res_ids.append(metal.target_id)
[ "def", "show_metal", "(", "self", ")", ":", "grp", "=", "self", ".", "getPseudoBondGroup", "(", "\"Metal Coordination-%i\"", "%", "self", ".", "tid", ",", "associateWith", "=", "[", "self", ".", "model", "]", ")", "grp", ".", "lineWidth", "=", "3", "for"...
Visualizes metal coordination.
[ "Visualizes", "metal", "coordination", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L185-L197
4,705
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.cleanup
def cleanup(self): """Clean up the visualization.""" 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" % " or ".join(water_selection)) # Show all interacting binding site residues self.rc("~display #%i & ~:/isHet" % self.model_dict[self.plipname]) self.rc("display :%s" % ",".join([str(self.atoms[bsid].residue.id) for bsid in self.bs_res_ids])) self.rc("color lightblue :HOH")
python
def cleanup(self): 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" % " or ".join(water_selection)) # Show all interacting binding site residues self.rc("~display #%i & ~:/isHet" % self.model_dict[self.plipname]) self.rc("display :%s" % ",".join([str(self.atoms[bsid].residue.id) for bsid in self.bs_res_ids])) self.rc("color lightblue :HOH")
[ "def", "cleanup", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "water_ids", ")", "==", "0", ":", "# Hide all non-interacting water molecules", "water_selection", "=", "[", "]", "for", "wid", "in", "self", ".", "water_ids", ":", "water_selecti...
Clean up the visualization.
[ "Clean", "up", "the", "visualization", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L199-L213
4,706
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.zoom_to_ligand
def zoom_to_ligand(self): """Centers the view on the ligand and its binding site residues.""" self.rc("center #%i & :%s" % (self.model_dict[self.plipname], self.hetid))
python
def zoom_to_ligand(self): self.rc("center #%i & :%s" % (self.model_dict[self.plipname], self.hetid))
[ "def", "zoom_to_ligand", "(", "self", ")", ":", "self", ".", "rc", "(", "\"center #%i & :%s\"", "%", "(", "self", ".", "model_dict", "[", "self", ".", "plipname", "]", ",", "self", ".", "hetid", ")", ")" ]
Centers the view on the ligand and its binding site residues.
[ "Centers", "the", "view", "on", "the", "ligand", "and", "its", "binding", "site", "residues", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L215-L217
4,707
ssalentin/plip
plip/modules/chimeraplip.py
ChimeraVisualizer.refinements
def refinements(self): """Details for the visualization.""" 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("display :pseudoatoms")
python
def refinements(self): 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("display :pseudoatoms")
[ "def", "refinements", "(", "self", ")", ":", "self", ".", "rc", "(", "\"setattr a color gray @CENTROID\"", ")", "self", ".", "rc", "(", "\"setattr a radius 0.3 @CENTROID\"", ")", "self", ".", "rc", "(", "\"represent sphere @CENTROID\"", ")", "self", ".", "rc", "...
Details for the visualization.
[ "Details", "for", "the", "visualization", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/chimeraplip.py#L219-L227
4,708
ella/ella
ella/photos/formatter.py
Formatter.format
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. """ if hasattr(self.image, '_getexif'): self.rotate_exif() crop_box = self.crop_to_ratio() self.resize() return self.image, crop_box
python
def format(self): if hasattr(self.image, '_getexif'): self.rotate_exif() crop_box = self.crop_to_ratio() self.resize() return self.image, crop_box
[ "def", "format", "(", "self", ")", ":", "if", "hasattr", "(", "self", ".", "image", ",", "'_getexif'", ")", ":", "self", ".", "rotate_exif", "(", ")", "crop_box", "=", "self", ".", "crop_to_ratio", "(", ")", "self", ".", "resize", "(", ")", "return",...
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.
[ "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", ...
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L22-L31
4,709
ella/ella
ella/photos/formatter.py
Formatter.center_important_part
def center_important_part(self, crop_box): """ If important_box was specified, make sure it lies inside the crop box. """ 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 move_verti = (ib[1] + ib[3]) // 2 - (ct + cb) // 2 # make sure we don't get out of the image # ... horizontaly if move_horiz > 0: move_horiz = min(iw - cr, move_horiz) else: move_horiz = max(-cl, move_horiz) # .. and verticaly if move_verti > 0: move_verti = min(ih - cb, move_verti) else: move_verti = max(-ct, move_verti) # move the crop_box return (cl + move_horiz, ct + move_verti, cr + move_horiz, cb + move_verti)
python
def center_important_part(self, crop_box): 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 move_verti = (ib[1] + ib[3]) // 2 - (ct + cb) // 2 # make sure we don't get out of the image # ... horizontaly if move_horiz > 0: move_horiz = min(iw - cr, move_horiz) else: move_horiz = max(-cl, move_horiz) # .. and verticaly if move_verti > 0: move_verti = min(ih - cb, move_verti) else: move_verti = max(-ct, move_verti) # move the crop_box return (cl + move_horiz, ct + move_verti, cr + move_horiz, cb + move_verti)
[ "def", "center_important_part", "(", "self", ",", "crop_box", ")", ":", "if", "not", "self", ".", "important_box", ":", "return", "crop_box", "# shortcuts", "ib", "=", "self", ".", "important_box", "cl", ",", "ct", ",", "cr", ",", "cb", "=", "crop_box", ...
If important_box was specified, make sure it lies inside the crop box.
[ "If", "important_box", "was", "specified", "make", "sure", "it", "lies", "inside", "the", "crop", "box", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L91-L121
4,710
ella/ella
ella/photos/formatter.py
Formatter.crop_to_ratio
def crop_to_ratio(self): " 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 out_of_photo = min(crop_box[0], crop_box[1]) < 0 or crop_box[2] > iw or crop_box[3] > ih # check whether there's transparent information in the image transparent = self.image.mode in ('RGBA', 'LA') if photos_settings.DEFAULT_BG_COLOR != 'black' and out_of_photo and not transparent: # if we do, just crop the image to the portion that will be visible updated_crop_box = ( max(0, crop_box[0]), max(0, crop_box[1]), min(iw, crop_box[2]), min(ih, crop_box[3]), ) cropped = self.image.crop(updated_crop_box) # create new image of the proper size and color self.image = Image.new('RGB', (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), photos_settings.DEFAULT_BG_COLOR) # and paste the cropped part into it's proper position self.image.paste(cropped, (abs(min(crop_box[0], 0)), abs(min(crop_box[1], 0)))) else: # crop normally if not the case self.image = self.image.crop(crop_box) return crop_box
python
def crop_to_ratio(self): " 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 out_of_photo = min(crop_box[0], crop_box[1]) < 0 or crop_box[2] > iw or crop_box[3] > ih # check whether there's transparent information in the image transparent = self.image.mode in ('RGBA', 'LA') if photos_settings.DEFAULT_BG_COLOR != 'black' and out_of_photo and not transparent: # if we do, just crop the image to the portion that will be visible updated_crop_box = ( max(0, crop_box[0]), max(0, crop_box[1]), min(iw, crop_box[2]), min(ih, crop_box[3]), ) cropped = self.image.crop(updated_crop_box) # create new image of the proper size and color self.image = Image.new('RGB', (crop_box[2] - crop_box[0], crop_box[3] - crop_box[1]), photos_settings.DEFAULT_BG_COLOR) # and paste the cropped part into it's proper position self.image.paste(cropped, (abs(min(crop_box[0], 0)), abs(min(crop_box[1], 0)))) else: # crop normally if not the case self.image = self.image.crop(crop_box) return crop_box
[ "def", "crop_to_ratio", "(", "self", ")", ":", "crop_box", "=", "self", ".", "get_crop_box", "(", ")", "if", "not", "crop_box", ":", "return", "crop_box", "=", "self", ".", "center_important_part", "(", "crop_box", ")", "iw", ",", "ih", "=", "self", ".",...
Get crop coordinates and perform the crop if we get any.
[ "Get", "crop", "coordinates", "and", "perform", "the", "crop", "if", "we", "get", "any", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L124-L153
4,711
ella/ella
ella/photos/formatter.py
Formatter.get_resized_size
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. """ 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_ratio: # image taller than format return (self.fh * iw / ih, self.fh) else: # self.image_ratio > self.format_ratio # image wider than format return (self.fw, self.fw * ih / iw)
python
def get_resized_size(self): 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_ratio: # image taller than format return (self.fh * iw / ih, self.fh) else: # self.image_ratio > self.format_ratio # image wider than format return (self.fw, self.fw * ih / iw)
[ "def", "get_resized_size", "(", "self", ")", ":", "f", "=", "self", ".", "fmt", "iw", ",", "ih", "=", "self", ".", "image", ".", "size", "if", "not", "f", ".", "stretch", "and", "iw", "<=", "self", ".", "fw", "and", "ih", "<=", "self", ".", "fh...
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.
[ "Get", "target", "size", "for", "the", "stretched", "or", "shirnked", "image", "to", "fit", "within", "the", "target", "dimensions", ".", "Do", "not", "stretch", "images", "if", "not", "format", ".", "stretch", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L155-L178
4,712
ella/ella
ella/photos/formatter.py
Formatter.resize
def resize(self): """ Get target size for a cropped image and do the resizing if we got anything usable. """ resized_size = self.get_resized_size() if not resized_size: return self.image = self.image.resize(resized_size, Image.ANTIALIAS)
python
def resize(self): resized_size = self.get_resized_size() if not resized_size: return self.image = self.image.resize(resized_size, Image.ANTIALIAS)
[ "def", "resize", "(", "self", ")", ":", "resized_size", "=", "self", ".", "get_resized_size", "(", ")", "if", "not", "resized_size", ":", "return", "self", ".", "image", "=", "self", ".", "image", ".", "resize", "(", "resized_size", ",", "Image", ".", ...
Get target size for a cropped image and do the resizing if we got anything usable.
[ "Get", "target", "size", "for", "a", "cropped", "image", "and", "do", "the", "resizing", "if", "we", "got", "anything", "usable", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L180-L189
4,713
ella/ella
ella/photos/formatter.py
Formatter.rotate_exif
def rotate_exif(self): """ Rotate image via exif information. Only 90, 180 and 270 rotations are supported. """ 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])
python
def rotate_exif(self): 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", ")", ":", "exif", "=", "self", ".", "image", ".", "_getexif", "(", ")", "or", "{", "}", "rotation", "=", "exif", ".", "get", "(", "TAGS", "[", "'Orientation'", "]", ",", "1", ")", "rotations", "=", "{", "6", ":"...
Rotate image via exif information. Only 90, 180 and 270 rotations are supported.
[ "Rotate", "image", "via", "exif", "information", ".", "Only", "90", "180", "and", "270", "rotations", "are", "supported", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/formatter.py#L191-L207
4,714
ella/ella
ella/core/views.py
get_content_type
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 found """ 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 break else: raise Http404 return ct
python
def get_content_type(ct_name): 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 break else: raise Http404 return ct
[ "def", "get_content_type", "(", "ct_name", ")", ":", "try", ":", "ct", "=", "CONTENT_TYPE_MAPPING", "[", "ct_name", "]", "except", "KeyError", ":", "for", "model", "in", "models", ".", "get_models", "(", ")", ":", "if", "ct_name", "==", "slugify", "(", "...
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 found
[ "A", "helper", "function", "that", "returns", "ContentType", "object", "based", "on", "its", "slugified", "verbose_name_plural", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/views.py#L423-L445
4,715
ella/ella
ella/core/views.py
get_templates_from_publishable
def get_templates_from_publishable(name, publishable): """ Returns the same template list as `get_templates` but gets values from `Publishable` instance. """ 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)
python
def get_templates_from_publishable(name, publishable): 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", ")", ":", "slug", "=", "publishable", ".", "slug", "category", "=", "publishable", ".", "category", "app_label", "=", "publishable", ".", "content_type", ".", "app_label", "model_label", "="...
Returns the same template list as `get_templates` but gets values from `Publishable` instance.
[ "Returns", "the", "same", "template", "list", "as", "get_templates", "but", "gets", "values", "from", "Publishable", "instance", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/views.py#L521-L529
4,716
ella/ella
ella/core/views.py
export
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 """ 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) return render( request, t_list, { 'category' : cat, 'listing' : listing }, content_type=content_type )
python
def export(request, count, name='', content_type=None): 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) return render( request, t_list, { 'category' : cat, 'listing' : listing }, content_type=content_type )
[ "def", "export", "(", "request", ",", "count", ",", "name", "=", "''", ",", "content_type", "=", "None", ")", ":", "t_list", "=", "[", "]", "if", "name", ":", "t_list", ".", "append", "(", "'page/export/%s.html'", "%", "name", ")", "t_list", ".", "ap...
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
[ "Export", "banners", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/views.py#L538-L562
4,717
ella/ella
ella/core/views.py
EllaCoreView.get_templates
def get_templates(self, context, template_name=None): " 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): ct = context['content_type'] kw['app_label'] = ct.app_label kw['model_label'] = ct.model return get_templates(template_name, category=context['category'], **kw)
python
def get_templates(self, context, template_name=None): " 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): ct = context['content_type'] kw['app_label'] = ct.app_label kw['model_label'] = ct.model return get_templates(template_name, category=context['category'], **kw)
[ "def", "get_templates", "(", "self", ",", "context", ",", "template_name", "=", "None", ")", ":", "if", "not", "template_name", ":", "template_name", "=", "self", ".", "template_name", "kw", "=", "{", "}", "if", "'object'", "in", "context", ":", "o", "="...
Extract parameters for `get_templates` from the context.
[ "Extract", "parameters", "for", "get_templates", "from", "the", "context", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/views.py#L82-L97
4,718
ella/ella
ella/photos/models.py
Format.get_blank_img
def get_blank_img(self): """ Return fake ``FormatedPhoto`` object to be used in templates when an error occurs in image generation. """ 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), } return out
python
def get_blank_img(self): 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), } return out
[ "def", "get_blank_img", "(", "self", ")", ":", "if", "photos_settings", ".", "DEBUG", ":", "return", "self", ".", "get_placeholder_img", "(", ")", "out", "=", "{", "'blank'", ":", "True", ",", "'width'", ":", "self", ".", "max_width", ",", "'height'", ":...
Return fake ``FormatedPhoto`` object to be used in templates when an error occurs in image generation.
[ "Return", "fake", "FormatedPhoto", "object", "to", "be", "used", "in", "templates", "when", "an", "error", "occurs", "in", "image", "generation", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/models.py#L216-L230
4,719
ella/ella
ella/photos/models.py
Format.get_placeholder_img
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. """ 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 } return out
python
def get_placeholder_img(self): 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 } return out
[ "def", "get_placeholder_img", "(", "self", ")", ":", "pars", "=", "{", "'width'", ":", "self", ".", "max_width", ",", "'height'", ":", "self", ".", "max_height", "}", "out", "=", "{", "'placeholder'", ":", "True", ",", "'width'", ":", "self", ".", "max...
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.
[ "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", "." ...
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/models.py#L232-L248
4,720
ella/ella
ella/photos/models.py
FormatedPhoto.generate
def generate(self, save=True): """ Generates photo file in current format. If ``save`` is ``True``, file is saved too. """ 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_height = bottom - self.crop_top self.width, self.height = stretched_photo.size f = StringIO() imgf = (self.photo._get_image().format or Image.EXTENSION[path.splitext(self.photo.image.name)[1]]) stretched_photo.save(f, format=imgf, quality=self.format.resample_quality) f.seek(0) self.image.save(self.file(), ContentFile(f.read()), save)
python
def generate(self, save=True): 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_height = bottom - self.crop_top self.width, self.height = stretched_photo.size f = StringIO() imgf = (self.photo._get_image().format or Image.EXTENSION[path.splitext(self.photo.image.name)[1]]) stretched_photo.save(f, format=imgf, quality=self.format.resample_quality) f.seek(0) self.image.save(self.file(), ContentFile(f.read()), save)
[ "def", "generate", "(", "self", ",", "save", "=", "True", ")", ":", "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...
Generates photo file in current format. If ``save`` is ``True``, file is saved too.
[ "Generates", "photo", "file", "in", "current", "format", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/models.py#L375-L400
4,721
ella/ella
ella/photos/models.py
FormatedPhoto.save
def save(self, **kwargs): """Overrides models.Model.save - Removes old file from the FS - Generates new file. """ self.remove_file() if not self.image: self.generate(save=False) else: self.image.name = self.file() super(FormatedPhoto, self).save(**kwargs)
python
def save(self, **kwargs): 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", ")", ":", "self", ".", "remove_file", "(", ")", "if", "not", "self", ".", "image", ":", "self", ".", "generate", "(", "save", "=", "False", ")", "else", ":", "self", ".", "image", ".", "name", ...
Overrides models.Model.save - Removes old file from the FS - Generates new file.
[ "Overrides", "models", ".", "Model", ".", "save" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/models.py#L402-L413
4,722
ella/ella
ella/photos/models.py
FormatedPhoto.file
def file(self): """ Method returns formated photo path - derived from format.id and source Photo filename """ 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])
python
def file(self): 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", ")", ":", "if", "photos_settings", ".", "FORMATED_PHOTO_FILENAME", "is", "not", "None", ":", "return", "photos_settings", ".", "FORMATED_PHOTO_FILENAME", "(", "self", ")", "source_file", "=", "path", ".", "split", "(", "self", ".", ...
Method returns formated photo path - derived from format.id and source Photo filename
[ "Method", "returns", "formated", "photo", "path", "-", "derived", "from", "format", ".", "id", "and", "source", "Photo", "filename" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/photos/models.py#L427-L432
4,723
ella/ella
ella/positions/templatetags/positions.py
_get_category_from_pars_var
def _get_category_from_pars_var(template_var, context): ''' 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
python
def _get_category_from_pars_var(template_var, context): ''' 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", ")", ":", "cat", "=", "template_var", ".", "resolve", "(", "context", ")", "if", "isinstance", "(", "cat", ",", "basestring", ")", ":", "cat", "=", "Category", ".", "objects", ".", ...
get category from template variable or from tree_path
[ "get", "category", "from", "template", "variable", "or", "from", "tree_path" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/positions/templatetags/positions.py#L11-L18
4,724
ella/ella
ella/positions/templatetags/positions.py
position
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 BOX_TYPE [nofallback] %}{% endposition %} Example usage:: {% position top_left for category %}{% endposition %} """ bits = token.split_contents() nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() return _parse_position_tag(bits, nodelist)
python
def position(parser, token): bits = token.split_contents() nodelist = parser.parse(('end' + bits[0],)) parser.delete_first_token() return _parse_position_tag(bits, nodelist)
[ "def", "position", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "nodelist", "=", "parser", ".", "parse", "(", "(", "'end'", "+", "bits", "[", "0", "]", ",", ")", ")", "parser", ".", "delete_first_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 BOX_TYPE [nofallback] %}{% endposition %} Example usage:: {% position top_left for category %}{% endposition %}
[ "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", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/positions/templatetags/positions.py#L22-L40
4,725
ssalentin/plip
plip/modules/detection.py
pistacking
def pistacking(rings_bs, rings_lig): """Return all pi-stackings between the given aromatic ring systems in receptor and ligand.""" 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) b = vecangle(r.normal, l.normal) a = min(b, 180 - b if not 180 - b < 0 else b) # Smallest of two angles, depending on direction of normal # RING CENTER OFFSET CALCULATION (project each ring center into the other ring) proj1 = projection(l.normal, l.center, r.center) proj2 = projection(r.normal, r.center, l.center) offset = min(euclidean3d(proj1, l.center), euclidean3d(proj2, r.center)) # RECEPTOR DATA resnr, restype, reschain = whichresnumber(r.atoms[0]), whichrestype(r.atoms[0]), whichchain(r.atoms[0]) resnr_l, restype_l, reschain_l = whichresnumber(l.orig_atoms[0]), whichrestype( l.orig_atoms[0]), whichchain(l.orig_atoms[0]) # SELECTION BY DISTANCE, ANGLE AND OFFSET passed = False if not config.MIN_DIST < d < config.PISTACK_DIST_MAX: continue if 0 < a < config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'P' passed = True if 90 - config.PISTACK_ANG_DEV < a < 90 + config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'T' passed = True if passed: contact = data(proteinring=r, ligandring=l, distance=d, angle=a, offset=offset, type=ptype, resnr=resnr, restype=restype, reschain=reschain, resnr_l=resnr_l, restype_l=restype_l, reschain_l=reschain_l) pairings.append(contact) return filter_contacts(pairings)
python
def pistacking(rings_bs, rings_lig): 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) b = vecangle(r.normal, l.normal) a = min(b, 180 - b if not 180 - b < 0 else b) # Smallest of two angles, depending on direction of normal # RING CENTER OFFSET CALCULATION (project each ring center into the other ring) proj1 = projection(l.normal, l.center, r.center) proj2 = projection(r.normal, r.center, l.center) offset = min(euclidean3d(proj1, l.center), euclidean3d(proj2, r.center)) # RECEPTOR DATA resnr, restype, reschain = whichresnumber(r.atoms[0]), whichrestype(r.atoms[0]), whichchain(r.atoms[0]) resnr_l, restype_l, reschain_l = whichresnumber(l.orig_atoms[0]), whichrestype( l.orig_atoms[0]), whichchain(l.orig_atoms[0]) # SELECTION BY DISTANCE, ANGLE AND OFFSET passed = False if not config.MIN_DIST < d < config.PISTACK_DIST_MAX: continue if 0 < a < config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'P' passed = True if 90 - config.PISTACK_ANG_DEV < a < 90 + config.PISTACK_ANG_DEV and offset < config.PISTACK_OFFSET_MAX: ptype = 'T' passed = True if passed: contact = data(proteinring=r, ligandring=l, distance=d, angle=a, offset=offset, type=ptype, resnr=resnr, restype=restype, reschain=reschain, resnr_l=resnr_l, restype_l=restype_l, reschain_l=reschain_l) pairings.append(contact) return filter_contacts(pairings)
[ "def", "pistacking", "(", "rings_bs", ",", "rings_lig", ")", ":", "data", "=", "namedtuple", "(", "'pistack'", ",", "'proteinring ligandring distance angle offset type restype resnr reschain restype_l resnr_l reschain_l'", ")", "pairings", "=", "[", "]", "for", "r", ",", ...
Return all pi-stackings between the given aromatic ring systems in receptor and ligand.
[ "Return", "all", "pi", "-", "stackings", "between", "the", "given", "aromatic", "ring", "systems", "in", "receptor", "and", "ligand", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/detection.py#L120-L156
4,726
ssalentin/plip
plip/modules/detection.py
halogen
def halogen(acceptor, donor): """Detect all halogen bonds of the type Y-O...X-C""" 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 = euclidean3d(acc.o.coords, don.x.coords) if not config.MIN_DIST < dist < config.HALOGEN_DIST_MAX: continue vec1, vec2 = vector(acc.o.coords, acc.y.coords), vector(acc.o.coords, don.x.coords) vec3, vec4 = vector(don.x.coords, acc.o.coords), vector(don.x.coords, don.c.coords) acc_angle, don_angle = vecangle(vec1, vec2), vecangle(vec3, vec4) is_sidechain_hal = acc.o.OBAtom.GetResidue().GetAtomProperty(acc.o.OBAtom, 8) # Check if sidechain atom if not config.HALOGEN_ACC_ANGLE - config.HALOGEN_ANGLE_DEV < acc_angle \ < config.HALOGEN_ACC_ANGLE + config.HALOGEN_ANGLE_DEV: continue if not config.HALOGEN_DON_ANGLE - config.HALOGEN_ANGLE_DEV < don_angle \ < config.HALOGEN_DON_ANGLE + config.HALOGEN_ANGLE_DEV: continue restype, reschain, resnr = whichrestype(acc.o), whichchain(acc.o), whichresnumber(acc.o) restype_l, reschain_l, resnr_l = whichrestype(don.orig_x), whichchain(don.orig_x), whichresnumber(don.orig_x) contact = data(acc=acc, acc_orig_idx=acc.o_orig_idx, don=don, don_orig_idx=don.x_orig_idx, distance=dist, don_angle=don_angle, acc_angle=acc_angle, restype=restype, resnr=resnr, reschain=reschain, restype_l=restype_l, reschain_l=reschain_l, resnr_l=resnr_l, donortype=don.x.OBAtom.GetType(), acctype=acc.o.type, sidechain=is_sidechain_hal) pairings.append(contact) return filter_contacts(pairings)
python
def halogen(acceptor, donor): 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 = euclidean3d(acc.o.coords, don.x.coords) if not config.MIN_DIST < dist < config.HALOGEN_DIST_MAX: continue vec1, vec2 = vector(acc.o.coords, acc.y.coords), vector(acc.o.coords, don.x.coords) vec3, vec4 = vector(don.x.coords, acc.o.coords), vector(don.x.coords, don.c.coords) acc_angle, don_angle = vecangle(vec1, vec2), vecangle(vec3, vec4) is_sidechain_hal = acc.o.OBAtom.GetResidue().GetAtomProperty(acc.o.OBAtom, 8) # Check if sidechain atom if not config.HALOGEN_ACC_ANGLE - config.HALOGEN_ANGLE_DEV < acc_angle \ < config.HALOGEN_ACC_ANGLE + config.HALOGEN_ANGLE_DEV: continue if not config.HALOGEN_DON_ANGLE - config.HALOGEN_ANGLE_DEV < don_angle \ < config.HALOGEN_DON_ANGLE + config.HALOGEN_ANGLE_DEV: continue restype, reschain, resnr = whichrestype(acc.o), whichchain(acc.o), whichresnumber(acc.o) restype_l, reschain_l, resnr_l = whichrestype(don.orig_x), whichchain(don.orig_x), whichresnumber(don.orig_x) contact = data(acc=acc, acc_orig_idx=acc.o_orig_idx, don=don, don_orig_idx=don.x_orig_idx, distance=dist, don_angle=don_angle, acc_angle=acc_angle, restype=restype, resnr=resnr, reschain=reschain, restype_l=restype_l, reschain_l=reschain_l, resnr_l=resnr_l, donortype=don.x.OBAtom.GetType(), acctype=acc.o.type, sidechain=is_sidechain_hal) pairings.append(contact) return filter_contacts(pairings)
[ "def", "halogen", "(", "acceptor", ",", "donor", ")", ":", "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"...
Detect all halogen bonds of the type Y-O...X-C
[ "Detect", "all", "halogen", "bonds", "of", "the", "type", "Y", "-", "O", "...", "X", "-", "C" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/detection.py#L232-L260
4,727
ssalentin/plip
plip/modules/plipxml.py
XMLStorage.getdata
def getdata(self, tree, location, force_string=False): """Gets XML data from a specific element and handles types.""" 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: try: return int(data) except ValueError: try: return float(data) except ValueError: # It's a string return data
python
def getdata(self, tree, location, force_string=False): 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: try: return int(data) except ValueError: try: return float(data) except ValueError: # It's a string return data
[ "def", "getdata", "(", "self", ",", "tree", ",", "location", ",", "force_string", "=", "False", ")", ":", "found", "=", "tree", ".", "xpath", "(", "'%s/text()'", "%", "location", ")", "if", "not", "found", ":", "return", "None", "else", ":", "data", ...
Gets XML data from a specific element and handles types.
[ "Gets", "XML", "data", "from", "a", "specific", "element", "and", "handles", "types", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L18-L39
4,728
ssalentin/plip
plip/modules/plipxml.py
XMLStorage.getcoordinates
def getcoordinates(self, tree, location): """Gets coordinates from a specific element in PLIP XML""" return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
python
def getcoordinates(self, tree, location): return tuple(float(x) for x in tree.xpath('.//%s/*/text()' % location))
[ "def", "getcoordinates", "(", "self", ",", "tree", ",", "location", ")", ":", "return", "tuple", "(", "float", "(", "x", ")", "for", "x", "in", "tree", ".", "xpath", "(", "'.//%s/*/text()'", "%", "location", ")", ")" ]
Gets coordinates from a specific element in PLIP XML
[ "Gets", "coordinates", "from", "a", "specific", "element", "in", "PLIP", "XML" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L41-L43
4,729
ssalentin/plip
plip/modules/plipxml.py
BSite.get_atom_mapping
def get_atom_mapping(self): """Parses the ligand atom mapping.""" # 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.split(':') for x in smiles_to_pdb_mapping[0].split(',')]} self.mappings = {'smiles_to_pdb': smiles_to_pdb_mapping} self.mappings['pdb_to_smiles'] = {v: k for k, v in self.mappings['smiles_to_pdb'].items()}
python
def get_atom_mapping(self): # 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.split(':') for x in smiles_to_pdb_mapping[0].split(',')]} self.mappings = {'smiles_to_pdb': smiles_to_pdb_mapping} self.mappings['pdb_to_smiles'] = {v: k for k, v in self.mappings['smiles_to_pdb'].items()}
[ "def", "get_atom_mapping", "(", "self", ")", ":", "# Atom mappings", "smiles_to_pdb_mapping", "=", "self", ".", "bindingsite", ".", "xpath", "(", "'mappings/smiles_to_pdb/text()'", ")", "if", "smiles_to_pdb_mapping", "==", "[", "]", ":", "self", ".", "mappings", "...
Parses the ligand atom mapping.
[ "Parses", "the", "ligand", "atom", "mapping", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L249-L259
4,730
ssalentin/plip
plip/modules/plipxml.py
BSite.get_counts
def get_counts(self): """counts the interaction types and backbone hydrogen bonding in a binding site""" 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(self.pi_cations), 'halogens': len(self.halogens), 'metal': len(self.metal_complexes), 'hbond_back': hbondsback, 'hbond_nonback': (len(self.hbonds) - hbondsback)} counts['total'] = counts['hydrophobics'] + counts['hbonds'] + counts['wbridges'] + \ counts['sbridges'] + counts['pistacks'] + counts['pications'] + counts['halogens'] + counts['metal'] return counts
python
def get_counts(self): 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(self.pi_cations), 'halogens': len(self.halogens), 'metal': len(self.metal_complexes), 'hbond_back': hbondsback, 'hbond_nonback': (len(self.hbonds) - hbondsback)} counts['total'] = counts['hydrophobics'] + counts['hbonds'] + counts['wbridges'] + \ counts['sbridges'] + counts['pistacks'] + counts['pications'] + counts['halogens'] + counts['metal'] return counts
[ "def", "get_counts", "(", "self", ")", ":", "hbondsback", "=", "len", "(", "[", "hb", "for", "hb", "in", "self", ".", "hbonds", "if", "not", "hb", ".", "sidechain", "]", ")", "counts", "=", "{", "'hydrophobics'", ":", "len", "(", "self", ".", "hydr...
counts the interaction types and backbone hydrogen bonding in a binding site
[ "counts", "the", "interaction", "types", "and", "backbone", "hydrogen", "bonding", "in", "a", "binding", "site" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L261-L271
4,731
ssalentin/plip
plip/modules/plipxml.py
PLIPXMLREST.load_data
def load_data(self, pdbid): """Loads and parses an XML resource and saves it as a tree if successful""" f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
python
def load_data(self, pdbid): f = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower()) self.doc = etree.parse(f)
[ "def", "load_data", "(", "self", ",", "pdbid", ")", ":", "f", "=", "urlopen", "(", "\"http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml\"", "%", "pdbid", ".", "lower", "(", ")", ")", "self", ".", "doc", "=", "etree", ".", "parse", "(", "f", ")...
Loads and parses an XML resource and saves it as a tree if successful
[ "Loads", "and", "parses", "an", "XML", "resource", "and", "saves", "it", "as", "a", "tree", "if", "successful" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/plipxml.py#L303-L306
4,732
ssalentin/plip
plip/modules/webservices.py
check_pdb_status
def check_pdb_status(pdbid): """Returns the status and up-to-date entry in the PDB for a given PDB ID""" url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid xmlf = urlopen(url) xml = et.parse(xmlf) xmlf.close() status = None current_pdbid = pdbid for df in xml.xpath('//record'): status = df.attrib['status'] # Status of an entry can be either 'UNKWOWN', 'OBSOLETE', or 'CURRENT' if status == 'OBSOLETE': current_pdbid = df.attrib['replacedBy'] # Contains the up-to-date PDB ID for obsolete entries return [status, current_pdbid.lower()]
python
def check_pdb_status(pdbid): url = 'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s' % pdbid xmlf = urlopen(url) xml = et.parse(xmlf) xmlf.close() status = None current_pdbid = pdbid for df in xml.xpath('//record'): status = df.attrib['status'] # Status of an entry can be either 'UNKWOWN', 'OBSOLETE', or 'CURRENT' if status == 'OBSOLETE': current_pdbid = df.attrib['replacedBy'] # Contains the up-to-date PDB ID for obsolete entries return [status, current_pdbid.lower()]
[ "def", "check_pdb_status", "(", "pdbid", ")", ":", "url", "=", "'http://www.rcsb.org/pdb/rest/idStatus?structureId=%s'", "%", "pdbid", "xmlf", "=", "urlopen", "(", "url", ")", "xml", "=", "et", ".", "parse", "(", "xmlf", ")", "xmlf", ".", "close", "(", ")", ...
Returns the status and up-to-date entry in the PDB for a given PDB ID
[ "Returns", "the", "status", "and", "up", "-", "to", "-", "date", "entry", "in", "the", "PDB", "for", "a", "given", "PDB", "ID" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/webservices.py#L22-L34
4,733
ssalentin/plip
plip/modules/webservices.py
fetch_pdb
def fetch_pdb(pdbid): """Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid.""" pdbid = pdbid.lower() write_message('\nChecking status of PDB ID %s ... ' % pdbid) state, current_entry = check_pdb_status(pdbid) # Get state and current PDB ID if state == 'OBSOLETE': write_message('entry is obsolete, getting %s instead.\n' % current_entry) elif state == 'CURRENT': write_message('entry is up to date.\n') elif state == 'UNKNOWN': sysexit(3, 'Invalid PDB ID (Entry does not exist on PDB server)\n') write_message('Downloading file from PDB ... ') pdburl = 'http://www.rcsb.org/pdb/files/%s.pdb' % current_entry # Get URL for current entry try: pdbfile = urlopen(pdburl).read().decode() # If no PDB file is available, a text is now shown with "We're sorry, but ..." # Could previously be distinguished by an HTTP error if 'sorry' in pdbfile: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") except HTTPError: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") return [pdbfile, current_entry]
python
def fetch_pdb(pdbid): pdbid = pdbid.lower() write_message('\nChecking status of PDB ID %s ... ' % pdbid) state, current_entry = check_pdb_status(pdbid) # Get state and current PDB ID if state == 'OBSOLETE': write_message('entry is obsolete, getting %s instead.\n' % current_entry) elif state == 'CURRENT': write_message('entry is up to date.\n') elif state == 'UNKNOWN': sysexit(3, 'Invalid PDB ID (Entry does not exist on PDB server)\n') write_message('Downloading file from PDB ... ') pdburl = 'http://www.rcsb.org/pdb/files/%s.pdb' % current_entry # Get URL for current entry try: pdbfile = urlopen(pdburl).read().decode() # If no PDB file is available, a text is now shown with "We're sorry, but ..." # Could previously be distinguished by an HTTP error if 'sorry' in pdbfile: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") except HTTPError: sysexit(5, "No file in PDB format available from wwPDB for the given PDB ID.\n") return [pdbfile, current_entry]
[ "def", "fetch_pdb", "(", "pdbid", ")", ":", "pdbid", "=", "pdbid", ".", "lower", "(", ")", "write_message", "(", "'\\nChecking status of PDB ID %s ... '", "%", "pdbid", ")", "state", ",", "current_entry", "=", "check_pdb_status", "(", "pdbid", ")", "# Get state ...
Get the newest entry from the RCSB server for the given PDB ID. Exits with '1' if PDB ID is invalid.
[ "Get", "the", "newest", "entry", "from", "the", "RCSB", "server", "for", "the", "given", "PDB", "ID", ".", "Exits", "with", "1", "if", "PDB", "ID", "is", "invalid", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/webservices.py#L37-L59
4,734
ella/ella
ella/positions/models.py
PositionBox
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
python
def PositionBox(position, *args, **kwargs): " Delegate the boxing. " obj = position.target return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs)
[ "def", "PositionBox", "(", "position", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "position", ".", "target", "return", "getattr", "(", "position", ".", "target", ",", "'box_class'", ",", "Box", ")", "(", "obj", ",", "*", "args",...
Delegate the boxing.
[ "Delegate", "the", "boxing", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/positions/models.py#L57-L60
4,735
ella/ella
ella/positions/models.py
PositionManager.get_active_position
def get_active_position(self, category, name, nofallback=False): """ Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent category if active position is not found for category """ now = timezone.now() lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \ (Q(active_till__isnull=True) | Q(active_till__gt=now)) while True: try: return self.get(lookup, category=category, name=name, disabled=False) except Position.DoesNotExist: # if nofallback was specified, do not look into parent categories if nofallback: return False # traverse the category tree to the top otherwise category = category.tree_parent # we reached the top and still haven't found the position - return if category is None: return False
python
def get_active_position(self, category, name, nofallback=False): now = timezone.now() lookup = (Q(active_from__isnull=True) | Q(active_from__lte=now)) & \ (Q(active_till__isnull=True) | Q(active_till__gt=now)) while True: try: return self.get(lookup, category=category, name=name, disabled=False) except Position.DoesNotExist: # if nofallback was specified, do not look into parent categories if nofallback: return False # traverse the category tree to the top otherwise category = category.tree_parent # we reached the top and still haven't found the position - return if category is None: return False
[ "def", "get_active_position", "(", "self", ",", "category", ",", "name", ",", "nofallback", "=", "False", ")", ":", "now", "=", "timezone", ".", "now", "(", ")", "lookup", "=", "(", "Q", "(", "active_from__isnull", "=", "True", ")", "|", "Q", "(", "a...
Get active position for given position name. params: category - Category model to look for name - name of the position nofallback - if True than do not fall back to parent category if active position is not found for category
[ "Get", "active", "position", "for", "given", "position", "name", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/positions/models.py#L26-L54
4,736
ella/ella
ella/positions/models.py
Position.render
def render(self, context, nodelist, box_type): " Render the position. " if not self.target: if self.target_ct: # broken Generic FK: log.warning('Broken target for position with pk %r', self.pk) return '' try: return Template(self.text, name="position-%s" % self.name).render(context) except TemplateSyntaxError: log.error('Broken definition for position with pk %r', self.pk) return '' if self.box_type: box_type = self.box_type if self.text: nodelist = Template('%s\n%s' % (nodelist.render({}), self.text), name="position-%s" % self.name).nodelist b = self.box_class(self, box_type, nodelist) return b.render(context)
python
def render(self, context, nodelist, box_type): " Render the position. " if not self.target: if self.target_ct: # broken Generic FK: log.warning('Broken target for position with pk %r', self.pk) return '' try: return Template(self.text, name="position-%s" % self.name).render(context) except TemplateSyntaxError: log.error('Broken definition for position with pk %r', self.pk) return '' if self.box_type: box_type = self.box_type if self.text: nodelist = Template('%s\n%s' % (nodelist.render({}), self.text), name="position-%s" % self.name).nodelist b = self.box_class(self, box_type, nodelist) return b.render(context)
[ "def", "render", "(", "self", ",", "context", ",", "nodelist", ",", "box_type", ")", ":", "if", "not", "self", ".", "target", ":", "if", "self", ".", "target_ct", ":", "# broken Generic FK:", "log", ".", "warning", "(", "'Broken target for position with pk %r'...
Render the position.
[ "Render", "the", "position", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/positions/models.py#L119-L139
4,737
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.set_initial_representations
def set_initial_representations(self): """General settings for PyMOL""" self.standard_settings() cmd.set('dash_gap', 0) # Show not dashes, but lines for the pliprofiler cmd.set('ray_shadow', 0) # Turn on ray shadows for clearer ray-traced images cmd.set('cartoon_color', 'mylightblue') # Set clipping planes for full view cmd.clip('far', -1000) cmd.clip('near', 1000)
python
def set_initial_representations(self): self.standard_settings() cmd.set('dash_gap', 0) # Show not dashes, but lines for the pliprofiler cmd.set('ray_shadow', 0) # Turn on ray shadows for clearer ray-traced images cmd.set('cartoon_color', 'mylightblue') # Set clipping planes for full view cmd.clip('far', -1000) cmd.clip('near', 1000)
[ "def", "set_initial_representations", "(", "self", ")", ":", "self", ".", "standard_settings", "(", ")", "cmd", ".", "set", "(", "'dash_gap'", ",", "0", ")", "# Show not dashes, but lines for the pliprofiler", "cmd", ".", "set", "(", "'ray_shadow'", ",", "0", ")...
General settings for PyMOL
[ "General", "settings", "for", "PyMOL" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L24-L33
4,738
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.standard_settings
def standard_settings(self): """Sets up standard settings for a nice visualization.""" cmd.set('bg_rgb', [1.0, 1.0, 1.0]) # White background cmd.set('depth_cue', 0) # Turn off depth cueing (no fog) cmd.set('cartoon_side_chain_helper', 1) # Improve combined visualization of sticks and cartoon cmd.set('cartoon_fancy_helices', 1) # Nicer visualization of helices (using tapered ends) cmd.set('transparency_mode', 1) # Turn on multilayer transparency cmd.set('dash_radius', 0.05) self.set_custom_colorset()
python
def standard_settings(self): cmd.set('bg_rgb', [1.0, 1.0, 1.0]) # White background cmd.set('depth_cue', 0) # Turn off depth cueing (no fog) cmd.set('cartoon_side_chain_helper', 1) # Improve combined visualization of sticks and cartoon cmd.set('cartoon_fancy_helices', 1) # Nicer visualization of helices (using tapered ends) cmd.set('transparency_mode', 1) # Turn on multilayer transparency cmd.set('dash_radius', 0.05) self.set_custom_colorset()
[ "def", "standard_settings", "(", "self", ")", ":", "cmd", ".", "set", "(", "'bg_rgb'", ",", "[", "1.0", ",", "1.0", ",", "1.0", "]", ")", "# White background", "cmd", ".", "set", "(", "'depth_cue'", ",", "0", ")", "# Turn off depth cueing (no fog)", "cmd",...
Sets up standard settings for a nice visualization.
[ "Sets", "up", "standard", "settings", "for", "a", "nice", "visualization", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L46-L54
4,739
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.set_custom_colorset
def set_custom_colorset(self): """Defines a colorset with matching colors. Provided by Joachim.""" cmd.set_color('myorange', '[253, 174, 97]') cmd.set_color('mygreen', '[171, 221, 164]') cmd.set_color('myred', '[215, 25, 28]') cmd.set_color('myblue', '[43, 131, 186]') cmd.set_color('mylightblue', '[158, 202, 225]') cmd.set_color('mylightgreen', '[229, 245, 224]')
python
def set_custom_colorset(self): cmd.set_color('myorange', '[253, 174, 97]') cmd.set_color('mygreen', '[171, 221, 164]') cmd.set_color('myred', '[215, 25, 28]') cmd.set_color('myblue', '[43, 131, 186]') cmd.set_color('mylightblue', '[158, 202, 225]') cmd.set_color('mylightgreen', '[229, 245, 224]')
[ "def", "set_custom_colorset", "(", "self", ")", ":", "cmd", ".", "set_color", "(", "'myorange'", ",", "'[253, 174, 97]'", ")", "cmd", ".", "set_color", "(", "'mygreen'", ",", "'[171, 221, 164]'", ")", "cmd", ".", "set_color", "(", "'myred'", ",", "'[215, 25, 2...
Defines a colorset with matching colors. Provided by Joachim.
[ "Defines", "a", "colorset", "with", "matching", "colors", ".", "Provided", "by", "Joachim", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L56-L63
4,740
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_halogen
def show_halogen(self): """Visualize halogen bonds.""" halogen = self.plcomplex.halogen_bonds all_don_x, all_acc_o = [], [] for h in halogen: all_don_x.append(h.don_id) all_acc_o.append(h.acc_id) cmd.select('tmp_bs', 'id %i & %s' % (h.acc_id, self.protname)) cmd.select('tmp_lig', 'id %i & %s' % (h.don_id, self.ligname)) cmd.distance('HalogenBonds', 'tmp_bs', 'tmp_lig') if not len(all_acc_o) == 0: self.select_by_ids('HalogenAccept', all_acc_o, restrict=self.protname) self.select_by_ids('HalogenDonor', all_don_x, restrict=self.ligname) if self.object_exists('HalogenBonds'): cmd.set('dash_color', 'greencyan', 'HalogenBonds')
python
def show_halogen(self): halogen = self.plcomplex.halogen_bonds all_don_x, all_acc_o = [], [] for h in halogen: all_don_x.append(h.don_id) all_acc_o.append(h.acc_id) cmd.select('tmp_bs', 'id %i & %s' % (h.acc_id, self.protname)) cmd.select('tmp_lig', 'id %i & %s' % (h.don_id, self.ligname)) cmd.distance('HalogenBonds', 'tmp_bs', 'tmp_lig') if not len(all_acc_o) == 0: self.select_by_ids('HalogenAccept', all_acc_o, restrict=self.protname) self.select_by_ids('HalogenDonor', all_don_x, restrict=self.ligname) if self.object_exists('HalogenBonds'): cmd.set('dash_color', 'greencyan', 'HalogenBonds')
[ "def", "show_halogen", "(", "self", ")", ":", "halogen", "=", "self", ".", "plcomplex", ".", "halogen_bonds", "all_don_x", ",", "all_acc_o", "=", "[", "]", ",", "[", "]", "for", "h", "in", "halogen", ":", "all_don_x", ".", "append", "(", "h", ".", "d...
Visualize halogen bonds.
[ "Visualize", "halogen", "bonds", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L122-L137
4,741
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_stacking
def show_stacking(self): """Visualize pi-stacking interactions.""" stacks = self.plcomplex.pistacking for i, stack in enumerate(stacks): pires_ids = '+'.join(map(str, stack.proteinring_atoms)) pilig_ids = '+'.join(map(str, stack.ligandring_atoms)) cmd.select('StackRings-P', 'StackRings-P or (id %s & %s)' % (pires_ids, self.protname)) cmd.select('StackRings-L', 'StackRings-L or (id %s & %s)' % (pilig_ids, self.ligname)) cmd.select('StackRings-P', 'byres StackRings-P') cmd.show('sticks', 'StackRings-P') cmd.pseudoatom('ps-pistack-1-%i' % i, pos=stack.proteinring_center) cmd.pseudoatom('ps-pistack-2-%i' % i, pos=stack.ligandring_center) cmd.pseudoatom('Centroids-P', pos=stack.proteinring_center) cmd.pseudoatom('Centroids-L', pos=stack.ligandring_center) if stack.type == 'P': cmd.distance('PiStackingP', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if stack.type == 'T': cmd.distance('PiStackingT', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if self.object_exists('PiStackingP'): cmd.set('dash_color', 'green', 'PiStackingP') cmd.set('dash_gap', 0.3, 'PiStackingP') cmd.set('dash_length', 0.6, 'PiStackingP') if self.object_exists('PiStackingT'): cmd.set('dash_color', 'smudge', 'PiStackingT') cmd.set('dash_gap', 0.3, 'PiStackingT') cmd.set('dash_length', 0.6, 'PiStackingT')
python
def show_stacking(self): stacks = self.plcomplex.pistacking for i, stack in enumerate(stacks): pires_ids = '+'.join(map(str, stack.proteinring_atoms)) pilig_ids = '+'.join(map(str, stack.ligandring_atoms)) cmd.select('StackRings-P', 'StackRings-P or (id %s & %s)' % (pires_ids, self.protname)) cmd.select('StackRings-L', 'StackRings-L or (id %s & %s)' % (pilig_ids, self.ligname)) cmd.select('StackRings-P', 'byres StackRings-P') cmd.show('sticks', 'StackRings-P') cmd.pseudoatom('ps-pistack-1-%i' % i, pos=stack.proteinring_center) cmd.pseudoatom('ps-pistack-2-%i' % i, pos=stack.ligandring_center) cmd.pseudoatom('Centroids-P', pos=stack.proteinring_center) cmd.pseudoatom('Centroids-L', pos=stack.ligandring_center) if stack.type == 'P': cmd.distance('PiStackingP', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if stack.type == 'T': cmd.distance('PiStackingT', 'ps-pistack-1-%i' % i, 'ps-pistack-2-%i' % i) if self.object_exists('PiStackingP'): cmd.set('dash_color', 'green', 'PiStackingP') cmd.set('dash_gap', 0.3, 'PiStackingP') cmd.set('dash_length', 0.6, 'PiStackingP') if self.object_exists('PiStackingT'): cmd.set('dash_color', 'smudge', 'PiStackingT') cmd.set('dash_gap', 0.3, 'PiStackingT') cmd.set('dash_length', 0.6, 'PiStackingT')
[ "def", "show_stacking", "(", "self", ")", ":", "stacks", "=", "self", ".", "plcomplex", ".", "pistacking", "for", "i", ",", "stack", "in", "enumerate", "(", "stacks", ")", ":", "pires_ids", "=", "'+'", ".", "join", "(", "map", "(", "str", ",", "stack...
Visualize pi-stacking interactions.
[ "Visualize", "pi", "-", "stacking", "interactions", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L139-L166
4,742
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_cationpi
def show_cationpi(self): """Visualize cation-pi interactions.""" for i, p in enumerate(self.plcomplex.pication): cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center) cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center) if p.protcharged: cmd.pseudoatom('Chargecenter-P', pos=p.charge_center) cmd.pseudoatom('Centroids-L', pos=p.ring_center) pilig_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-L', 'PiCatRing-L or (id %s & %s)' % (pilig_ids, self.ligname)) for a in p.charge_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (a, self.protname)) else: cmd.pseudoatom('Chargecenter-L', pos=p.charge_center) cmd.pseudoatom('Centroids-P', pos=p.ring_center) pires_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-P', 'PiCatRing-P or (id %s & %s)' % (pires_ids, self.protname)) for a in p.charge_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (a, self.ligname)) cmd.distance('PiCation', 'ps-picat-1-%i' % i, 'ps-picat-2-%i' % i) if self.object_exists('PiCation'): cmd.set('dash_color', 'orange', 'PiCation') cmd.set('dash_gap', 0.3, 'PiCation') cmd.set('dash_length', 0.6, 'PiCation')
python
def show_cationpi(self): for i, p in enumerate(self.plcomplex.pication): cmd.pseudoatom('ps-picat-1-%i' % i, pos=p.ring_center) cmd.pseudoatom('ps-picat-2-%i' % i, pos=p.charge_center) if p.protcharged: cmd.pseudoatom('Chargecenter-P', pos=p.charge_center) cmd.pseudoatom('Centroids-L', pos=p.ring_center) pilig_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-L', 'PiCatRing-L or (id %s & %s)' % (pilig_ids, self.ligname)) for a in p.charge_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (a, self.protname)) else: cmd.pseudoatom('Chargecenter-L', pos=p.charge_center) cmd.pseudoatom('Centroids-P', pos=p.ring_center) pires_ids = '+'.join(map(str, p.ring_atoms)) cmd.select('PiCatRing-P', 'PiCatRing-P or (id %s & %s)' % (pires_ids, self.protname)) for a in p.charge_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (a, self.ligname)) cmd.distance('PiCation', 'ps-picat-1-%i' % i, 'ps-picat-2-%i' % i) if self.object_exists('PiCation'): cmd.set('dash_color', 'orange', 'PiCation') cmd.set('dash_gap', 0.3, 'PiCation') cmd.set('dash_length', 0.6, 'PiCation')
[ "def", "show_cationpi", "(", "self", ")", ":", "for", "i", ",", "p", "in", "enumerate", "(", "self", ".", "plcomplex", ".", "pication", ")", ":", "cmd", ".", "pseudoatom", "(", "'ps-picat-1-%i'", "%", "i", ",", "pos", "=", "p", ".", "ring_center", ")...
Visualize cation-pi interactions.
[ "Visualize", "cation", "-", "pi", "interactions", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L168-L191
4,743
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_sbridges
def show_sbridges(self): """Visualize salt bridges.""" for i, saltb in enumerate(self.plcomplex.saltbridges): if saltb.protispos: for patom in saltb.positive_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.negative_atoms: cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center], ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i) else: for patom in saltb.negative_atoms: cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.positive_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center], ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i) if self.object_exists('Saltbridges'): cmd.set('dash_color', 'yellow', 'Saltbridges') cmd.set('dash_gap', 0.5, 'Saltbridges')
python
def show_sbridges(self): for i, saltb in enumerate(self.plcomplex.saltbridges): if saltb.protispos: for patom in saltb.positive_atoms: cmd.select('PosCharge-P', 'PosCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.negative_atoms: cmd.select('NegCharge-L', 'NegCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbl-1-%i' % i, 'Chargecenter-P', saltb.positive_center], ['ps-sbl-2-%i' % i, 'Chargecenter-L', saltb.negative_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbl-1-%i' % i, 'ps-sbl-2-%i' % i) else: for patom in saltb.negative_atoms: cmd.select('NegCharge-P', 'NegCharge-P or (id %i & %s)' % (patom, self.protname)) for latom in saltb.positive_atoms: cmd.select('PosCharge-L', 'PosCharge-L or (id %i & %s)' % (latom, self.ligname)) for sbgroup in [['ps-sbp-1-%i' % i, 'Chargecenter-P', saltb.negative_center], ['ps-sbp-2-%i' % i, 'Chargecenter-L', saltb.positive_center]]: cmd.pseudoatom(sbgroup[0], pos=sbgroup[2]) cmd.pseudoatom(sbgroup[1], pos=sbgroup[2]) cmd.distance('Saltbridges', 'ps-sbp-1-%i' % i, 'ps-sbp-2-%i' % i) if self.object_exists('Saltbridges'): cmd.set('dash_color', 'yellow', 'Saltbridges') cmd.set('dash_gap', 0.5, 'Saltbridges')
[ "def", "show_sbridges", "(", "self", ")", ":", "for", "i", ",", "saltb", "in", "enumerate", "(", "self", ".", "plcomplex", ".", "saltbridges", ")", ":", "if", "saltb", ".", "protispos", ":", "for", "patom", "in", "saltb", ".", "positive_atoms", ":", "c...
Visualize salt bridges.
[ "Visualize", "salt", "bridges", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L193-L219
4,744
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_wbridges
def show_wbridges(self): """Visualize water bridges.""" for bridge in self.plcomplex.waterbridges: if bridge.protisdon: cmd.select('HBondDonor-P', 'HBondDonor-P or (id %i & %s)' % (bridge.don_id, self.protname)) cmd.select('HBondAccept-L', 'HBondAccept-L or (id %i & %s)' % (bridge.acc_id, self.ligname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.protname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.ligname)) else: cmd.select('HBondDonor-L', 'HBondDonor-L or (id %i & %s)' % (bridge.don_id, self.ligname)) cmd.select('HBondAccept-P', 'HBondAccept-P or (id %i & %s)' % (bridge.acc_id, self.protname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.ligname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.protname)) cmd.select('Water', 'Water or (id %i & resn HOH)' % bridge.water_id) cmd.select('tmp_water', 'id %i & resn HOH' % bridge.water_id) cmd.distance('WaterBridges', 'tmp_acc', 'tmp_water') cmd.distance('WaterBridges', 'tmp_don', 'tmp_water') if self.object_exists('WaterBridges'): cmd.set('dash_color', 'lightblue', 'WaterBridges') cmd.delete('tmp_water or tmp_acc or tmp_don') cmd.color('lightblue', 'Water') cmd.show('spheres', 'Water')
python
def show_wbridges(self): for bridge in self.plcomplex.waterbridges: if bridge.protisdon: cmd.select('HBondDonor-P', 'HBondDonor-P or (id %i & %s)' % (bridge.don_id, self.protname)) cmd.select('HBondAccept-L', 'HBondAccept-L or (id %i & %s)' % (bridge.acc_id, self.ligname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.protname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.ligname)) else: cmd.select('HBondDonor-L', 'HBondDonor-L or (id %i & %s)' % (bridge.don_id, self.ligname)) cmd.select('HBondAccept-P', 'HBondAccept-P or (id %i & %s)' % (bridge.acc_id, self.protname)) cmd.select('tmp_don', 'id %i & %s' % (bridge.don_id, self.ligname)) cmd.select('tmp_acc', 'id %i & %s' % (bridge.acc_id, self.protname)) cmd.select('Water', 'Water or (id %i & resn HOH)' % bridge.water_id) cmd.select('tmp_water', 'id %i & resn HOH' % bridge.water_id) cmd.distance('WaterBridges', 'tmp_acc', 'tmp_water') cmd.distance('WaterBridges', 'tmp_don', 'tmp_water') if self.object_exists('WaterBridges'): cmd.set('dash_color', 'lightblue', 'WaterBridges') cmd.delete('tmp_water or tmp_acc or tmp_don') cmd.color('lightblue', 'Water') cmd.show('spheres', 'Water')
[ "def", "show_wbridges", "(", "self", ")", ":", "for", "bridge", "in", "self", ".", "plcomplex", ".", "waterbridges", ":", "if", "bridge", ".", "protisdon", ":", "cmd", ".", "select", "(", "'HBondDonor-P'", ",", "'HBondDonor-P or (id %i & %s)'", "%", "(", "br...
Visualize water bridges.
[ "Visualize", "water", "bridges", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L221-L242
4,745
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.show_metal
def show_metal(self): """Visualize metal coordination.""" metal_complexes = self.plcomplex.metal_complexes if not len(metal_complexes) == 0: self.select_by_ids('Metal-M', self.metal_ids) for metal_complex in metal_complexes: cmd.select('tmp_m', 'id %i' % metal_complex.metal_id) cmd.select('tmp_t', 'id %i' % metal_complex.target_id) if metal_complex.location == 'water': cmd.select('Metal-W', 'Metal-W or id %s' % metal_complex.target_id) if metal_complex.location.startswith('protein'): cmd.select('tmp_t', 'tmp_t & %s' % self.protname) cmd.select('Metal-P', 'Metal-P or (id %s & %s)' % (metal_complex.target_id, self.protname)) if metal_complex.location == 'ligand': cmd.select('tmp_t', 'tmp_t & %s' % self.ligname) cmd.select('Metal-L', 'Metal-L or (id %s & %s)' % (metal_complex.target_id, self.ligname)) cmd.distance('MetalComplexes', 'tmp_m', 'tmp_t') cmd.delete('tmp_m or tmp_t') if self.object_exists('MetalComplexes'): cmd.set('dash_color', 'violetpurple', 'MetalComplexes') cmd.set('dash_gap', 0.5, 'MetalComplexes') # Show water molecules for metal complexes cmd.show('spheres', 'Metal-W') cmd.color('lightblue', 'Metal-W')
python
def show_metal(self): metal_complexes = self.plcomplex.metal_complexes if not len(metal_complexes) == 0: self.select_by_ids('Metal-M', self.metal_ids) for metal_complex in metal_complexes: cmd.select('tmp_m', 'id %i' % metal_complex.metal_id) cmd.select('tmp_t', 'id %i' % metal_complex.target_id) if metal_complex.location == 'water': cmd.select('Metal-W', 'Metal-W or id %s' % metal_complex.target_id) if metal_complex.location.startswith('protein'): cmd.select('tmp_t', 'tmp_t & %s' % self.protname) cmd.select('Metal-P', 'Metal-P or (id %s & %s)' % (metal_complex.target_id, self.protname)) if metal_complex.location == 'ligand': cmd.select('tmp_t', 'tmp_t & %s' % self.ligname) cmd.select('Metal-L', 'Metal-L or (id %s & %s)' % (metal_complex.target_id, self.ligname)) cmd.distance('MetalComplexes', 'tmp_m', 'tmp_t') cmd.delete('tmp_m or tmp_t') if self.object_exists('MetalComplexes'): cmd.set('dash_color', 'violetpurple', 'MetalComplexes') cmd.set('dash_gap', 0.5, 'MetalComplexes') # Show water molecules for metal complexes cmd.show('spheres', 'Metal-W') cmd.color('lightblue', 'Metal-W')
[ "def", "show_metal", "(", "self", ")", ":", "metal_complexes", "=", "self", ".", "plcomplex", ".", "metal_complexes", "if", "not", "len", "(", "metal_complexes", ")", "==", "0", ":", "self", ".", "select_by_ids", "(", "'Metal-M'", ",", "self", ".", "metal_...
Visualize metal coordination.
[ "Visualize", "metal", "coordination", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L244-L267
4,746
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.selections_cleanup
def selections_cleanup(self): """Cleans up non-used selections""" if not len(self.plcomplex.unpaired_hba_idx) == 0: self.select_by_ids('Unpaired-HBA', self.plcomplex.unpaired_hba_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hbd_idx) == 0: self.select_by_ids('Unpaired-HBD', self.plcomplex.unpaired_hbd_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hal_idx) == 0: self.select_by_ids('Unpaired-HAL', self.plcomplex.unpaired_hal_idx, selection_exists=True) selections = cmd.get_names("selections") for selection in selections: try: empty = len(cmd.get_model(selection).atom) == 0 except: empty = True if empty: cmd.delete(selection) cmd.deselect() cmd.delete('tmp*') cmd.delete('ps-*')
python
def selections_cleanup(self): if not len(self.plcomplex.unpaired_hba_idx) == 0: self.select_by_ids('Unpaired-HBA', self.plcomplex.unpaired_hba_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hbd_idx) == 0: self.select_by_ids('Unpaired-HBD', self.plcomplex.unpaired_hbd_idx, selection_exists=True) if not len(self.plcomplex.unpaired_hal_idx) == 0: self.select_by_ids('Unpaired-HAL', self.plcomplex.unpaired_hal_idx, selection_exists=True) selections = cmd.get_names("selections") for selection in selections: try: empty = len(cmd.get_model(selection).atom) == 0 except: empty = True if empty: cmd.delete(selection) cmd.deselect() cmd.delete('tmp*') cmd.delete('ps-*')
[ "def", "selections_cleanup", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "plcomplex", ".", "unpaired_hba_idx", ")", "==", "0", ":", "self", ".", "select_by_ids", "(", "'Unpaired-HBA'", ",", "self", ".", "plcomplex", ".", "unpaired_hba_idx", ...
Cleans up non-used selections
[ "Cleans", "up", "non", "-", "used", "selections" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L269-L289
4,747
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.selections_group
def selections_group(self): """Group all selections""" cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname)) cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT ' 'Saltbridges MetalComplexes') cmd.group('Atoms', '') cmd.group('Atoms.Protein', 'Hydrophobic-P HBondAccept-P HBondDonor-P HalogenAccept Centroids-P PiCatRing-P ' 'StackRings-P PosCharge-P NegCharge-P AllBSRes Chargecenter-P Metal-P') cmd.group('Atoms.Ligand', 'Hydrophobic-L HBondAccept-L HBondDonor-L HalogenDonor Centroids-L NegCharge-L ' 'PosCharge-L NegCharge-L ChargeCenter-L StackRings-L PiCatRing-L Metal-L Metal-M ' 'Unpaired-HBA Unpaired-HBD Unpaired-HAL Unpaired-RINGS') cmd.group('Atoms.Other', 'Water Metal-W') cmd.order('*', 'y')
python
def selections_group(self): cmd.group('Structures', '%s %s %sCartoon' % (self.protname, self.ligname, self.protname)) cmd.group('Interactions', 'Hydrophobic HBonds HalogenBonds WaterBridges PiCation PiStackingP PiStackingT ' 'Saltbridges MetalComplexes') cmd.group('Atoms', '') cmd.group('Atoms.Protein', 'Hydrophobic-P HBondAccept-P HBondDonor-P HalogenAccept Centroids-P PiCatRing-P ' 'StackRings-P PosCharge-P NegCharge-P AllBSRes Chargecenter-P Metal-P') cmd.group('Atoms.Ligand', 'Hydrophobic-L HBondAccept-L HBondDonor-L HalogenDonor Centroids-L NegCharge-L ' 'PosCharge-L NegCharge-L ChargeCenter-L StackRings-L PiCatRing-L Metal-L Metal-M ' 'Unpaired-HBA Unpaired-HBD Unpaired-HAL Unpaired-RINGS') cmd.group('Atoms.Other', 'Water Metal-W') cmd.order('*', 'y')
[ "def", "selections_group", "(", "self", ")", ":", "cmd", ".", "group", "(", "'Structures'", ",", "'%s %s %sCartoon'", "%", "(", "self", ".", "protname", ",", "self", ".", "ligname", ",", "self", ".", "protname", ")", ")", "cmd", ".", "group", "(", "'In...
Group all selections
[ "Group", "all", "selections" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L291-L303
4,748
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.additional_cleanup
def additional_cleanup(self): """Cleanup of various representations""" cmd.remove('not alt ""+A') # Remove alternate conformations cmd.hide('labels', 'Interactions') # Hide labels of lines cmd.disable('%sCartoon' % self.protname) cmd.hide('everything', 'hydrogens')
python
def additional_cleanup(self): cmd.remove('not alt ""+A') # Remove alternate conformations cmd.hide('labels', 'Interactions') # Hide labels of lines cmd.disable('%sCartoon' % self.protname) cmd.hide('everything', 'hydrogens')
[ "def", "additional_cleanup", "(", "self", ")", ":", "cmd", ".", "remove", "(", "'not alt \"\"+A'", ")", "# Remove alternate conformations", "cmd", ".", "hide", "(", "'labels'", ",", "'Interactions'", ")", "# Hide labels of lines", "cmd", ".", "disable", "(", "'%sC...
Cleanup of various representations
[ "Cleanup", "of", "various", "representations" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L305-L311
4,749
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.zoom_to_ligand
def zoom_to_ligand(self): """Zoom in too ligand and its interactions.""" cmd.center(self.ligname) cmd.orient(self.ligname) cmd.turn('x', 110) # If the ligand is aligned with the longest axis, aromatic rings are hidden if 'AllBSRes' in cmd.get_names("selections"): cmd.zoom('%s or AllBSRes' % self.ligname, 3) else: if self.object_exists(self.ligname): cmd.zoom(self.ligname, 3) cmd.origin(self.ligname)
python
def zoom_to_ligand(self): cmd.center(self.ligname) cmd.orient(self.ligname) cmd.turn('x', 110) # If the ligand is aligned with the longest axis, aromatic rings are hidden if 'AllBSRes' in cmd.get_names("selections"): cmd.zoom('%s or AllBSRes' % self.ligname, 3) else: if self.object_exists(self.ligname): cmd.zoom(self.ligname, 3) cmd.origin(self.ligname)
[ "def", "zoom_to_ligand", "(", "self", ")", ":", "cmd", ".", "center", "(", "self", ".", "ligname", ")", "cmd", ".", "orient", "(", "self", ".", "ligname", ")", "cmd", ".", "turn", "(", "'x'", ",", "110", ")", "# If the ligand is aligned with the longest ax...
Zoom in too ligand and its interactions.
[ "Zoom", "in", "too", "ligand", "and", "its", "interactions", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L313-L323
4,750
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.save_session
def save_session(self, outfolder, override=None): """Saves a PyMOL session file.""" filename = '%s_%s' % (self.protname.upper(), "_".join( [self.hetid, self.plcomplex.chain, self.plcomplex.position])) if override is not None: filename = override cmd.save("/".join([outfolder, "%s.pse" % filename]))
python
def save_session(self, outfolder, override=None): filename = '%s_%s' % (self.protname.upper(), "_".join( [self.hetid, self.plcomplex.chain, self.plcomplex.position])) if override is not None: filename = override cmd.save("/".join([outfolder, "%s.pse" % filename]))
[ "def", "save_session", "(", "self", ",", "outfolder", ",", "override", "=", "None", ")", ":", "filename", "=", "'%s_%s'", "%", "(", "self", ".", "protname", ".", "upper", "(", ")", ",", "\"_\"", ".", "join", "(", "[", "self", ".", "hetid", ",", "se...
Saves a PyMOL session file.
[ "Saves", "a", "PyMOL", "session", "file", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L325-L331
4,751
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.save_picture
def save_picture(self, outfolder, filename): """Saves a picture""" self.set_fancy_ray() self.png_workaround("/".join([outfolder, filename]))
python
def save_picture(self, outfolder, filename): self.set_fancy_ray() self.png_workaround("/".join([outfolder, filename]))
[ "def", "save_picture", "(", "self", ",", "outfolder", ",", "filename", ")", ":", "self", ".", "set_fancy_ray", "(", ")", "self", ".", "png_workaround", "(", "\"/\"", ".", "join", "(", "[", "outfolder", ",", "filename", "]", ")", ")" ]
Saves a picture
[ "Saves", "a", "picture" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L380-L383
4,752
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.set_fancy_ray
def set_fancy_ray(self): """Give the molecule a flat, modern look.""" cmd.set('light_count', 6) cmd.set('spec_count', 1.5) cmd.set('shininess', 4) cmd.set('specular', 0.3) cmd.set('reflect', 1.6) cmd.set('ambient', 0) cmd.set('direct', 0) cmd.set('ray_shadow', 0) # Gives the molecules a flat, modern look cmd.set('ambient_occlusion_mode', 1) cmd.set('ray_opaque_background', 0)
python
def set_fancy_ray(self): cmd.set('light_count', 6) cmd.set('spec_count', 1.5) cmd.set('shininess', 4) cmd.set('specular', 0.3) cmd.set('reflect', 1.6) cmd.set('ambient', 0) cmd.set('direct', 0) cmd.set('ray_shadow', 0) # Gives the molecules a flat, modern look cmd.set('ambient_occlusion_mode', 1) cmd.set('ray_opaque_background', 0)
[ "def", "set_fancy_ray", "(", "self", ")", ":", "cmd", ".", "set", "(", "'light_count'", ",", "6", ")", "cmd", ".", "set", "(", "'spec_count'", ",", "1.5", ")", "cmd", ".", "set", "(", "'shininess'", ",", "4", ")", "cmd", ".", "set", "(", "'specular...
Give the molecule a flat, modern look.
[ "Give", "the", "molecule", "a", "flat", "modern", "look", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L385-L396
4,753
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.adapt_for_peptides
def adapt_for_peptides(self): """Adapt visualization for peptide ligands and interchain contacts""" cmd.hide('sticks', self.ligname) cmd.set('cartoon_color', 'lightorange', self.ligname) cmd.show('cartoon', self.ligname) cmd.show('sticks', "byres *-L") cmd.util.cnc(self.ligname) cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain)) cmd.set('cartoon_side_chain_helper', 0)
python
def adapt_for_peptides(self): cmd.hide('sticks', self.ligname) cmd.set('cartoon_color', 'lightorange', self.ligname) cmd.show('cartoon', self.ligname) cmd.show('sticks', "byres *-L") cmd.util.cnc(self.ligname) cmd.remove('%sCartoon and chain %s' % (self.protname, self.plcomplex.chain)) cmd.set('cartoon_side_chain_helper', 0)
[ "def", "adapt_for_peptides", "(", "self", ")", ":", "cmd", ".", "hide", "(", "'sticks'", ",", "self", ".", "ligname", ")", "cmd", ".", "set", "(", "'cartoon_color'", ",", "'lightorange'", ",", "self", ".", "ligname", ")", "cmd", ".", "show", "(", "'car...
Adapt visualization for peptide ligands and interchain contacts
[ "Adapt", "visualization", "for", "peptide", "ligands", "and", "interchain", "contacts" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L398-L406
4,754
ssalentin/plip
plip/modules/pymolplip.py
PyMOLVisualizer.refinements
def refinements(self): """Refinements for the visualization""" # Show sticks for all residues interacing with the ligand cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRes') # Show spheres for the ring centroids cmd.hide('everything', 'centroids*') cmd.show('nb_spheres', 'centroids*') # Show spheres for centers of charge if self.object_exists('Chargecenter-P') or self.object_exists('Chargecenter-L'): cmd.hide('nonbonded', 'chargecenter*') cmd.show('spheres', 'chargecenter*') cmd.set('sphere_scale', 0.4, 'chargecenter*') cmd.color('yellow', 'chargecenter*') cmd.set('valence', 1) # Show bond valency (e.g. double bonds) # Optional cartoon representation of the protein cmd.copy('%sCartoon' % self.protname, self.protname) cmd.show('cartoon', '%sCartoon' % self.protname) cmd.show('sticks', '%sCartoon' % self.protname) cmd.set('stick_transparency', 1, '%sCartoon' % self.protname) # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein cmd.set('sphere_scale', 0.2, 'resn HOH or Water') # Needs to be done here because of the copy made cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)') if 'Centroids*' in cmd.get_names("selections"): cmd.color('grey80', 'Centroids*') cmd.hide('spheres', '%sCartoon' % self.protname) cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname) # Hide DNA/RNA Cartoon if self.ligname == 'SF4': # Special case for iron-sulfur clusters, can't be visualized with sticks cmd.show('spheres', '%s' % self.ligname) cmd.hide('everything', 'resn HOH &!Water') # Hide all non-interacting water molecules cmd.hide('sticks', '%s and !%s and !AllBSRes' % (self.protname, self.ligname)) # Hide all non-interacting residues if self.ligandtype in ['PEPTIDE', 'INTRA']: self.adapt_for_peptides() if self.ligandtype == 'INTRA': self.adapt_for_intra()
python
def refinements(self): # Show sticks for all residues interacing with the ligand cmd.select('AllBSRes', 'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or ' 'StackRings-P or PiCatRing-P or HalogenAcc or Metal-P)') cmd.show('sticks', 'AllBSRes') # Show spheres for the ring centroids cmd.hide('everything', 'centroids*') cmd.show('nb_spheres', 'centroids*') # Show spheres for centers of charge if self.object_exists('Chargecenter-P') or self.object_exists('Chargecenter-L'): cmd.hide('nonbonded', 'chargecenter*') cmd.show('spheres', 'chargecenter*') cmd.set('sphere_scale', 0.4, 'chargecenter*') cmd.color('yellow', 'chargecenter*') cmd.set('valence', 1) # Show bond valency (e.g. double bonds) # Optional cartoon representation of the protein cmd.copy('%sCartoon' % self.protname, self.protname) cmd.show('cartoon', '%sCartoon' % self.protname) cmd.show('sticks', '%sCartoon' % self.protname) cmd.set('stick_transparency', 1, '%sCartoon' % self.protname) # Resize water molecules. Sometimes they are not heteroatoms HOH, but part of the protein cmd.set('sphere_scale', 0.2, 'resn HOH or Water') # Needs to be done here because of the copy made cmd.set('sphere_transparency', 0.4, '!(resn HOH or Water)') if 'Centroids*' in cmd.get_names("selections"): cmd.color('grey80', 'Centroids*') cmd.hide('spheres', '%sCartoon' % self.protname) cmd.hide('cartoon', '%sCartoon and resn DA+DG+DC+DU+DT+A+G+C+U+T' % self.protname) # Hide DNA/RNA Cartoon if self.ligname == 'SF4': # Special case for iron-sulfur clusters, can't be visualized with sticks cmd.show('spheres', '%s' % self.ligname) cmd.hide('everything', 'resn HOH &!Water') # Hide all non-interacting water molecules cmd.hide('sticks', '%s and !%s and !AllBSRes' % (self.protname, self.ligname)) # Hide all non-interacting residues if self.ligandtype in ['PEPTIDE', 'INTRA']: self.adapt_for_peptides() if self.ligandtype == 'INTRA': self.adapt_for_intra()
[ "def", "refinements", "(", "self", ")", ":", "# Show sticks for all residues interacing with the ligand", "cmd", ".", "select", "(", "'AllBSRes'", ",", "'byres (Hydrophobic-P or HBondDonor-P or HBondAccept-P or PosCharge-P or NegCharge-P or '", "'StackRings-P or PiCatRing-P or HalogenAcc...
Refinements for the visualization
[ "Refinements", "for", "the", "visualization" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/pymolplip.py#L411-L454
4,755
ella/ella
ella/core/cache/utils.py
get_cached_object
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs): """ Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type """ if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we are looking for a publishable, fetch just the actual content # type and then fetch the actual object if model_ct.app_label == 'core' and model_ct.model == 'publishable': actual_ct_id = model_ct.model_class()._default_manager.values('content_type_id').get(**kwargs)['content_type_id'] model_ct = ContentType.objects.get_for_id(actual_ct_id) # fetch the actual object we want obj = model_ct.model_class()._default_manager.get(**kwargs) # since 99% of lookups are done via PK make sure we set the cache for # that lookup even if we retrieved it using a different one. if 'pk' in kwargs: cache.set(key, obj, timeout) elif not isinstance(cache, DummyCache): cache.set_many({key: obj, _get_key(KEY_PREFIX, model_ct, pk=obj.pk): obj}, timeout=timeout) return obj
python
def get_cached_object(model, timeout=CACHE_TIMEOUT, **kwargs): if not isinstance(model, ContentType): model_ct = ContentType.objects.get_for_model(model) else: model_ct = model key = _get_key(KEY_PREFIX, model_ct, **kwargs) obj = cache.get(key) if obj is None: # if we are looking for a publishable, fetch just the actual content # type and then fetch the actual object if model_ct.app_label == 'core' and model_ct.model == 'publishable': actual_ct_id = model_ct.model_class()._default_manager.values('content_type_id').get(**kwargs)['content_type_id'] model_ct = ContentType.objects.get_for_id(actual_ct_id) # fetch the actual object we want obj = model_ct.model_class()._default_manager.get(**kwargs) # since 99% of lookups are done via PK make sure we set the cache for # that lookup even if we retrieved it using a different one. if 'pk' in kwargs: cache.set(key, obj, timeout) elif not isinstance(cache, DummyCache): cache.set_many({key: obj, _get_key(KEY_PREFIX, model_ct, pk=obj.pk): obj}, timeout=timeout) return obj
[ "def", "get_cached_object", "(", "model", ",", "timeout", "=", "CACHE_TIMEOUT", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "model", ",", "ContentType", ")", ":", "model_ct", "=", "ContentType", ".", "objects", ".", "get_for_model", ...
Return a cached object. If the object does not exist in the cache, create it. Params: model - ContentType instance representing the model's class or the model class itself timeout - TTL for the item in cache, defaults to CACHE_TIMEOUT **kwargs - lookup parameters for content_type.get_object_for_this_type and for key creation Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type
[ "Return", "a", "cached", "object", ".", "If", "the", "object", "does", "not", "exist", "in", "the", "cache", "create", "it", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L70-L107
4,756
ella/ella
ella/core/cache/utils.py
get_cached_objects
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE): """ Return a list of objects with given PKs using cache. Params: pks - list of Primary Key values to look up or list of content_type_id, pk tuples model - ContentType instance representing the model's class or the model class itself timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type """ if model is not None: if not isinstance(model, ContentType): model = ContentType.objects.get_for_model(model) pks = [(model, pk) for pk in pks] else: pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks] keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks] cached = cache.get_many(keys) # keys not in cache keys_to_set = set(keys) - set(cached.keys()) if keys_to_set: # build lookup to get model and pks from the key lookup = dict(zip(keys, pks)) to_get = {} # group lookups by CT so we can do in_bulk for k in keys_to_set: ct, pk = lookup[k] to_get.setdefault(ct, {})[int(pk)] = k # take out all the publishables publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable')) if publishable_ct in to_get: publishable_keys = to_get.pop(publishable_ct) models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys()) for m in models: ct = ContentType.objects.get_for_id(m['content_type_id']) pk = m['id'] # and put them back as their native content_type to_get.setdefault(ct, {})[pk] = publishable_keys[pk] to_set = {} # retrieve all the models from DB for ct, vals in to_get.items(): models = ct.model_class()._default_manager.in_bulk(vals.keys()) for pk, m in models.items(): k = vals[pk] cached[k] = to_set[k] = m if not isinstance(cache, DummyCache): # write them into cache cache.set_many(to_set, timeout=timeout) out = [] for k in keys: try: out.append(cached[k]) except KeyError: if missing == NONE: out.append(None) elif missing == SKIP: pass elif missing == RAISE: ct = ContentType.objects.get_for_id(int(k.split(':')[1])) raise ct.model_class().DoesNotExist( '%s matching query does not exist.' % ct.model_class()._meta.object_name) return out
python
def get_cached_objects(pks, model=None, timeout=CACHE_TIMEOUT, missing=RAISE): if model is not None: if not isinstance(model, ContentType): model = ContentType.objects.get_for_model(model) pks = [(model, pk) for pk in pks] else: pks = [(ContentType.objects.get_for_id(ct_id), pk) for (ct_id, pk) in pks] keys = [_get_key(KEY_PREFIX, model, pk=pk) for (model, pk) in pks] cached = cache.get_many(keys) # keys not in cache keys_to_set = set(keys) - set(cached.keys()) if keys_to_set: # build lookup to get model and pks from the key lookup = dict(zip(keys, pks)) to_get = {} # group lookups by CT so we can do in_bulk for k in keys_to_set: ct, pk = lookup[k] to_get.setdefault(ct, {})[int(pk)] = k # take out all the publishables publishable_ct = ContentType.objects.get_for_model(get_model('core', 'publishable')) if publishable_ct in to_get: publishable_keys = to_get.pop(publishable_ct) models = publishable_ct.model_class()._default_manager.values('content_type_id', 'id').filter(id__in=publishable_keys.keys()) for m in models: ct = ContentType.objects.get_for_id(m['content_type_id']) pk = m['id'] # and put them back as their native content_type to_get.setdefault(ct, {})[pk] = publishable_keys[pk] to_set = {} # retrieve all the models from DB for ct, vals in to_get.items(): models = ct.model_class()._default_manager.in_bulk(vals.keys()) for pk, m in models.items(): k = vals[pk] cached[k] = to_set[k] = m if not isinstance(cache, DummyCache): # write them into cache cache.set_many(to_set, timeout=timeout) out = [] for k in keys: try: out.append(cached[k]) except KeyError: if missing == NONE: out.append(None) elif missing == SKIP: pass elif missing == RAISE: ct = ContentType.objects.get_for_id(int(k.split(':')[1])) raise ct.model_class().DoesNotExist( '%s matching query does not exist.' % ct.model_class()._meta.object_name) return out
[ "def", "get_cached_objects", "(", "pks", ",", "model", "=", "None", ",", "timeout", "=", "CACHE_TIMEOUT", ",", "missing", "=", "RAISE", ")", ":", "if", "model", "is", "not", "None", ":", "if", "not", "isinstance", "(", "model", ",", "ContentType", ")", ...
Return a list of objects with given PKs using cache. Params: pks - list of Primary Key values to look up or list of content_type_id, pk tuples model - ContentType instance representing the model's class or the model class itself timeout - TTL for the items in cache, defaults to CACHE_TIMEOUT Throws: model.DoesNotExist is propagated from content_type.get_object_for_this_type
[ "Return", "a", "list", "of", "objects", "with", "given", "PKs", "using", "cache", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L113-L184
4,757
ella/ella
ella/core/cache/utils.py
get_cached_object_or_404
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs): """ Shortcut that will raise Http404 if there is no object matching the query see get_cached_object for params description """ try: return get_cached_object(model, timeout=timeout, **kwargs) except ObjectDoesNotExist, e: raise Http404('Reason: %s' % str(e))
python
def get_cached_object_or_404(model, timeout=CACHE_TIMEOUT, **kwargs): try: return get_cached_object(model, timeout=timeout, **kwargs) except ObjectDoesNotExist, e: raise Http404('Reason: %s' % str(e))
[ "def", "get_cached_object_or_404", "(", "model", ",", "timeout", "=", "CACHE_TIMEOUT", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "get_cached_object", "(", "model", ",", "timeout", "=", "timeout", ",", "*", "*", "kwargs", ")", "except", "Obje...
Shortcut that will raise Http404 if there is no object matching the query see get_cached_object for params description
[ "Shortcut", "that", "will", "raise", "Http404", "if", "there", "is", "no", "object", "matching", "the", "query" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/cache/utils.py#L187-L196
4,758
ssalentin/plip
plip/modules/supplemental.py
tmpfile
def tmpfile(prefix, direc): """Returns the path to a newly created temporary file.""" return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
python
def tmpfile(prefix, direc): return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc)
[ "def", "tmpfile", "(", "prefix", ",", "direc", ")", ":", "return", "tempfile", ".", "mktemp", "(", "prefix", "=", "prefix", ",", "suffix", "=", "'.pdb'", ",", "dir", "=", "direc", ")" ]
Returns the path to a newly created temporary file.
[ "Returns", "the", "path", "to", "a", "newly", "created", "temporary", "file", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L41-L43
4,759
ssalentin/plip
plip/modules/supplemental.py
extract_pdbid
def extract_pdbid(string): """Use regular expressions to get a PDB ID from a string""" p = re.compile("[0-9][0-9a-z]{3}") m = p.search(string.lower()) try: return m.group() except AttributeError: return "UnknownProtein"
python
def extract_pdbid(string): p = re.compile("[0-9][0-9a-z]{3}") m = p.search(string.lower()) try: return m.group() except AttributeError: return "UnknownProtein"
[ "def", "extract_pdbid", "(", "string", ")", ":", "p", "=", "re", ".", "compile", "(", "\"[0-9][0-9a-z]{3}\"", ")", "m", "=", "p", ".", "search", "(", "string", ".", "lower", "(", ")", ")", "try", ":", "return", "m", ".", "group", "(", ")", "except"...
Use regular expressions to get a PDB ID from a string
[ "Use", "regular", "expressions", "to", "get", "a", "PDB", "ID", "from", "a", "string" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L52-L59
4,760
ssalentin/plip
plip/modules/supplemental.py
whichrestype
def whichrestype(atom): """Returns the residue name of an Pybel or OpenBabel atom.""" atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetName() if atom.GetResidue() is not None else None
python
def whichrestype(atom): atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetName() if atom.GetResidue() is not None else None
[ "def", "whichrestype", "(", "atom", ")", ":", "atom", "=", "atom", "if", "not", "isinstance", "(", "atom", ",", "Atom", ")", "else", "atom", ".", "OBAtom", "# Convert to OpenBabel Atom", "return", "atom", ".", "GetResidue", "(", ")", ".", "GetName", "(", ...
Returns the residue name of an Pybel or OpenBabel atom.
[ "Returns", "the", "residue", "name", "of", "an", "Pybel", "or", "OpenBabel", "atom", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L62-L65
4,761
ssalentin/plip
plip/modules/supplemental.py
whichchain
def whichchain(atom): """Returns the residue number of an PyBel or OpenBabel atom.""" atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None
python
def whichchain(atom): atom = atom if not isinstance(atom, Atom) else atom.OBAtom # Convert to OpenBabel Atom return atom.GetResidue().GetChain() if atom.GetResidue() is not None else None
[ "def", "whichchain", "(", "atom", ")", ":", "atom", "=", "atom", "if", "not", "isinstance", "(", "atom", ",", "Atom", ")", "else", "atom", ".", "OBAtom", "# Convert to OpenBabel Atom", "return", "atom", ".", "GetResidue", "(", ")", ".", "GetChain", "(", ...
Returns the residue number of an PyBel or OpenBabel atom.
[ "Returns", "the", "residue", "number", "of", "an", "PyBel", "or", "OpenBabel", "atom", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L74-L77
4,762
ssalentin/plip
plip/modules/supplemental.py
euclidean3d
def euclidean3d(v1, v2): """Faster implementation of euclidean distance for the 3D case.""" if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
python
def euclidean3d(v1, v2): if not len(v1) == 3 and len(v2) == 3: print("Vectors are not in 3D space. Returning None.") return None return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2)
[ "def", "euclidean3d", "(", "v1", ",", "v2", ")", ":", "if", "not", "len", "(", "v1", ")", "==", "3", "and", "len", "(", "v2", ")", "==", "3", ":", "print", "(", "\"Vectors are not in 3D space. Returning None.\"", ")", "return", "None", "return", "np", ...
Faster implementation of euclidean distance for the 3D case.
[ "Faster", "implementation", "of", "euclidean", "distance", "for", "the", "3D", "case", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L84-L89
4,763
ssalentin/plip
plip/modules/supplemental.py
create_folder_if_not_exists
def create_folder_if_not_exists(folder_path): """Creates a folder if it does not exists.""" folder_path = tilde_expansion(folder_path) folder_path = "".join([folder_path, '/']) if not folder_path[-1] == '/' else folder_path direc = os.path.dirname(folder_path) if not folder_exists(direc): os.makedirs(direc)
python
def create_folder_if_not_exists(folder_path): folder_path = tilde_expansion(folder_path) folder_path = "".join([folder_path, '/']) if not folder_path[-1] == '/' else folder_path direc = os.path.dirname(folder_path) if not folder_exists(direc): os.makedirs(direc)
[ "def", "create_folder_if_not_exists", "(", "folder_path", ")", ":", "folder_path", "=", "tilde_expansion", "(", "folder_path", ")", "folder_path", "=", "\"\"", ".", "join", "(", "[", "folder_path", ",", "'/'", "]", ")", "if", "not", "folder_path", "[", "-", ...
Creates a folder if it does not exists.
[ "Creates", "a", "folder", "if", "it", "does", "not", "exists", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L206-L212
4,764
ssalentin/plip
plip/modules/supplemental.py
start_pymol
def start_pymol(quiet=False, options='-p', run=False): """Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output. Command line options can be passed as the second argument.""" import pymol pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:] if run: initialize_pymol(options) if quiet: pymol.cmd.feedback('disable', 'all', 'everything')
python
def start_pymol(quiet=False, options='-p', run=False): import pymol pymol.pymol_argv = ['pymol', '%s' % options] + sys.argv[1:] if run: initialize_pymol(options) if quiet: pymol.cmd.feedback('disable', 'all', 'everything')
[ "def", "start_pymol", "(", "quiet", "=", "False", ",", "options", "=", "'-p'", ",", "run", "=", "False", ")", ":", "import", "pymol", "pymol", ".", "pymol_argv", "=", "[", "'pymol'", ",", "'%s'", "%", "options", "]", "+", "sys", ".", "argv", "[", "...
Starts up PyMOL and sets general options. Quiet mode suppresses all PyMOL output. Command line options can be passed as the second argument.
[ "Starts", "up", "PyMOL", "and", "sets", "general", "options", ".", "Quiet", "mode", "suppresses", "all", "PyMOL", "output", ".", "Command", "line", "options", "can", "be", "passed", "as", "the", "second", "argument", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L231-L239
4,765
ssalentin/plip
plip/modules/supplemental.py
ring_is_planar
def ring_is_planar(ring, r_atoms): """Given a set of ring atoms, check if the ring is sufficiently planar to be considered aromatic""" normals = [] for a in r_atoms: adj = pybel.ob.OBAtomAtomIter(a.OBAtom) # Check for neighboring atoms in the ring n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)] vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1]) normals.append(np.cross(vec1, vec2)) # Given all normals of ring atoms and their neighbors, the angle between any has to be 5.0 deg or less for n1, n2 in itertools.product(normals, repeat=2): arom_angle = vecangle(n1, n2) if all([arom_angle > config.AROMATIC_PLANARITY, arom_angle < 180.0 - config.AROMATIC_PLANARITY]): return False return True
python
def ring_is_planar(ring, r_atoms): normals = [] for a in r_atoms: adj = pybel.ob.OBAtomAtomIter(a.OBAtom) # Check for neighboring atoms in the ring n_coords = [pybel.Atom(neigh).coords for neigh in adj if ring.IsMember(neigh)] vec1, vec2 = vector(a.coords, n_coords[0]), vector(a.coords, n_coords[1]) normals.append(np.cross(vec1, vec2)) # Given all normals of ring atoms and their neighbors, the angle between any has to be 5.0 deg or less for n1, n2 in itertools.product(normals, repeat=2): arom_angle = vecangle(n1, n2) if all([arom_angle > config.AROMATIC_PLANARITY, arom_angle < 180.0 - config.AROMATIC_PLANARITY]): return False return True
[ "def", "ring_is_planar", "(", "ring", ",", "r_atoms", ")", ":", "normals", "=", "[", "]", "for", "a", "in", "r_atoms", ":", "adj", "=", "pybel", ".", "ob", ".", "OBAtomAtomIter", "(", "a", ".", "OBAtom", ")", "# Check for neighboring atoms in the ring", "n...
Given a set of ring atoms, check if the ring is sufficiently planar to be considered aromatic
[ "Given", "a", "set", "of", "ring", "atoms", "check", "if", "the", "ring", "is", "sufficiently", "planar", "to", "be", "considered", "aromatic" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L274-L289
4,766
ssalentin/plip
plip/modules/supplemental.py
get_isomorphisms
def get_isomorphisms(reference, lig): """Get all isomorphisms of the ligand.""" query = pybel.ob.CompileMoleculeQuery(reference.OBMol) mappr = pybel.ob.OBIsomorphismMapper.GetInstance(query) if all: isomorphs = pybel.ob.vvpairUIntUInt() mappr.MapAll(lig.OBMol, isomorphs) else: isomorphs = pybel.ob.vpairUIntUInt() mappr.MapFirst(lig.OBMol, isomorphs) isomorphs = [isomorphs] write_message("Number of isomorphisms: %i\n" % len(isomorphs), mtype='debug') # #@todo Check which isomorphism to take return isomorphs
python
def get_isomorphisms(reference, lig): query = pybel.ob.CompileMoleculeQuery(reference.OBMol) mappr = pybel.ob.OBIsomorphismMapper.GetInstance(query) if all: isomorphs = pybel.ob.vvpairUIntUInt() mappr.MapAll(lig.OBMol, isomorphs) else: isomorphs = pybel.ob.vpairUIntUInt() mappr.MapFirst(lig.OBMol, isomorphs) isomorphs = [isomorphs] write_message("Number of isomorphisms: %i\n" % len(isomorphs), mtype='debug') # #@todo Check which isomorphism to take return isomorphs
[ "def", "get_isomorphisms", "(", "reference", ",", "lig", ")", ":", "query", "=", "pybel", ".", "ob", ".", "CompileMoleculeQuery", "(", "reference", ".", "OBMol", ")", "mappr", "=", "pybel", ".", "ob", ".", "OBIsomorphismMapper", ".", "GetInstance", "(", "q...
Get all isomorphisms of the ligand.
[ "Get", "all", "isomorphisms", "of", "the", "ligand", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L326-L339
4,767
ssalentin/plip
plip/modules/supplemental.py
canonicalize
def canonicalize(lig, preserve_bond_order=False): """Get the canonical atom order for the ligand.""" atomorder = None # Get canonical atom order lig = pybel.ob.OBMol(lig.OBMol) if not preserve_bond_order: for bond in pybel.ob.OBMolBondIter(lig): if bond.GetBondOrder() != 1: bond.SetBondOrder(1) lig.DeleteData(pybel.ob.StereoData) lig = pybel.Molecule(lig) testcan = lig.write(format='can') try: pybel.readstring('can', testcan) reference = pybel.readstring('can', testcan) except IOError: testcan, reference = '', '' if testcan != '': reference.removeh() isomorphs = get_isomorphisms(reference, lig) # isomorphs now holds all isomorphisms within the molecule if not len(isomorphs) == 0: smi_dict = {} smi_to_can = isomorphs[0] for x in smi_to_can: smi_dict[int(x[1]) + 1] = int(x[0]) + 1 atomorder = [smi_dict[x + 1] for x in range(len(lig.atoms))] else: atomorder = None return atomorder
python
def canonicalize(lig, preserve_bond_order=False): atomorder = None # Get canonical atom order lig = pybel.ob.OBMol(lig.OBMol) if not preserve_bond_order: for bond in pybel.ob.OBMolBondIter(lig): if bond.GetBondOrder() != 1: bond.SetBondOrder(1) lig.DeleteData(pybel.ob.StereoData) lig = pybel.Molecule(lig) testcan = lig.write(format='can') try: pybel.readstring('can', testcan) reference = pybel.readstring('can', testcan) except IOError: testcan, reference = '', '' if testcan != '': reference.removeh() isomorphs = get_isomorphisms(reference, lig) # isomorphs now holds all isomorphisms within the molecule if not len(isomorphs) == 0: smi_dict = {} smi_to_can = isomorphs[0] for x in smi_to_can: smi_dict[int(x[1]) + 1] = int(x[0]) + 1 atomorder = [smi_dict[x + 1] for x in range(len(lig.atoms))] else: atomorder = None return atomorder
[ "def", "canonicalize", "(", "lig", ",", "preserve_bond_order", "=", "False", ")", ":", "atomorder", "=", "None", "# Get canonical atom order", "lig", "=", "pybel", ".", "ob", ".", "OBMol", "(", "lig", ".", "OBMol", ")", "if", "not", "preserve_bond_order", ":...
Get the canonical atom order for the ligand.
[ "Get", "the", "canonical", "atom", "order", "for", "the", "ligand", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L342-L371
4,768
ssalentin/plip
plip/modules/supplemental.py
read_pdb
def read_pdb(pdbfname, as_string=False): """Reads a given PDB file and returns a Pybel Molecule.""" pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings if os.name != 'nt': # Resource module not available for Windows maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1] resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize)) sys.setrecursionlimit(10 ** 5) # increase Python recoursion limit return readmol(pdbfname, as_string=as_string)
python
def read_pdb(pdbfname, as_string=False): pybel.ob.obErrorLog.StopLogging() # Suppress all OpenBabel warnings if os.name != 'nt': # Resource module not available for Windows maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1] resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize)) sys.setrecursionlimit(10 ** 5) # increase Python recoursion limit return readmol(pdbfname, as_string=as_string)
[ "def", "read_pdb", "(", "pdbfname", ",", "as_string", "=", "False", ")", ":", "pybel", ".", "ob", ".", "obErrorLog", ".", "StopLogging", "(", ")", "# Suppress all OpenBabel warnings", "if", "os", ".", "name", "!=", "'nt'", ":", "# Resource module not available f...
Reads a given PDB file and returns a Pybel Molecule.
[ "Reads", "a", "given", "PDB", "file", "and", "returns", "a", "Pybel", "Molecule", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L389-L396
4,769
ssalentin/plip
plip/modules/supplemental.py
read
def read(fil): """Returns a file handler and detects gzipped files.""" if os.path.splitext(fil)[-1] == '.gz': return gzip.open(fil, 'rb') elif os.path.splitext(fil)[-1] == '.zip': zf = zipfile.ZipFile(fil, 'r') return zf.open(zf.infolist()[0].filename) else: return open(fil, 'r')
python
def read(fil): if os.path.splitext(fil)[-1] == '.gz': return gzip.open(fil, 'rb') elif os.path.splitext(fil)[-1] == '.zip': zf = zipfile.ZipFile(fil, 'r') return zf.open(zf.infolist()[0].filename) else: return open(fil, 'r')
[ "def", "read", "(", "fil", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "fil", ")", "[", "-", "1", "]", "==", "'.gz'", ":", "return", "gzip", ".", "open", "(", "fil", ",", "'rb'", ")", "elif", "os", ".", "path", ".", "splitext", "...
Returns a file handler and detects gzipped files.
[ "Returns", "a", "file", "handler", "and", "detects", "gzipped", "files", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L399-L407
4,770
ssalentin/plip
plip/modules/supplemental.py
readmol
def readmol(path, as_string=False): """Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type. In contrast to the standard Pybel implementation, the file is closed properly.""" supported_formats = ['pdb'] # Fix for Windows-generated files: Remove carriage return characters if "\r" in path and as_string: path = path.replace('\r', '') for sformat in supported_formats: obc = pybel.ob.OBConversion() obc.SetInFormat(sformat) write_message("Detected {} as format. Trying to read file with OpenBabel...\n".format(sformat), mtype='debug') # Read molecules with single bond information if as_string: try: mymol = pybel.readstring(sformat, path) except IOError: sysexit(4, 'No valid file format provided.') else: read_file = pybel.readfile(format=sformat, filename=path, opt={"s": None}) try: mymol = next(read_file) except StopIteration: sysexit(4, 'File contains no valid molecules.\n') write_message("Molecule successfully read.\n", mtype='debug') # Assign multiple bonds mymol.OBMol.PerceiveBondOrders() return mymol, sformat sysexit(4, 'No valid file format provided.')
python
def readmol(path, as_string=False): supported_formats = ['pdb'] # Fix for Windows-generated files: Remove carriage return characters if "\r" in path and as_string: path = path.replace('\r', '') for sformat in supported_formats: obc = pybel.ob.OBConversion() obc.SetInFormat(sformat) write_message("Detected {} as format. Trying to read file with OpenBabel...\n".format(sformat), mtype='debug') # Read molecules with single bond information if as_string: try: mymol = pybel.readstring(sformat, path) except IOError: sysexit(4, 'No valid file format provided.') else: read_file = pybel.readfile(format=sformat, filename=path, opt={"s": None}) try: mymol = next(read_file) except StopIteration: sysexit(4, 'File contains no valid molecules.\n') write_message("Molecule successfully read.\n", mtype='debug') # Assign multiple bonds mymol.OBMol.PerceiveBondOrders() return mymol, sformat sysexit(4, 'No valid file format provided.')
[ "def", "readmol", "(", "path", ",", "as_string", "=", "False", ")", ":", "supported_formats", "=", "[", "'pdb'", "]", "# Fix for Windows-generated files: Remove carriage return characters", "if", "\"\\r\"", "in", "path", "and", "as_string", ":", "path", "=", "path",...
Reads the given molecule file and returns the corresponding Pybel molecule as well as the input file type. In contrast to the standard Pybel implementation, the file is closed properly.
[ "Reads", "the", "given", "molecule", "file", "and", "returns", "the", "corresponding", "Pybel", "molecule", "as", "well", "as", "the", "input", "file", "type", ".", "In", "contrast", "to", "the", "standard", "Pybel", "implementation", "the", "file", "is", "c...
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L410-L442
4,771
ssalentin/plip
plip/modules/supplemental.py
colorlog
def colorlog(msg, color, bold=False, blink=False): """Colors messages on non-Windows systems supporting ANSI escape.""" # ANSI Escape Codes PINK_COL = '\x1b[35m' GREEN_COL = '\x1b[32m' RED_COL = '\x1b[31m' YELLOW_COL = '\x1b[33m' BLINK = '\x1b[5m' RESET = '\x1b[0m' if platform.system() != 'Windows': if blink: msg = BLINK + msg + RESET if color == 'yellow': msg = YELLOW_COL + msg + RESET if color == 'red': msg = RED_COL + msg + RESET if color == 'green': msg = GREEN_COL + msg + RESET if color == 'pink': msg = PINK_COL + msg + RESET return msg
python
def colorlog(msg, color, bold=False, blink=False): # ANSI Escape Codes PINK_COL = '\x1b[35m' GREEN_COL = '\x1b[32m' RED_COL = '\x1b[31m' YELLOW_COL = '\x1b[33m' BLINK = '\x1b[5m' RESET = '\x1b[0m' if platform.system() != 'Windows': if blink: msg = BLINK + msg + RESET if color == 'yellow': msg = YELLOW_COL + msg + RESET if color == 'red': msg = RED_COL + msg + RESET if color == 'green': msg = GREEN_COL + msg + RESET if color == 'pink': msg = PINK_COL + msg + RESET return msg
[ "def", "colorlog", "(", "msg", ",", "color", ",", "bold", "=", "False", ",", "blink", "=", "False", ")", ":", "# ANSI Escape Codes", "PINK_COL", "=", "'\\x1b[35m'", "GREEN_COL", "=", "'\\x1b[32m'", "RED_COL", "=", "'\\x1b[31m'", "YELLOW_COL", "=", "'\\x1b[33m'...
Colors messages on non-Windows systems supporting ANSI escape.
[ "Colors", "messages", "on", "non", "-", "Windows", "systems", "supporting", "ANSI", "escape", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L455-L477
4,772
ssalentin/plip
plip/modules/supplemental.py
write_message
def write_message(msg, indent=False, mtype='standard', caption=False): """Writes message if verbose mode is set.""" if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error': message(msg, indent=indent, mtype=mtype, caption=caption)
python
def write_message(msg, indent=False, mtype='standard', caption=False): if (mtype == 'debug' and config.DEBUG) or (mtype != 'debug' and config.VERBOSE) or mtype == 'error': message(msg, indent=indent, mtype=mtype, caption=caption)
[ "def", "write_message", "(", "msg", ",", "indent", "=", "False", ",", "mtype", "=", "'standard'", ",", "caption", "=", "False", ")", ":", "if", "(", "mtype", "==", "'debug'", "and", "config", ".", "DEBUG", ")", "or", "(", "mtype", "!=", "'debug'", "a...
Writes message if verbose mode is set.
[ "Writes", "message", "if", "verbose", "mode", "is", "set", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L480-L483
4,773
ssalentin/plip
plip/modules/supplemental.py
message
def message(msg, indent=False, mtype='standard', caption=False): """Writes messages in verbose mode""" if caption: msg = '\n' + msg + '\n' + '-'*len(msg) + '\n' if mtype == 'warning': msg = colorlog('Warning: ' + msg, 'yellow') if mtype == 'error': msg = colorlog('Error: ' + msg, 'red') if mtype == 'debug': msg = colorlog('Debug: ' + msg, 'pink') if mtype == 'info': msg = colorlog('Info: ' + msg, 'green') if indent: msg = ' ' + msg sys.stderr.write(msg)
python
def message(msg, indent=False, mtype='standard', caption=False): if caption: msg = '\n' + msg + '\n' + '-'*len(msg) + '\n' if mtype == 'warning': msg = colorlog('Warning: ' + msg, 'yellow') if mtype == 'error': msg = colorlog('Error: ' + msg, 'red') if mtype == 'debug': msg = colorlog('Debug: ' + msg, 'pink') if mtype == 'info': msg = colorlog('Info: ' + msg, 'green') if indent: msg = ' ' + msg sys.stderr.write(msg)
[ "def", "message", "(", "msg", ",", "indent", "=", "False", ",", "mtype", "=", "'standard'", ",", "caption", "=", "False", ")", ":", "if", "caption", ":", "msg", "=", "'\\n'", "+", "msg", "+", "'\\n'", "+", "'-'", "*", "len", "(", "msg", ")", "+",...
Writes messages in verbose mode
[ "Writes", "messages", "in", "verbose", "mode" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/supplemental.py#L486-L500
4,774
ella/ella
ella/core/templatetags/related.py
do_related
def do_related(parser, token): """ Get N related models into a context variable optionally specifying a named related finder. **Usage**:: {% related <limit>[ query_type] [app.model, ...] for <object> as <result> %} **Parameters**:: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``query_type`` Named finder to resolve the related objects, falls back to ``settings.DEFAULT_RELATED_FINDER`` when not specified. ``app.model``, ... List of allowed models, all if omitted. ``object`` Object to get the related for. ``result`` Store the resulting list in context under given name. ================================== ================================================ **Examples**:: {% related 10 for object as related_list %} {% related 10 directly articles.article, galleries.gallery for object as related_list %} """ bits = token.split_contents() obj_var, count, var_name, mods, finder = parse_related_tag(bits) return RelatedNode(obj_var, count, var_name, mods, finder)
python
def do_related(parser, token): bits = token.split_contents() obj_var, count, var_name, mods, finder = parse_related_tag(bits) return RelatedNode(obj_var, count, var_name, mods, finder)
[ "def", "do_related", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "obj_var", ",", "count", ",", "var_name", ",", "mods", ",", "finder", "=", "parse_related_tag", "(", "bits", ")", "return", "RelatedNode", ...
Get N related models into a context variable optionally specifying a named related finder. **Usage**:: {% related <limit>[ query_type] [app.model, ...] for <object> as <result> %} **Parameters**:: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``query_type`` Named finder to resolve the related objects, falls back to ``settings.DEFAULT_RELATED_FINDER`` when not specified. ``app.model``, ... List of allowed models, all if omitted. ``object`` Object to get the related for. ``result`` Store the resulting list in context under given name. ================================== ================================================ **Examples**:: {% related 10 for object as related_list %} {% related 10 directly articles.article, galleries.gallery for object as related_list %}
[ "Get", "N", "related", "models", "into", "a", "context", "variable", "optionally", "specifying", "a", "named", "related", "finder", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/related.py#L68-L98
4,775
ella/ella
ella/core/models/publishable.py
PublishableBox
def PublishableBox(publishable, box_type, nodelist, model=None): "add some content type info of self.target" if not model: model = publishable.content_type.model_class() box_class = model.box_class if box_class == PublishableBox: box_class = Box return box_class(publishable, box_type, nodelist, model=model)
python
def PublishableBox(publishable, box_type, nodelist, model=None): "add some content type info of self.target" if not model: model = publishable.content_type.model_class() box_class = model.box_class if box_class == PublishableBox: box_class = Box return box_class(publishable, box_type, nodelist, model=model)
[ "def", "PublishableBox", "(", "publishable", ",", "box_type", ",", "nodelist", ",", "model", "=", "None", ")", ":", "if", "not", "model", ":", "model", "=", "publishable", ".", "content_type", ".", "model_class", "(", ")", "box_class", "=", "model", ".", ...
add some content type info of self.target
[ "add", "some", "content", "type", "info", "of", "self", ".", "target" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L23-L31
4,776
ella/ella
ella/core/models/publishable.py
ListingBox
def ListingBox(listing, *args, **kwargs): " Delegate the boxing to the target's Box class. " obj = listing.publishable return obj.box_class(obj, *args, **kwargs)
python
def ListingBox(listing, *args, **kwargs): " Delegate the boxing to the target's Box class. " obj = listing.publishable return obj.box_class(obj, *args, **kwargs)
[ "def", "ListingBox", "(", "listing", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "obj", "=", "listing", ".", "publishable", "return", "obj", ".", "box_class", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Delegate the boxing to the target's Box class.
[ "Delegate", "the", "boxing", "to", "the", "target", "s", "Box", "class", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L225-L228
4,777
ella/ella
ella/core/models/publishable.py
Publishable.get_absolute_url
def get_absolute_url(self, domain=False): " Get object's URL. " category = self.category kwargs = { 'slug': self.slug, } if self.static: kwargs['id'] = self.pk if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('static_detail', kwargs=kwargs) else: url = reverse('home_static_detail', kwargs=kwargs) else: publish_from = localize(self.publish_from) kwargs.update({ 'year': publish_from.year, 'month': publish_from.month, 'day': publish_from.day, }) if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('object_detail', kwargs=kwargs) else: url = reverse('home_object_detail', kwargs=kwargs) if category.site_id != settings.SITE_ID or domain: return 'http://' + category.site.domain + url return url
python
def get_absolute_url(self, domain=False): " Get object's URL. " category = self.category kwargs = { 'slug': self.slug, } if self.static: kwargs['id'] = self.pk if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('static_detail', kwargs=kwargs) else: url = reverse('home_static_detail', kwargs=kwargs) else: publish_from = localize(self.publish_from) kwargs.update({ 'year': publish_from.year, 'month': publish_from.month, 'day': publish_from.day, }) if category.tree_parent_id: kwargs['category'] = category.tree_path url = reverse('object_detail', kwargs=kwargs) else: url = reverse('home_object_detail', kwargs=kwargs) if category.site_id != settings.SITE_ID or domain: return 'http://' + category.site.domain + url return url
[ "def", "get_absolute_url", "(", "self", ",", "domain", "=", "False", ")", ":", "category", "=", "self", ".", "category", "kwargs", "=", "{", "'slug'", ":", "self", ".", "slug", ",", "}", "if", "self", ".", "static", ":", "kwargs", "[", "'id'", "]", ...
Get object's URL.
[ "Get", "object", "s", "URL", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L90-L120
4,778
ella/ella
ella/core/models/publishable.py
Publishable.is_published
def is_published(self): "Return True if the Publishable is currently active." cur_time = now() return self.published and cur_time > self.publish_from and \ (self.publish_to is None or cur_time < self.publish_to)
python
def is_published(self): "Return True if the Publishable is currently active." cur_time = now() return self.published and cur_time > self.publish_from and \ (self.publish_to is None or cur_time < self.publish_to)
[ "def", "is_published", "(", "self", ")", ":", "cur_time", "=", "now", "(", ")", "return", "self", ".", "published", "and", "cur_time", ">", "self", ".", "publish_from", "and", "(", "self", ".", "publish_to", "is", "None", "or", "cur_time", "<", "self", ...
Return True if the Publishable is currently active.
[ "Return", "True", "if", "the", "Publishable", "is", "currently", "active", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/publishable.py#L218-L222
4,779
ella/ella
ella/core/box.py
Box.resolve_params
def resolve_params(self, text): " Parse the parameters into a dict. " params = MultiValueDict() for line in text.split('\n'): pair = line.split(':', 1) if len(pair) == 2: params.appendlist(pair[0].strip(), pair[1].strip()) return params
python
def resolve_params(self, text): " Parse the parameters into a dict. " params = MultiValueDict() for line in text.split('\n'): pair = line.split(':', 1) if len(pair) == 2: params.appendlist(pair[0].strip(), pair[1].strip()) return params
[ "def", "resolve_params", "(", "self", ",", "text", ")", ":", "params", "=", "MultiValueDict", "(", ")", "for", "line", "in", "text", ".", "split", "(", "'\\n'", ")", ":", "pair", "=", "line", ".", "split", "(", "':'", ",", "1", ")", "if", "len", ...
Parse the parameters into a dict.
[ "Parse", "the", "parameters", "into", "a", "dict", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L49-L56
4,780
ella/ella
ella/core/box.py
Box.prepare
def prepare(self, context): """ Do the pre-processing - render and parse the parameters and store them for further use in self.params. """ self.params = {} # no params, not even a newline if not self.nodelist: return # just static text, no vars, assume one TextNode if not self.nodelist.contains_nontext: text = self.nodelist[0].s.strip() # vars in params, we have to render else: context.push() context['object'] = self.obj text = self.nodelist.render(context) context.pop() if text: self.params = self.resolve_params(text) # override the default template from the parameters if 'template_name' in self.params: self.template_name = self.params['template_name']
python
def prepare(self, context): self.params = {} # no params, not even a newline if not self.nodelist: return # just static text, no vars, assume one TextNode if not self.nodelist.contains_nontext: text = self.nodelist[0].s.strip() # vars in params, we have to render else: context.push() context['object'] = self.obj text = self.nodelist.render(context) context.pop() if text: self.params = self.resolve_params(text) # override the default template from the parameters if 'template_name' in self.params: self.template_name = self.params['template_name']
[ "def", "prepare", "(", "self", ",", "context", ")", ":", "self", ".", "params", "=", "{", "}", "# no params, not even a newline", "if", "not", "self", ".", "nodelist", ":", "return", "# just static text, no vars, assume one TextNode", "if", "not", "self", ".", "...
Do the pre-processing - render and parse the parameters and store them for further use in self.params.
[ "Do", "the", "pre", "-", "processing", "-", "render", "and", "parse", "the", "parameters", "and", "store", "them", "for", "further", "use", "in", "self", ".", "params", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L58-L85
4,781
ella/ella
ella/core/box.py
Box.get_context
def get_context(self): " Get context to render the template. " return { 'content_type_name' : str(self.name), 'content_type_verbose_name' : self.verbose_name, 'content_type_verbose_name_plural' : self.verbose_name_plural, 'object' : self.obj, 'box' : self, }
python
def get_context(self): " Get context to render the template. " return { 'content_type_name' : str(self.name), 'content_type_verbose_name' : self.verbose_name, 'content_type_verbose_name_plural' : self.verbose_name_plural, 'object' : self.obj, 'box' : self, }
[ "def", "get_context", "(", "self", ")", ":", "return", "{", "'content_type_name'", ":", "str", "(", "self", ".", "name", ")", ",", "'content_type_verbose_name'", ":", "self", ".", "verbose_name", ",", "'content_type_verbose_name_plural'", ":", "self", ".", "verb...
Get context to render the template.
[ "Get", "context", "to", "render", "the", "template", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L87-L95
4,782
ella/ella
ella/core/box.py
Box._render
def _render(self, context): " The main function that takes care of the rendering. " if self.template_name: t = loader.get_template(self.template_name) else: t_list = self._get_template_list() t = loader.select_template(t_list) context.update(self.get_context()) resp = t.render(context) context.pop() return resp
python
def _render(self, context): " The main function that takes care of the rendering. " if self.template_name: t = loader.get_template(self.template_name) else: t_list = self._get_template_list() t = loader.select_template(t_list) context.update(self.get_context()) resp = t.render(context) context.pop() return resp
[ "def", "_render", "(", "self", ",", "context", ")", ":", "if", "self", ".", "template_name", ":", "t", "=", "loader", ".", "get_template", "(", "self", ".", "template_name", ")", "else", ":", "t_list", "=", "self", ".", "_get_template_list", "(", ")", ...
The main function that takes care of the rendering.
[ "The", "main", "function", "that", "takes", "care", "of", "the", "rendering", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L143-L154
4,783
ella/ella
ella/core/box.py
Box.get_cache_key
def get_cache_key(self): " Return a cache key constructed from the box's parameters. " if not self.is_model: return None pars = '' if self.params: pars = ','.join(':'.join((smart_str(key), smart_str(self.params[key]))) for key in sorted(self.params.keys())) return normalize_key('%s:box:%d:%s:%s' % ( _get_key(KEY_PREFIX, self.ct, pk=self.obj.pk), settings.SITE_ID, str(self.box_type), pars ))
python
def get_cache_key(self): " Return a cache key constructed from the box's parameters. " if not self.is_model: return None pars = '' if self.params: pars = ','.join(':'.join((smart_str(key), smart_str(self.params[key]))) for key in sorted(self.params.keys())) return normalize_key('%s:box:%d:%s:%s' % ( _get_key(KEY_PREFIX, self.ct, pk=self.obj.pk), settings.SITE_ID, str(self.box_type), pars ))
[ "def", "get_cache_key", "(", "self", ")", ":", "if", "not", "self", ".", "is_model", ":", "return", "None", "pars", "=", "''", "if", "self", ".", "params", ":", "pars", "=", "','", ".", "join", "(", "':'", ".", "join", "(", "(", "smart_str", "(", ...
Return a cache key constructed from the box's parameters.
[ "Return", "a", "cache", "key", "constructed", "from", "the", "box", "s", "parameters", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/box.py#L156-L167
4,784
ella/ella
ella/core/models/main.py
Category.get_absolute_url
def get_absolute_url(self): """ Returns absolute URL for the category. """ if not self.tree_parent_id: url = reverse('root_homepage') else: url = reverse('category_detail', kwargs={'category' : self.tree_path}) if self.site_id != settings.SITE_ID: # prepend the domain if it doesn't match current Site return 'http://' + self.site.domain + url return url
python
def get_absolute_url(self): if not self.tree_parent_id: url = reverse('root_homepage') else: url = reverse('category_detail', kwargs={'category' : self.tree_path}) if self.site_id != settings.SITE_ID: # prepend the domain if it doesn't match current Site return 'http://' + self.site.domain + url return url
[ "def", "get_absolute_url", "(", "self", ")", ":", "if", "not", "self", ".", "tree_parent_id", ":", "url", "=", "reverse", "(", "'root_homepage'", ")", "else", ":", "url", "=", "reverse", "(", "'category_detail'", ",", "kwargs", "=", "{", "'category'", ":",...
Returns absolute URL for the category.
[ "Returns", "absolute", "URL", "for", "the", "category", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/models/main.py#L169-L180
4,785
ella/ella
ella/core/templatetags/core.py
listing
def listing(parser, token): """ Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <result> %} Parameters: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``offset`` Starting with number (1-based), starts from first if no offset specified. ``app.model``, ... List of allowed models, all if omitted. ``category`` Category of the listing, all categories if not specified. Can be either string (tree path), or variable containing a Category object. ``children`` Include items from direct subcategories. ``descendents`` Include items from all descend subcategories. ``exclude`` Variable including a ``Publishable`` to omit. ``using`` Name of Listing Handler ro use ``result`` Store the resulting list in context under given name. ================================== ================================================ Examples:: {% listing 10 of articles.article for "home_page" as obj_list %} {% listing 10 of articles.article for category as obj_list %} {% listing 10 of articles.article for category with children as obj_list %} {% listing 10 of articles.article for category with descendents as obj_list %} {% listing 10 from 10 of articles.article as obj_list %} {% listing 10 of articles.article, photos.photo as obj_list %} """ var_name, parameters = listing_parse(token.split_contents()) return ListingNode(var_name, parameters)
python
def listing(parser, token): var_name, parameters = listing_parse(token.split_contents()) return ListingNode(var_name, parameters)
[ "def", "listing", "(", "parser", ",", "token", ")", ":", "var_name", ",", "parameters", "=", "listing_parse", "(", "token", ".", "split_contents", "(", ")", ")", "return", "ListingNode", "(", "var_name", ",", "parameters", ")" ]
Tag that will obtain listing of top objects for a given category and store them in context under given name. Usage:: {% listing <limit>[ from <offset>][of <app.model>[, <app.model>[, ...]]][ for <category> ] [with children|descendents] [using listing_handler] as <result> %} Parameters: ================================== ================================================ Option Description ================================== ================================================ ``limit`` Number of objects to retrieve. ``offset`` Starting with number (1-based), starts from first if no offset specified. ``app.model``, ... List of allowed models, all if omitted. ``category`` Category of the listing, all categories if not specified. Can be either string (tree path), or variable containing a Category object. ``children`` Include items from direct subcategories. ``descendents`` Include items from all descend subcategories. ``exclude`` Variable including a ``Publishable`` to omit. ``using`` Name of Listing Handler ro use ``result`` Store the resulting list in context under given name. ================================== ================================================ Examples:: {% listing 10 of articles.article for "home_page" as obj_list %} {% listing 10 of articles.article for category as obj_list %} {% listing 10 of articles.article for category with children as obj_list %} {% listing 10 of articles.article for category with descendents as obj_list %} {% listing 10 from 10 of articles.article as obj_list %} {% listing 10 of articles.article, photos.photo as obj_list %}
[ "Tag", "that", "will", "obtain", "listing", "of", "top", "objects", "for", "a", "given", "category", "and", "store", "them", "in", "context", "under", "given", "name", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L50-L88
4,786
ella/ella
ella/core/templatetags/core.py
do_render
def do_render(parser, token): """ Renders a rich-text field using defined markup. Example:: {% render some_var %} """ bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError() return RenderNode(bits[1])
python
def do_render(parser, token): bits = token.split_contents() if len(bits) != 2: raise template.TemplateSyntaxError() return RenderNode(bits[1])
[ "def", "do_render", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "!=", "2", ":", "raise", "template", ".", "TemplateSyntaxError", "(", ")", "return", "RenderNode", "(", "bi...
Renders a rich-text field using defined markup. Example:: {% render some_var %}
[ "Renders", "a", "rich", "-", "text", "field", "using", "defined", "markup", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L332-L345
4,787
ella/ella
ella/core/templatetags/core.py
ipblur
def ipblur(text): # brutalizer ;-) """ blurs IP address """ import re m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text) if not m: return text return '%sxxx' % m.group(1)
python
def ipblur(text): # brutalizer ;-) import re m = re.match(r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.)\d{1,3}.*', text) if not m: return text return '%sxxx' % m.group(1)
[ "def", "ipblur", "(", "text", ")", ":", "# brutalizer ;-)", "import", "re", "m", "=", "re", ".", "match", "(", "r'^(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.)\\d{1,3}.*'", ",", "text", ")", "if", "not", "m", ":", "return", "text", "return", "'%sxxx'", "%", "m", ".",...
blurs IP address
[ "blurs", "IP", "address" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/templatetags/core.py#L349-L355
4,788
ella/ella
ella/utils/installedapps.py
register
def register(app_name, modules): """ simple module registering for later usage we don't want to import admin.py in models.py """ global INSTALLED_APPS_REGISTER mod_list = INSTALLED_APPS_REGISTER.get(app_name, []) if isinstance(modules, basestring): mod_list.append(modules) elif is_iterable(modules): mod_list.extend(modules) INSTALLED_APPS_REGISTER[app_name] = mod_list
python
def register(app_name, modules): global INSTALLED_APPS_REGISTER mod_list = INSTALLED_APPS_REGISTER.get(app_name, []) if isinstance(modules, basestring): mod_list.append(modules) elif is_iterable(modules): mod_list.extend(modules) INSTALLED_APPS_REGISTER[app_name] = mod_list
[ "def", "register", "(", "app_name", ",", "modules", ")", ":", "global", "INSTALLED_APPS_REGISTER", "mod_list", "=", "INSTALLED_APPS_REGISTER", ".", "get", "(", "app_name", ",", "[", "]", ")", "if", "isinstance", "(", "modules", ",", "basestring", ")", ":", "...
simple module registering for later usage we don't want to import admin.py in models.py
[ "simple", "module", "registering", "for", "later", "usage", "we", "don", "t", "want", "to", "import", "admin", ".", "py", "in", "models", ".", "py" ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/utils/installedapps.py#L11-L24
4,789
ella/ella
ella/core/related_finders.py
related_by_category
def related_by_category(obj, count, collected_so_far, mods=[], only_from_same_site=True): """ Returns other Publishable objects related to ``obj`` by using the same category principle. Returns up to ``count`` objects. """ related = [] # top objects in given category if count > 0: from ella.core.models import Listing cat = obj.category listings = Listing.objects.get_queryset_wrapper( category=cat, content_types=[ContentType.objects.get_for_model(m) for m in mods] ) for l in listings[0:count + len(related)]: t = l.publishable if t != obj and t not in collected_so_far and t not in related: related.append(t) count -= 1 if count <= 0: return related return related
python
def related_by_category(obj, count, collected_so_far, mods=[], only_from_same_site=True): related = [] # top objects in given category if count > 0: from ella.core.models import Listing cat = obj.category listings = Listing.objects.get_queryset_wrapper( category=cat, content_types=[ContentType.objects.get_for_model(m) for m in mods] ) for l in listings[0:count + len(related)]: t = l.publishable if t != obj and t not in collected_so_far and t not in related: related.append(t) count -= 1 if count <= 0: return related return related
[ "def", "related_by_category", "(", "obj", ",", "count", ",", "collected_so_far", ",", "mods", "=", "[", "]", ",", "only_from_same_site", "=", "True", ")", ":", "related", "=", "[", "]", "# top objects in given category", "if", "count", ">", "0", ":", "from",...
Returns other Publishable objects related to ``obj`` by using the same category principle. Returns up to ``count`` objects.
[ "Returns", "other", "Publishable", "objects", "related", "to", "obj", "by", "using", "the", "same", "category", "principle", ".", "Returns", "up", "to", "count", "objects", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/related_finders.py#L7-L29
4,790
ella/ella
ella/core/related_finders.py
directly_related
def directly_related(obj, count, collected_so_far, mods=[], only_from_same_site=True): """ Returns objects related to ``obj`` up to ``count`` by searching ``Related`` instances for the ``obj``. """ # manually entered dependencies qset = Related.objects.filter(publishable=obj) if mods: qset = qset.filter(related_ct__in=[ ContentType.objects.get_for_model(m).pk for m in mods]) return get_cached_objects(qset.values_list('related_ct', 'related_id')[:count], missing=SKIP)
python
def directly_related(obj, count, collected_so_far, mods=[], only_from_same_site=True): # manually entered dependencies qset = Related.objects.filter(publishable=obj) if mods: qset = qset.filter(related_ct__in=[ ContentType.objects.get_for_model(m).pk for m in mods]) return get_cached_objects(qset.values_list('related_ct', 'related_id')[:count], missing=SKIP)
[ "def", "directly_related", "(", "obj", ",", "count", ",", "collected_so_far", ",", "mods", "=", "[", "]", ",", "only_from_same_site", "=", "True", ")", ":", "# manually entered dependencies", "qset", "=", "Related", ".", "objects", ".", "filter", "(", "publish...
Returns objects related to ``obj`` up to ``count`` by searching ``Related`` instances for the ``obj``.
[ "Returns", "objects", "related", "to", "obj", "up", "to", "count", "by", "searching", "Related", "instances", "for", "the", "obj", "." ]
4a1414991f649dc21c4b777dc6b41a922a13faa7
https://github.com/ella/ella/blob/4a1414991f649dc21c4b777dc6b41a922a13faa7/ella/core/related_finders.py#L32-L44
4,791
ssalentin/plip
plip/modules/report.py
StructureReport.construct_xml_tree
def construct_xml_tree(self): """Construct the basic XML tree""" report = et.Element('report') plipversion = et.SubElement(report, 'plipversion') plipversion.text = __version__ date_of_creation = et.SubElement(report, 'date_of_creation') date_of_creation.text = time.strftime("%Y/%m/%d") citation_information = et.SubElement(report, 'citation_information') citation_information.text = "Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler. " \ "Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315" mode = et.SubElement(report, 'mode') if config.DNARECEPTOR: mode.text = 'dna_receptor' else: mode.text = 'default' pdbid = et.SubElement(report, 'pdbid') pdbid.text = self.mol.pymol_name.upper() filetype = et.SubElement(report, 'filetype') filetype.text = self.mol.filetype.upper() pdbfile = et.SubElement(report, 'pdbfile') pdbfile.text = self.mol.sourcefiles['pdbcomplex'] pdbfixes = et.SubElement(report, 'pdbfixes') pdbfixes.text = str(self.mol.information['pdbfixes']) filename = et.SubElement(report, 'filename') filename.text = str(self.mol.sourcefiles.get('filename') or None) exligs = et.SubElement(report, 'excluded_ligands') for i, exlig in enumerate(self.excluded): e = et.SubElement(exligs, 'excluded_ligand', id=str(i + 1)) e.text = exlig covalent = et.SubElement(report, 'covlinkages') for i, covlinkage in enumerate(self.mol.covalent): e = et.SubElement(covalent, 'covlinkage', id=str(i + 1)) f1 = et.SubElement(e, 'res1') f2 = et.SubElement(e, 'res2') f1.text = ":".join([covlinkage.id1, covlinkage.chain1, str(covlinkage.pos1)]) f2.text = ":".join([covlinkage.id2, covlinkage.chain2, str(covlinkage.pos2)]) return report
python
def construct_xml_tree(self): report = et.Element('report') plipversion = et.SubElement(report, 'plipversion') plipversion.text = __version__ date_of_creation = et.SubElement(report, 'date_of_creation') date_of_creation.text = time.strftime("%Y/%m/%d") citation_information = et.SubElement(report, 'citation_information') citation_information.text = "Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler. " \ "Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315" mode = et.SubElement(report, 'mode') if config.DNARECEPTOR: mode.text = 'dna_receptor' else: mode.text = 'default' pdbid = et.SubElement(report, 'pdbid') pdbid.text = self.mol.pymol_name.upper() filetype = et.SubElement(report, 'filetype') filetype.text = self.mol.filetype.upper() pdbfile = et.SubElement(report, 'pdbfile') pdbfile.text = self.mol.sourcefiles['pdbcomplex'] pdbfixes = et.SubElement(report, 'pdbfixes') pdbfixes.text = str(self.mol.information['pdbfixes']) filename = et.SubElement(report, 'filename') filename.text = str(self.mol.sourcefiles.get('filename') or None) exligs = et.SubElement(report, 'excluded_ligands') for i, exlig in enumerate(self.excluded): e = et.SubElement(exligs, 'excluded_ligand', id=str(i + 1)) e.text = exlig covalent = et.SubElement(report, 'covlinkages') for i, covlinkage in enumerate(self.mol.covalent): e = et.SubElement(covalent, 'covlinkage', id=str(i + 1)) f1 = et.SubElement(e, 'res1') f2 = et.SubElement(e, 'res2') f1.text = ":".join([covlinkage.id1, covlinkage.chain1, str(covlinkage.pos1)]) f2.text = ":".join([covlinkage.id2, covlinkage.chain2, str(covlinkage.pos2)]) return report
[ "def", "construct_xml_tree", "(", "self", ")", ":", "report", "=", "et", ".", "Element", "(", "'report'", ")", "plipversion", "=", "et", ".", "SubElement", "(", "report", ",", "'plipversion'", ")", "plipversion", ".", "text", "=", "__version__", "date_of_cre...
Construct the basic XML tree
[ "Construct", "the", "basic", "XML", "tree" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L37-L73
4,792
ssalentin/plip
plip/modules/report.py
StructureReport.construct_txt_file
def construct_txt_file(self): """Construct the header of the txt file""" textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftime("%Y/%m/%d"), __version__)) textlines.append('If you are using PLIP in your work, please cite:') textlines.append('Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler.') textlines.append('Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315\n') if len(self.excluded) != 0: textlines.append('Excluded molecules as ligands: %s\n' % ','.join([lig for lig in self.excluded])) if config.DNARECEPTOR: textlines.append('DNA/RNA in structure was chosen as the receptor part.\n') return textlines
python
def construct_txt_file(self): textlines = ['Prediction of noncovalent interactions for PDB structure %s' % self.mol.pymol_name.upper(), ] textlines.append("=" * len(textlines[0])) textlines.append('Created on %s using PLIP v%s\n' % (time.strftime("%Y/%m/%d"), __version__)) textlines.append('If you are using PLIP in your work, please cite:') textlines.append('Salentin,S. et al. PLIP: fully automated protein-ligand interaction profiler.') textlines.append('Nucl. Acids Res. (1 July 2015) 43 (W1): W443-W447. doi: 10.1093/nar/gkv315\n') if len(self.excluded) != 0: textlines.append('Excluded molecules as ligands: %s\n' % ','.join([lig for lig in self.excluded])) if config.DNARECEPTOR: textlines.append('DNA/RNA in structure was chosen as the receptor part.\n') return textlines
[ "def", "construct_txt_file", "(", "self", ")", ":", "textlines", "=", "[", "'Prediction of noncovalent interactions for PDB structure %s'", "%", "self", ".", "mol", ".", "pymol_name", ".", "upper", "(", ")", ",", "]", "textlines", ".", "append", "(", "\"=\"", "*...
Construct the header of the txt file
[ "Construct", "the", "header", "of", "the", "txt", "file" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L75-L87
4,793
ssalentin/plip
plip/modules/report.py
StructureReport.get_bindingsite_data
def get_bindingsite_data(self): """Get the additional data for the binding sites""" for i, site in enumerate(sorted(self.mol.interaction_sets)): s = self.mol.interaction_sets[site] bindingsite = BindingSiteReport(s).generate_xml() bindingsite.set('id', str(i + 1)) bindingsite.set('has_interactions', 'False') self.xmlreport.insert(i + 1, bindingsite) for itype in BindingSiteReport(s).generate_txt(): self.txtreport.append(itype) if not s.no_interactions: bindingsite.set('has_interactions', 'True') else: self.txtreport.append('No interactions detected.') sys.stdout = sys.__stdout__
python
def get_bindingsite_data(self): for i, site in enumerate(sorted(self.mol.interaction_sets)): s = self.mol.interaction_sets[site] bindingsite = BindingSiteReport(s).generate_xml() bindingsite.set('id', str(i + 1)) bindingsite.set('has_interactions', 'False') self.xmlreport.insert(i + 1, bindingsite) for itype in BindingSiteReport(s).generate_txt(): self.txtreport.append(itype) if not s.no_interactions: bindingsite.set('has_interactions', 'True') else: self.txtreport.append('No interactions detected.') sys.stdout = sys.__stdout__
[ "def", "get_bindingsite_data", "(", "self", ")", ":", "for", "i", ",", "site", "in", "enumerate", "(", "sorted", "(", "self", ".", "mol", ".", "interaction_sets", ")", ")", ":", "s", "=", "self", ".", "mol", ".", "interaction_sets", "[", "site", "]", ...
Get the additional data for the binding sites
[ "Get", "the", "additional", "data", "for", "the", "binding", "sites" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L89-L103
4,794
ssalentin/plip
plip/modules/report.py
StructureReport.write_xml
def write_xml(self, as_string=False): """Write the XML report""" if not as_string: et.ElementTree(self.xmlreport).write('{}/{}.xml'.format(self.outpath, self.outputprefix), pretty_print=True, xml_declaration=True) else: output = et.tostring(self.xmlreport, pretty_print=True) if config.RAWSTRING: output = repr(output) print(output)
python
def write_xml(self, as_string=False): if not as_string: et.ElementTree(self.xmlreport).write('{}/{}.xml'.format(self.outpath, self.outputprefix), pretty_print=True, xml_declaration=True) else: output = et.tostring(self.xmlreport, pretty_print=True) if config.RAWSTRING: output = repr(output) print(output)
[ "def", "write_xml", "(", "self", ",", "as_string", "=", "False", ")", ":", "if", "not", "as_string", ":", "et", ".", "ElementTree", "(", "self", ".", "xmlreport", ")", ".", "write", "(", "'{}/{}.xml'", ".", "format", "(", "self", ".", "outpath", ",", ...
Write the XML report
[ "Write", "the", "XML", "report" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L105-L113
4,795
ssalentin/plip
plip/modules/report.py
StructureReport.write_txt
def write_txt(self, as_string=False): """Write the TXT report""" if not as_string: with open('{}/{}.txt'.format(self.outpath, self.outputprefix), 'w') as f: [f.write(textline + '\n') for textline in self.txtreport] else: output = '\n'.join(self.txtreport) if config.RAWSTRING: output = repr(output) print(output)
python
def write_txt(self, as_string=False): if not as_string: with open('{}/{}.txt'.format(self.outpath, self.outputprefix), 'w') as f: [f.write(textline + '\n') for textline in self.txtreport] else: output = '\n'.join(self.txtreport) if config.RAWSTRING: output = repr(output) print(output)
[ "def", "write_txt", "(", "self", ",", "as_string", "=", "False", ")", ":", "if", "not", "as_string", ":", "with", "open", "(", "'{}/{}.txt'", ".", "format", "(", "self", ".", "outpath", ",", "self", ".", "outputprefix", ")", ",", "'w'", ")", "as", "f...
Write the TXT report
[ "Write", "the", "TXT", "report" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L115-L124
4,796
ssalentin/plip
plip/modules/report.py
BindingSiteReport.rst_table
def rst_table(self, array): """Given an array, the function formats and returns and table in rST format.""" # Determine cell width for each column cell_dict = {} for i, row in enumerate(array): for j, val in enumerate(row): if j not in cell_dict: cell_dict[j] = [] cell_dict[j].append(val) for item in cell_dict: cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1 # Contains adapted width for each column # Format top line num_cols = len(array[0]) form = '+' for col in range(num_cols): form += (cell_dict[col] + 1) * '-' form += '+' form += '\n' # Format values for i, row in enumerate(array): form += '| ' for j, val in enumerate(row): cell_width = cell_dict[j] form += str(val) + (cell_width - len(val)) * ' ' + '| ' form.rstrip() form += '\n' # Seperation lines form += '+' if i == 0: sign = '=' else: sign = '-' for col in range(num_cols): form += (cell_dict[col] + 1) * sign form += '+' form += '\n' return form
python
def rst_table(self, array): # Determine cell width for each column cell_dict = {} for i, row in enumerate(array): for j, val in enumerate(row): if j not in cell_dict: cell_dict[j] = [] cell_dict[j].append(val) for item in cell_dict: cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1 # Contains adapted width for each column # Format top line num_cols = len(array[0]) form = '+' for col in range(num_cols): form += (cell_dict[col] + 1) * '-' form += '+' form += '\n' # Format values for i, row in enumerate(array): form += '| ' for j, val in enumerate(row): cell_width = cell_dict[j] form += str(val) + (cell_width - len(val)) * ' ' + '| ' form.rstrip() form += '\n' # Seperation lines form += '+' if i == 0: sign = '=' else: sign = '-' for col in range(num_cols): form += (cell_dict[col] + 1) * sign form += '+' form += '\n' return form
[ "def", "rst_table", "(", "self", ",", "array", ")", ":", "# Determine cell width for each column", "cell_dict", "=", "{", "}", "for", "i", ",", "row", "in", "enumerate", "(", "array", ")", ":", "for", "j", ",", "val", "in", "enumerate", "(", "row", ")", ...
Given an array, the function formats and returns and table in rST format.
[ "Given", "an", "array", "the", "function", "formats", "and", "returns", "and", "table", "in", "rST", "format", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L283-L322
4,797
ssalentin/plip
plip/modules/report.py
BindingSiteReport.generate_txt
def generate_txt(self): """Generates an flat text report for a single binding site""" txt = [] titletext = '%s (%s) - %s' % (self.bsid, self.longname, self.ligtype) txt.append(titletext) for i, member in enumerate(self.lig_members[1:]): txt.append(' + %s' % ":".join(str(element) for element in member)) txt.append("-" * len(titletext)) txt.append("Interacting chain(s): %s\n" % ','.join([chain for chain in self.interacting_chains])) for section in [['Hydrophobic Interactions', self.hydrophobic_features, self.hydrophobic_info], ['Hydrogen Bonds', self.hbond_features, self.hbond_info], ['Water Bridges', self.waterbridge_features, self.waterbridge_info], ['Salt Bridges', self.saltbridge_features, self.saltbridge_info], ['pi-Stacking', self.pistacking_features, self.pistacking_info], ['pi-Cation Interactions', self.pication_features, self.pication_info], ['Halogen Bonds', self.halogen_features, self.halogen_info], ['Metal Complexes', self.metal_features, self.metal_info]]: iname, features, interaction_information = section # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2)) if not len(interaction_information) == 0: txt.append('\n**%s**' % iname) table = [features, ] for single_contact in interaction_information: values = [] for x in single_contact: if type(x) == str: values.append(x) elif type(x) == tuple and len(x) == 3: # Coordinates values.append("%.3f, %.3f, %.3f" % x) else: values.append(str(x)) table.append(values) txt.append(self.rst_table(table)) txt.append('\n') return txt
python
def generate_txt(self): txt = [] titletext = '%s (%s) - %s' % (self.bsid, self.longname, self.ligtype) txt.append(titletext) for i, member in enumerate(self.lig_members[1:]): txt.append(' + %s' % ":".join(str(element) for element in member)) txt.append("-" * len(titletext)) txt.append("Interacting chain(s): %s\n" % ','.join([chain for chain in self.interacting_chains])) for section in [['Hydrophobic Interactions', self.hydrophobic_features, self.hydrophobic_info], ['Hydrogen Bonds', self.hbond_features, self.hbond_info], ['Water Bridges', self.waterbridge_features, self.waterbridge_info], ['Salt Bridges', self.saltbridge_features, self.saltbridge_info], ['pi-Stacking', self.pistacking_features, self.pistacking_info], ['pi-Cation Interactions', self.pication_features, self.pication_info], ['Halogen Bonds', self.halogen_features, self.halogen_info], ['Metal Complexes', self.metal_features, self.metal_info]]: iname, features, interaction_information = section # Sort results first by res number, then by distance and finally ligand coordinates to get a unique order interaction_information = sorted(interaction_information, key=itemgetter(0, 2, -2)) if not len(interaction_information) == 0: txt.append('\n**%s**' % iname) table = [features, ] for single_contact in interaction_information: values = [] for x in single_contact: if type(x) == str: values.append(x) elif type(x) == tuple and len(x) == 3: # Coordinates values.append("%.3f, %.3f, %.3f" % x) else: values.append(str(x)) table.append(values) txt.append(self.rst_table(table)) txt.append('\n') return txt
[ "def", "generate_txt", "(", "self", ")", ":", "txt", "=", "[", "]", "titletext", "=", "'%s (%s) - %s'", "%", "(", "self", ".", "bsid", ",", "self", ".", "longname", ",", "self", ".", "ligtype", ")", "txt", ".", "append", "(", "titletext", ")", "for",...
Generates an flat text report for a single binding site
[ "Generates", "an", "flat", "text", "report", "for", "a", "single", "binding", "site" ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/report.py#L324-L361
4,798
ssalentin/plip
plip/modules/mp.py
pool_args
def pool_args(function, sequence, kwargs): """Return a single iterator of n elements of lists of length 3, given a sequence of len n.""" return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))
python
def pool_args(function, sequence, kwargs): return zip(itertools.repeat(function), sequence, itertools.repeat(kwargs))
[ "def", "pool_args", "(", "function", ",", "sequence", ",", "kwargs", ")", ":", "return", "zip", "(", "itertools", ".", "repeat", "(", "function", ")", ",", "sequence", ",", "itertools", ".", "repeat", "(", "kwargs", ")", ")" ]
Return a single iterator of n elements of lists of length 3, given a sequence of len n.
[ "Return", "a", "single", "iterator", "of", "n", "elements", "of", "lists", "of", "length", "3", "given", "a", "sequence", "of", "len", "n", "." ]
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/mp.py#L30-L32
4,799
ssalentin/plip
plip/modules/mp.py
parallel_fn
def parallel_fn(f): """Simple wrapper function, returning a parallel version of the given function f. The function f must have one argument and may have an arbitray number of keyword arguments. """ def simple_parallel(func, sequence, **args): """ f takes an element of sequence as input and the keyword args in **args""" if 'processes' in args: processes = args.get('processes') del args['processes'] else: processes = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes) # depends on available cores result = pool.map_async(universal_worker, pool_args(func, sequence, args)) pool.close() pool.join() cleaned = [x for x in result.get() if x is not None] # getting results cleaned = asarray(cleaned) return cleaned return partial(simple_parallel, f)
python
def parallel_fn(f): def simple_parallel(func, sequence, **args): """ f takes an element of sequence as input and the keyword args in **args""" if 'processes' in args: processes = args.get('processes') del args['processes'] else: processes = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes) # depends on available cores result = pool.map_async(universal_worker, pool_args(func, sequence, args)) pool.close() pool.join() cleaned = [x for x in result.get() if x is not None] # getting results cleaned = asarray(cleaned) return cleaned return partial(simple_parallel, f)
[ "def", "parallel_fn", "(", "f", ")", ":", "def", "simple_parallel", "(", "func", ",", "sequence", ",", "*", "*", "args", ")", ":", "\"\"\" f takes an element of sequence as input and the keyword args in **args\"\"\"", "if", "'processes'", "in", "args", ":", "processes...
Simple wrapper function, returning a parallel version of the given function f. The function f must have one argument and may have an arbitray number of keyword arguments.
[ "Simple", "wrapper", "function", "returning", "a", "parallel", "version", "of", "the", "given", "function", "f", ".", "The", "function", "f", "must", "have", "one", "argument", "and", "may", "have", "an", "arbitray", "number", "of", "keyword", "arguments", "...
906c8d36463689779b403f6c2c9ed06174acaf9a
https://github.com/ssalentin/plip/blob/906c8d36463689779b403f6c2c9ed06174acaf9a/plip/modules/mp.py#L35-L56