_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 = sel... | 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
... | 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):
... | 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], sel... | 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_i... | 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("~disp... | python | {
"resource": ""
} |
q4706 | ChimeraVisualizer.zoom_to_ligand | train | 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 | {
"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")
self.rc("represent sphere @CENTROID")
self.rc("setattr a color orange @CHARGE")
self.rc("setattr a radius 0.4 @CHARGE")
... | 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 about rotation, use it and rotate resulting image.
"""
if hasattr(self.image, '_getexif'):
self.rotate_exif()... | 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.im... | 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 out... | 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 = ... | 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 = self.get_resized_size()
if not resized_size:
return
self.image = self.image.resize(resized_size, Image.ANTIALIAS) | 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 {}
rotation = exif.get(TAGS['Orientation'], 1)
rotations = {
6: -90,
3: -180,
8: -2... | 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 = publishable.category
app_label = publishable.content_type.app_label
model_label = publishable.conte... | 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 = []
... | 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:
return self.get_placeholder_img()
out = {
'blank': True,
'width': self.ma... | 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,
... | 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... | 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:
self.generate(save=False)
else:
self.image.name = self.file()
super(FormatedPho... | 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)
source_file = path.split(self.photo.image.name)
return pa... | 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 isinstance(cat, basestring):
cat = Category.objects.get_by_tree_path(cat)
return cat | 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 %}
{% p... | 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 iter... | 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')
pairin... | 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
... | python | {
"resource": ""
} |
q4728 | XMLStorage.getcoordinates | train | 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 | {
"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:
... | 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... | 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 = urlopen("http://projects.biotec.tu-dresden.de/plip-rest/pdb/%s?format=xml" % pdbid.lower())
self.doc = etree.parse(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('//r... | 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... | python | {
"resource": ""
} |
q4734 | PositionBox | train | def PositionBox(position, *args, **kwargs):
" Delegate the boxing. "
obj = position.target
return getattr(position.target, 'box_class', Box)(obj, *args, **kwargs) | 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
... | 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 ... | 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 pliprofiler
cmd.set('ray_shadow', 0) # Turn on ray shadows for clearer ray-traced images
cmd.set('cartoon_color', 'myligh... | 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 ... | 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]')
cmd.set_color('myblue', '[43, 131, 186]')
cmd... | 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.prot... | 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('... | 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.pseud... | 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))
... | 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 (i... | 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' % m... | 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... | 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 '
'Saltbridg... | 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
cmd.disable('%sCartoon' % self.protname)
cmd.hide('everything', 'hydrogens') | 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... | 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]))
if override is not None:
filename = override
cmd.save("/".join(... | python | {
"resource": ""
} |
q4751 | PyMOLVisualizer.save_picture | train | def save_picture(self, outfolder, filename):
"""Saves a picture"""
self.set_fancy_ray()
self.png_workaround("/".join([outfolder, filename])) | 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)
cmd.set('... | 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)
cmd.show('sticks', "byres *-L")
cmd.util.cnc(self.l... | 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 o... | 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 CAC... | 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 th... | 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
"""
try:
return get_cached_object(model, timeout=timeout, **kwargs)
except ObjectDoesNotExist,... | python | {
"resource": ""
} |
q4758 | tmpfile | train | def tmpfile(prefix, direc):
"""Returns the path to a newly created temporary file."""
return tempfile.mktemp(prefix=prefix, suffix='.pdb', dir=direc) | 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:
return m.group()
except AttributeError:
return "UnknownProtein" | python | {
"resource": ""
} |
q4760 | whichrestype | train | 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 | {
"resource": ""
} |
q4761 | whichchain | train | 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 | {
"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 None.")
return None
return np.sqrt((v1[0] - v2[0]) ** 2 + (v1[1] - v2[1]) ** 2 + (v1[2] - v2[2]) ** 2) | 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)
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... | 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 = ['pymol', '%s' % options] + sys.argv[1:]
if run:
initializ... | 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).co... | 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:
... | 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:
... | 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]
re... | 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':
zf = zipfile.ZipFile(fil, 'r')
return zf.open(zf.infolist()[0].filename)
else:
return open(f... | 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 carria... | 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.syst... | python | {
"resource": ""
} |
q4772 | write_message | train | 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 | {
"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: ' + ms... | 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**::
================================== ... | 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 == PublishableBox:
box_class = Box
return box_class(publishable, box_typ... | python | {
"resource": ""
} |
q4776 | ListingBox | train | 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 | {
"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_pat... | python | {
"resource": ""
} |
q4778 | Publishable.is_published | train | 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 | {
"resource": ""
} |
q4779 | Box.resolve_params | train | 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 | {
"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 va... | python | {
"resource": ""
} |
q4781 | Box.get_context | train | 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.ob... | 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()
t = loader.select_template(t_list)
context.update(self.get_... | 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')
else:
url = reverse('category_detail', kwargs={'category' : self.tree_path})
if self.site_id != settings.SITE_ID:
... | 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 <re... | 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()
if len(bits) != 2:
raise template.TemplateSyntaxError()
return RenderNode(bits[1]) | 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)
if not m:
return text
return '%sxxx' % m.group(1) | 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):
mod_list.append(modules)
elif ... | 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:
fro... | 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:
... | 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.strft... | 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.strftim... | 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:
output = et.tostring(self.xmlreport, pretty_print=Tr... | 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:
output = '\n'.join(self.txtreport)
... | 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:
... | 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... | python | {
"resource": ""
} |
q4798 | pool_args | train | 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 | {
"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 an... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.