_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q4700 | ChimeraVisualizer.show_stacking | train | 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"))
| python | {
"resource": ""
} |
q4701 | ChimeraVisualizer.show_cationpi | train | 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"))
| python | {
"resource": ""
} |
q4702 | ChimeraVisualizer.show_sbridges | train | 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"))
| python | {
"resource": ""
} |
q4703 | ChimeraVisualizer.show_wbridges | train | 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)
| python | {
"resource": ""
} |
q4704 | ChimeraVisualizer.show_metal | train | 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')
| python | {
"resource": ""
} |
q4705 | ChimeraVisualizer.cleanup | train | 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))
| python | {
"resource": ""
} |
q4706 | ChimeraVisualizer.zoom_to_ligand | train | def zoom_to_ligand(self):
"""Centers the view on the ligand and its binding site residues."""
| python | {
"resource": ""
} |
q4707 | ChimeraVisualizer.refinements | train | def refinements(self):
"""Details for the visualization."""
self.rc("setattr a color gray @CENTROID")
self.rc("setattr a radius 0.3 @CENTROID")
| python | {
"resource": ""
} |
q4708 | Formatter.format | train | 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 | python | {
"resource": ""
} |
q4709 | Formatter.center_important_part | train | 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 | python | {
"resource": ""
} |
q4710 | Formatter.crop_to_ratio | train | 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, | python | {
"resource": ""
} |
q4711 | Formatter.get_resized_size | train | 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
| python | {
"resource": ""
} |
q4712 | Formatter.resize | train | def resize(self):
"""
Get target size for a cropped image and do the resizing if we got
anything usable.
"""
resized_size | python | {
"resource": ""
} |
q4713 | Formatter.rotate_exif | train | def rotate_exif(self):
"""
Rotate image via exif information.
Only 90, 180 and 270 rotations are supported.
"""
exif = self.image._getexif() or {}
| python | {
"resource": ""
} |
q4714 | get_content_type | train | 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:
| python | {
"resource": ""
} |
q4715 | get_templates_from_publishable | train | 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 = | python | {
"resource": ""
} |
q4716 | export | train | 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:
| python | {
"resource": ""
} |
q4717 | EllaCoreView.get_templates | train | 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
| python | {
"resource": ""
} |
q4718 | Format.get_blank_img | train | 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:
| python | {
"resource": ""
} |
q4719 | Format.get_placeholder_img | train | 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 = {
| python | {
"resource": ""
} |
q4720 | FormatedPhoto.generate | train | 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 = | python | {
"resource": ""
} |
q4721 | FormatedPhoto.save | train | def save(self, **kwargs):
"""Overrides models.Model.save
- Removes old file from the FS
- Generates new file.
"""
self.remove_file()
if not self.image:
| python | {
"resource": ""
} |
q4722 | FormatedPhoto.file | train | 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)
| python | {
"resource": ""
} |
q4723 | _get_category_from_pars_var | train | def _get_category_from_pars_var(template_var, context):
'''
get category from template variable or from tree_path
'''
cat = template_var.resolve(context)
if | python | {
"resource": ""
} |
q4724 | position | train | 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::
| python | {
"resource": ""
} |
q4725 | pistacking | train | 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)
| python | {
"resource": ""
} |
q4726 | halogen | train | 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 | python | {
"resource": ""
} |
q4727 | XMLStorage.getdata | train | 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
| python | {
"resource": ""
} |
q4728 | XMLStorage.getcoordinates | train | def getcoordinates(self, tree, location):
"""Gets coordinates from a specific element in PLIP XML"""
| python | {
"resource": ""
} |
q4729 | BSite.get_atom_mapping | train | 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(':')
| python | {
"resource": ""
} |
q4730 | BSite.get_counts | train | 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),
| python | {
"resource": ""
} |
q4731 | PLIPXMLREST.load_data | train | def load_data(self, pdbid):
"""Loads and parses an XML resource and saves it as a tree if successful"""
f | python | {
"resource": ""
} |
q4732 | check_pdb_status | train | 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 | python | {
"resource": ""
} |
q4733 | fetch_pdb | train | 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()
| python | {
"resource": ""
} |
q4734 | PositionBox | train | def PositionBox(position, *args, **kwargs):
" Delegate the boxing. "
obj = position.target
| python | {
"resource": ""
} |
q4735 | PositionManager.get_active_position | train | 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)) & \
| python | {
"resource": ""
} |
q4736 | Position.render | train | 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:
| python | {
"resource": ""
} |
q4737 | PyMOLVisualizer.set_initial_representations | train | def set_initial_representations(self):
"""General settings for PyMOL"""
self.standard_settings()
cmd.set('dash_gap', 0) # Show not dashes, but lines for the | python | {
"resource": ""
} |
q4738 | PyMOLVisualizer.standard_settings | train | 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
| python | {
"resource": ""
} |
q4739 | PyMOLVisualizer.set_custom_colorset | train | 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]')
| python | {
"resource": ""
} |
q4740 | PyMOLVisualizer.show_halogen | train | 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', | python | {
"resource": ""
} |
q4741 | PyMOLVisualizer.show_stacking | train | 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':
| python | {
"resource": ""
} |
q4742 | PyMOLVisualizer.show_cationpi | train | 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))
| python | {
"resource": ""
} |
q4743 | PyMOLVisualizer.show_sbridges | train | 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:
| python | {
"resource": ""
} |
q4744 | PyMOLVisualizer.show_wbridges | train | 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))
| python | {
"resource": ""
} |
q4745 | PyMOLVisualizer.show_metal | train | 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'):
| python | {
"resource": ""
} |
q4746 | PyMOLVisualizer.selections_cleanup | train | 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)
| python | {
"resource": ""
} |
q4747 | PyMOLVisualizer.selections_group | train | 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 | python | {
"resource": ""
} |
q4748 | PyMOLVisualizer.additional_cleanup | train | def additional_cleanup(self):
"""Cleanup of various representations"""
cmd.remove('not alt ""+A') # Remove alternate conformations
cmd.hide('labels', 'Interactions') # Hide labels of lines | python | {
"resource": ""
} |
q4749 | PyMOLVisualizer.zoom_to_ligand | train | 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' % | python | {
"resource": ""
} |
q4750 | PyMOLVisualizer.save_session | train | 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]))
| python | {
"resource": ""
} |
q4751 | PyMOLVisualizer.save_picture | train | def save_picture(self, outfolder, filename):
"""Saves a picture"""
| python | {
"resource": ""
} |
q4752 | PyMOLVisualizer.set_fancy_ray | train | 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)
| python | {
"resource": ""
} |
q4753 | PyMOLVisualizer.adapt_for_peptides | train | 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)
| python | {
"resource": ""
} |
q4754 | PyMOLVisualizer.refinements | train | 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"):
| python | {
"resource": ""
} |
q4755 | get_cached_object | train | 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
| python | {
"resource": ""
} |
q4756 | get_cached_objects | train | 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 | python | {
"resource": ""
} |
q4757 | get_cached_object_or_404 | train | 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
"""
| python | {
"resource": ""
} |
q4758 | tmpfile | train | def tmpfile(prefix, direc):
"""Returns the path to a newly | python | {
"resource": ""
} |
q4759 | extract_pdbid | train | 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:
| python | {
"resource": ""
} |
q4760 | whichrestype | train | def whichrestype(atom):
"""Returns the residue name of an Pybel or OpenBabel atom."""
atom = atom if | python | {
"resource": ""
} |
q4761 | whichchain | train | def whichchain(atom):
"""Returns the residue number of an PyBel or OpenBabel atom."""
atom = atom if | python | {
"resource": ""
} |
q4762 | euclidean3d | train | 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 | python | {
"resource": ""
} |
q4763 | create_folder_if_not_exists | train | def create_folder_if_not_exists(folder_path):
"""Creates a folder if it does not exists."""
folder_path = tilde_expansion(folder_path)
| python | {
"resource": ""
} |
q4764 | start_pymol | train | 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 | python | {
"resource": ""
} |
q4765 | ring_is_planar | train | 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 | python | {
"resource": ""
} |
q4766 | get_isomorphisms | train | 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, | python | {
"resource": ""
} |
q4767 | canonicalize | train | 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 = | python | {
"resource": ""
} |
q4768 | read_pdb | train | 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]
| python | {
"resource": ""
} |
q4769 | read | train | 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':
| python | {
"resource": ""
} |
q4770 | readmol | train | 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 | python | {
"resource": ""
} |
q4771 | colorlog | train | 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 + | python | {
"resource": ""
} |
q4772 | write_message | train | def write_message(msg, indent=False, mtype='standard', caption=False):
"""Writes message if verbose mode is set."""
| python | {
"resource": ""
} |
q4773 | message | train | 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 | python | {
"resource": ""
} |
q4774 | do_related | train | 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.
| python | {
"resource": ""
} |
q4775 | PublishableBox | train | 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 == | python | {
"resource": ""
} |
q4776 | ListingBox | train | def ListingBox(listing, *args, **kwargs):
" Delegate the boxing to the target's Box class. "
| python | {
"resource": ""
} |
q4777 | Publishable.get_absolute_url | train | 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)
| python | {
"resource": ""
} |
q4778 | Publishable.is_published | train | def is_published(self):
"Return True if the Publishable is currently active."
cur_time = | python | {
"resource": ""
} |
q4779 | Box.resolve_params | train | def resolve_params(self, text):
" Parse the parameters into a dict. "
params = MultiValueDict()
for line in | python | {
"resource": ""
} |
q4780 | Box.prepare | train | 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'] = | python | {
"resource": ""
} |
q4781 | Box.get_context | train | def get_context(self):
" Get context to render the template. "
return {
'content_type_name' : str(self.name),
| python | {
"resource": ""
} |
q4782 | Box._render | train | 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()
| python | {
"resource": ""
} |
q4783 | Box.get_cache_key | train | 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()))
| python | {
"resource": ""
} |
q4784 | Category.get_absolute_url | train | def get_absolute_url(self):
"""
Returns absolute URL for the category.
"""
if not self.tree_parent_id:
url = reverse('root_homepage')
| python | {
"resource": ""
} |
q4785 | listing | train | 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`` | python | {
"resource": ""
} |
q4786 | do_render | train | def do_render(parser, token):
"""
Renders a rich-text field using defined markup.
Example::
{% render some_var %}
"""
bits = token.split_contents() | python | {
"resource": ""
} |
q4787 | ipblur | train | 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)
| python | {
"resource": ""
} |
q4788 | register | train | 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):
| python | {
"resource": ""
} |
q4789 | related_by_category | train | 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 | python | {
"resource": ""
} |
q4790 | directly_related | train | 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=[
| python | {
"resource": ""
} |
q4791 | StructureReport.construct_xml_tree | train | 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')
| python | {
"resource": ""
} |
q4792 | StructureReport.construct_txt_file | train | 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 | python | {
"resource": ""
} |
q4793 | StructureReport.get_bindingsite_data | train | 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))
| python | {
"resource": ""
} |
q4794 | StructureReport.write_xml | train | 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:
| python | {
"resource": ""
} |
q4795 | StructureReport.write_txt | train | 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:
| python | {
"resource": ""
} |
q4796 | BindingSiteReport.rst_table | train | 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):
| python | {
"resource": ""
} |
q4797 | BindingSiteReport.generate_txt | train | 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
| python | {
"resource": ""
} |
q4798 | pool_args | train | def pool_args(function, sequence, kwargs):
"""Return a single iterator of n elements of | python | {
"resource": ""
} |
q4799 | parallel_fn | train | 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 | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.