_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q2100
TwitterStream.datagramReceived
train
def datagramReceived(self, data): """ Decode the JSON-encoded datagram and call the callback. """ try: obj = json.loads(data) except ValueError, e: log.err(e, 'Invalid JSON in stream: %r' % data) return
python
{ "resource": "" }
q2101
TwitterStream.connectionLost
train
def connectionLost(self, reason): """ Called when the body is complete or the connection was lost. @note: As the body length is usually not known at the beginning of the response we expect a L{PotentialDataLoss} when Twitter closes the stream, instead of L{ResponseDone}. Other exceptions are treated as error conditions.
python
{ "resource": "" }
q2102
simpleListFactory
train
def simpleListFactory(list_type): """Used for simple parsers that support only one type of object""" def create(delegate, extra_args=None): """Create a Parser object for the specific tag type,
python
{ "resource": "" }
q2103
BaseXMLHandler.setSubDelegates
train
def setSubDelegates(self, namelist, before=None, after=None): """Set a delegate for a sub-sub-item, according to a list of names""" if len(namelist) > 1: def set_sub(i): i.setSubDelegates(namelist[1:], before, after)
python
{ "resource": "" }
q2104
_split_path
train
def _split_path(path): """split a path return by the api return - the sentinel: - the rest of the path as a list. - the original path stripped of / for normalisation.
python
{ "resource": "" }
q2105
MixedContentsManager.path_dispatch_rename
train
def path_dispatch_rename(rename_like_method): """ decorator for rename-like function, that need dispatch on 2 arguments """ def _wrapper_method(self, old_path, new_path): old_path, _old_path, old_sentinel = _split_path(old_path); new_path, _new_path, new_sentinel = _split_path(new_path); if old_sentinel != new_sentinel: raise ValueError('Does not know how to move things across contents manager mountpoints') else: sentinel = new_sentinel
python
{ "resource": "" }
q2106
deactivate
train
def deactivate(profile='default'): """should be a matter of just unsetting the above keys """ with jconfig(profile) as config: deact = True; if not getattr(config.NotebookApp.contents_manager_class, 'startswith',lambda x:False)('jupyterdrive'):
python
{ "resource": "" }
q2107
sequence_type
train
def sequence_type(seq): '''Validates a coral.sequence data type. :param sequence_in: input DNA sequence. :type sequence_in: any :returns: The material - 'dna', 'rna', or 'peptide'. :rtype: str :raises: ValueError ''' if isinstance(seq, coral.DNA): material = 'dna' elif isinstance(seq, coral.RNA):
python
{ "resource": "" }
q2108
digest
train
def digest(dna, restriction_enzyme): '''Restriction endonuclease reaction. :param dna: DNA template to digest. :type dna: coral.DNA :param restriction_site: Restriction site to use. :type restriction_site: RestrictionSite :returns: list of digested DNA fragments. :rtype: coral.DNA list ''' pattern = restriction_enzyme.recognition_site located = dna.locate(pattern) if not located[0] and not located[1]: return [dna] # Bottom strand indices are relative to the bottom strand 5' end. # Convert to same type as top strand pattern_len = len(pattern) r_indices = [len(dna) - index - pattern_len for index in located[1]] # If sequence is palindrome, remove redundant results if pattern.is_palindrome(): r_indices = [index for index in r_indices if
python
{ "resource": "" }
q2109
_cut
train
def _cut(dna, index, restriction_enzyme): '''Cuts template once at the specified index. :param dna: DNA to cut :type dna: coral.DNA :param index: index at which to cut :type index: int :param restriction_enzyme: Enzyme with which to cut :type restriction_enzyme: coral.RestrictionSite :returns: 2-element list of digested sequence, including any overhangs. :rtype: list ''' # TODO: handle case where cut site is outside of recognition sequence, # for both circular and linear cases where site is at index 0 # Find absolute indices at which to cut cut_site = restriction_enzyme.cut_site top_cut = index + cut_site[0] bottom_cut = index + cut_site[1] # Isolate left and ride sequences to_cut = dna.pop() max_cut = max(top_cut, bottom_cut) min_cut = min(top_cut, bottom_cut) left = to_cut[:max_cut]
python
{ "resource": "" }
q2110
ipynb_to_rst
train
def ipynb_to_rst(directory, filename): """Converts a given file in a directory to an rst in the same directory.""" print(filename) os.chdir(directory) subprocess.Popen(["ipython", "nbconvert", "--to", "rst", filename],
python
{ "resource": "" }
q2111
convert_ipynbs
train
def convert_ipynbs(directory): """Recursively converts all ipynb files in a directory into rst files in the same directory.""" # The ipython_examples dir has to be in the same dir as this script for root, subfolders, files in os.walk(os.path.abspath(directory)):
python
{ "resource": "" }
q2112
_context_walk
train
def _context_walk(dna, window_size, context_len, step): '''Generate context-dependent 'non-boundedness' scores for a DNA sequence. :param dna: Sequence to score. :type dna: coral.DNA :param window_size: Window size in base pairs. :type window_size: int :param context_len: The number of bases of context to use when analyzing each window. :type context_len: int :param step: The number of base pairs to move for each new window. :type step: int ''' # Generate window indices window_start_ceiling = len(dna) - context_len - window_size window_starts = range(context_len - 1, window_start_ceiling, step) window_ends = [start + window_size for start in window_starts] # Generate left and right in-context subsequences l_starts = [step * i for i in range(len(window_starts))] l_seqs = [dna[start:end] for start, end in zip(l_starts, window_ends)] r_ends = [x + window_size + context_len for x in window_starts] r_seqs = [dna[start:end].reverse_complement() for start, end in
python
{ "resource": "" }
q2113
StructureWindows.plot
train
def plot(self): '''Plot the results of the run method.''' try: from matplotlib import pylab except ImportError: raise ImportError('Optional dependency matplotlib not installed.') if self.walked: fig = pylab.figure() ax1 = fig.add_subplot(111)
python
{ "resource": "" }
q2114
primer
train
def primer(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3, end_gc=False, tm_parameters='cloning', overhang=None, structure=False): '''Design primer to a nearest-neighbor Tm setpoint. :param dna: Sequence for which to design a primer. :type dna: coral.DNA :param tm: Ideal primer Tm in degrees C. :type tm: float :param min_len: Minimum primer length. :type min_len: int :param tm_undershoot: Allowed Tm undershoot. :type tm_undershoot: float :param tm_overshoot: Allowed Tm overshoot. :type tm_overshoot: float :param end_gc: Obey the 'end on G or C' rule. :type end_gc: bool :param tm_parameters: Melting temp calculator method to use. :type tm_parameters: string :param overhang: Append the primer to this overhang sequence. :type overhang: str :param structure: Evaluate primer for structure, with warning for high structure. :type structure: bool :returns: A primer. :rtype: coral.Primer :raises: ValueError if the input sequence is lower than the Tm settings allow. ValueError if a primer ending with G or C can't be found given the Tm settings. ''' # Check Tm of input sequence to see if it's already too low seq_tm = coral.analysis.tm(dna, parameters=tm_parameters) if seq_tm < (tm - tm_undershoot): msg = 'Input sequence Tm is lower than primer Tm setting' raise ValueError(msg) # Focus on first 90 bases - shouldn't need more than 90bp to anneal dna = dna[0:90] # Generate primers from min_len to 'tm' + tm_overshoot # TODO: this is a good place for optimization. Only calculate as many # primers as are needed. Use binary search. primers_tms = [] last_tm = 0 bases = min_len while last_tm <= tm + tm_overshoot and bases != len(dna): next_primer = dna[0:bases] last_tm = coral.analysis.tm(next_primer, parameters=tm_parameters) primers_tms.append((next_primer, last_tm)) bases += 1 # Trim primer list based on tm_undershoot and end_gc primers_tms = [(primer, melt) for primer, melt in primers_tms if melt >= tm - tm_undershoot] if end_gc: primers_tms = [pair for pair in primers_tms if pair[0][-1] == coral.DNA('C') or pair[0][-1] == coral.DNA('G')] if not
python
{ "resource": "" }
q2115
primers
train
def primers(dna, tm=65, min_len=10, tm_undershoot=1, tm_overshoot=3, end_gc=False, tm_parameters='cloning', overhangs=None, structure=False): '''Design primers for PCR amplifying any arbitrary sequence. :param dna: Input sequence. :type dna: coral.DNA :param tm: Ideal primer Tm in degrees C. :type tm: float :param min_len: Minimum primer length. :type min_len: int :param tm_undershoot: Allowed Tm undershoot. :type tm_undershoot: float :param tm_overshoot: Allowed Tm overshoot. :type tm_overshoot: float :param end_gc: Obey the 'end on G or C' rule. :type end_gc: bool :param tm_parameters:
python
{ "resource": "" }
q2116
Sanger.nonmatches
train
def nonmatches(self): '''Report mismatches, indels, and coverage.''' # For every result, keep a dictionary of mismatches, insertions, and
python
{ "resource": "" }
q2117
Sanger.plot
train
def plot(self): '''Make a summary plot of the alignment and highlight nonmatches.''' import matplotlib.pyplot as plt import matplotlib.patches as patches # Constants to use throughout drawing n = len(self.results) nbases = len(self.aligned_reference) barheight = 0.4 # Vary height of figure based on number of results figheight = 3 + 3 * (n - 1) fig = plt.figure(figsize=(9, figheight)) ax1 = fig.add_subplot(111) # Plot bars to represent coverage area # Reference sequence ax1.add_patch(patches.Rectangle((0, 0), nbases, barheight, facecolor='black')) # Results for i, report in enumerate(self.nonmatches()): j = i + 1 start, stop = report['coverage'] patch = patches.Rectangle((start, j), stop - start, barheight, facecolor='darkgray') ax1.add_patch(patch) # Draw a vertical line for each type of result plt.vlines(report['mismatches'], j, j + barheight, colors='b') plt.vlines(report['insertions'], j, j + barheight,
python
{ "resource": "" }
q2118
Sanger._remove_n
train
def _remove_n(self): '''Remove terminal Ns from sequencing results.''' for i, result in enumerate(self.results): largest = max(str(result).split('N'),
python
{ "resource": "" }
q2119
random_dna
train
def random_dna(n): '''Generate a random DNA sequence. :param n: Output sequence length. :type n: int :returns: Random DNA sequence of length n. :rtype:
python
{ "resource": "" }
q2120
random_codons
train
def random_codons(peptide, frequency_cutoff=0.0, weighted=False, table=None): '''Generate randomized codons given a peptide sequence. :param peptide: Peptide sequence for which to generate randomized codons. :type peptide: coral.Peptide :param frequency_cutoff: Relative codon usage cutoff - codons that are rarer will not be used. Frequency is relative to average over all codons for a given amino acid. :param frequency_cutoff: Codon frequency table to use. :param weighted: Use codon table :type weighted: bool :param table: Codon frequency table to use. Table should be organized by amino acid, then be a dict of codon: frequency. Only relevant if weighted=True or frequency_cutoff > 0. Tables available: constants.molecular_bio.CODON_FREQ_BY_AA['sc'] (default) :type table: dict :returns: Randomized sequence of codons (DNA) that code for the input peptide. :rtype: coral.DNA :raises: ValueError if frequency_cutoff is set so high that there are no codons available for an amino acid in the input peptide. ''' if table is None: table = CODON_FREQ_BY_AA['sc'] # Process codon table using frequency_cutoff new_table = _cutoff(table, frequency_cutoff)
python
{ "resource": "" }
q2121
_cutoff
train
def _cutoff(table, frequency_cutoff): '''Generate new codon frequency table given a mean cutoff. :param table: codon frequency table of form {amino acid: codon: frequency} :type table: dict :param frequency_cutoff: value between 0 and 1.0 for mean frequency cutoff :type frequency_cutoff: float :returns: A codon frequency table with some codons removed. :rtype: dict ''' new_table = {} # IDEA: cutoff should be relative to
python
{ "resource": "" }
q2122
fetch_genome
train
def fetch_genome(genome_id): '''Acquire a genome from Entrez ''' # TODO: Can strandedness by found in fetched genome attributes? # TODO: skip read/write step? # Using a dummy email for now - does this violate NCBI guidelines? email = '[email protected]' Entrez.email = email print 'Downloading Genome...' handle = Entrez.efetch(db='nucleotide', id=str(genome_id), rettype='gb',
python
{ "resource": "" }
q2123
ViennaRNA.fold
train
def fold(self, strand, temp=37.0, dangles=2, nolp=False, nogu=False, noclosinggu=False, constraints=None, canonicalbponly=False, partition=False, pfscale=None, imfeelinglucky=False, gquad=False): '''Run the RNAfold command and retrieve the result in a dictionary. :param strand: The DNA or RNA sequence on which to run RNAfold. :type strand: coral.DNA or coral.RNA :param temp: Temperature at which to run the calculations. :type temp: float :param dangles: How to treat dangling end energies. Set to 0 to ignore dangling ends. Set to 1 to limit unpaired bases to at most one dangling end (default for MFE calc). Set to 2 (the default) to remove the limit in 1. Set to 3 to allow coaxial stacking of adjacent helices in .multi-loops :type dangles: int :param nolp: Produce structures without lonely pairs (isolated single base pairs). :type nolp: bool :param nogu: Do not allow GU pairs. :type nogu: bool :param noclosinggu: Do not allow GU pairs at the end of helices. :type noclosinggu: bool :param constraints: Any structural constraints to use. Format is defined at http://www.tbi.univie.ac.at/RNA/RNAfold.1.html :type constraints: str :param canonicalbponly: Remove non-canonical base pairs from the structure constraint (if applicable). :type canonicalbponly: bool :param partition: Generates the partition function, generating a coarse grain structure ('coarse') in the format described at http://www.itc.univie.ac.at/~ivo/RNA/RNAlib/PF-Fold.h tml, the ensemble free energy ('ensemble'), the centroid structure ('centroid'), the free energy of
python
{ "resource": "" }
q2124
dimers
train
def dimers(primer1, primer2, concentrations=[5e-7, 3e-11]): '''Calculate expected fraction of primer dimers. :param primer1: Forward primer. :type primer1: coral.DNA :param primer2: Reverse primer. :type primer2: coral.DNA :param template: DNA template. :type template: coral.DNA :param concentrations: list of concentrations for primers and the template. Defaults are those for PCR with 1kb template. :type concentrations: list :returns: Fraction of dimers versus the total amount of primer added. :rtype: float ''' # It is not reasonable (yet) to use a long template for doing
python
{ "resource": "" }
q2125
read_dna
train
def read_dna(path): '''Read DNA from file. Uses BioPython and coerces to coral format. :param path: Full path to input file. :type path: str :returns: DNA sequence. :rtype: coral.DNA ''' filename, ext = os.path.splitext(os.path.split(path)[-1]) genbank_exts = ['.gb', '.ape'] fasta_exts = ['.fasta', '.fa', '.fsa', '.seq'] abi_exts = ['.abi', '.ab1'] if any([ext == extension for extension in genbank_exts]): file_format = 'genbank' elif any([ext == extension for extension in fasta_exts]): file_format = 'fasta' elif any([ext == extension for
python
{ "resource": "" }
q2126
_seqfeature_to_coral
train
def _seqfeature_to_coral(feature): '''Convert a Biopython SeqFeature to a coral.Feature. :param feature: Biopython SeqFeature :type feature: Bio.SeqFeature ''' # Some genomic sequences don't have a label attribute # TODO: handle genomic cases differently than others. Some features lack # a label but should still be incorporated somehow. qualifiers = feature.qualifiers if 'label' in qualifiers: feature_name = qualifiers['label'][0] elif 'locus_tag' in qualifiers: feature_name = qualifiers['locus_tag'][0] else: raise FeatureNameError('Unrecognized feature name') # Features with gaps are special, require looking at subfeatures # Assumption: subfeatures are never more than one level deep if feature.location_operator == 'join': # Feature has gaps. Have to figure out start/stop from subfeatures, # calculate gap indices. A nested feature model may be required # eventually. # Reorder the sub_feature list by start location # Assumption: none of the subfeatures overlap so the last entry in # the reordered list also has the final stop point of the feature. # FIXME: Getting a deprecation warning about using sub_features # instead of feature.location being a CompoundFeatureLocation reordered = sorted(feature.location.parts, key=lambda location: location.start) starts = [int(location.start) for location in reordered] stops = [int(location.end) for location in reordered] feature_start = starts.pop(0)
python
{ "resource": "" }
q2127
_coral_to_seqfeature
train
def _coral_to_seqfeature(feature): '''Convert a coral.Feature to a Biopython SeqFeature. :param feature: coral Feature. :type feature: coral.Feature ''' bio_strand = 1 if feature.strand == 1 else -1 ftype = _process_feature_type(feature.feature_type, bio_to_coral=False) sublocations = [] if feature.gaps: # There are gaps. Have to define location_operator and add subfeatures location_operator = 'join' # Feature location means nothing for 'join' sequences? # TODO: verify location = FeatureLocation(ExactPosition(0), ExactPosition(1), strand=bio_strand) # Reconstruct start/stop indices for each subfeature stops, starts = zip(*feature.gaps) starts = [feature.start] + [start + feature.start for start in starts] stops = [stop + feature.start for stop in stops] + [feature.stop] # Build subfeatures for start, stop in zip(starts, stops): sublocation = FeatureLocation(ExactPosition(start), ExactPosition(stop),
python
{ "resource": "" }
q2128
score_alignment
train
def score_alignment(a, b, gap_open, gap_extend, matrix): '''Calculate the alignment score from two aligned sequences. :param a: The first aligned sequence. :type a: str :param b: The second aligned sequence. :type b: str :param gap_open: The cost of opening a gap (negative number). :type gap_open: int :param gap_extend: The cost of extending an open gap (negative number). :type gap_extend: int. :param matrix: A score matrix dictionary name. Examples can be found in the substitution_matrices module. ''' al = a bl = b l = len(al)
python
{ "resource": "" }
q2129
build_docs
train
def build_docs(directory): """Builds sphinx docs from a given directory.""" os.chdir(directory)
python
{ "resource": "" }
q2130
gibson
train
def gibson(seq_list, circular=True, overlaps='mixed', overlap_tm=65, maxlen=80, terminal_primers=True, primer_kwargs=None): '''Design Gibson primers given a set of sequences :param seq_list: List of DNA sequences to stitch together :type seq_list: list containing coral.DNA :param circular: If true, designs primers for making a circular construct. If false, designs primers for a linear construct. :type circular: bool :param splits: Specifies locations of overlap. Must be either a single entry of the same type as the 'split' parameter in gibson_primers or a list of those types of the appropriate length (for circular construct, len(seq_list), for linear construct, len(seq_list) - 1) :type splits: str or list of str :param overlap_tm: Minimum Tm of overlap :type overlap_tm: float :param maxlen: Maximum length of each primer. :type maxlen: int :param terminal_primers: If the output is not circular, will design non-Gibson primers for amplifying the first and last fragments sans homology. If False, there will be one less set of primers returned. :type terminal_primers: bool :param primer_kwargs: keyword arguments to pass to design.primer :type primer_kwargs: dict :returns: Forward and reverse primers for amplifying every fragment. :rtype: a list of sequence.Primer tuples :raises: ValueError if split parameter is an invalid string or wrong size. ''' # Input checking if circular: n_overlaps = len(seq_list) else: n_overlaps = len(seq_list) - 1 if type(overlaps) is str: overlaps = [overlaps] * n_overlaps else: if len(overlaps) != n_overlaps: raise ValueError('Incorrect number of \'overlaps\' entries.') else: for overlap in overlaps: if overlap not in ['left', 'right', 'mixed']: raise ValueError('Invalid \'overlaps\' setting.') if primer_kwargs is None: primer_kwargs = {} # If here, inputs were good # Design primers for linear constructs: primers_list = [] for i, (left, right) in enumerate(zip(seq_list[:-1], seq_list[1:])): primers_list.append(gibson_primers(left, right, overlaps[i],
python
{ "resource": "" }
q2131
reverse_complement
train
def reverse_complement(sequence, material): '''Reverse complement a sequence. :param sequence: Sequence to reverse complement :type sequence: str :param material: dna, rna, or peptide. :type material: str
python
{ "resource": "" }
q2132
check_alphabet
train
def check_alphabet(seq, material): '''Verify that a given string is valid DNA, RNA, or peptide characters. :param seq: DNA, RNA, or peptide sequence. :type seq: str :param material: Input material - 'dna', 'rna', or 'pepide'. :type sequence: str :returns: Whether the `seq` is a valid string of `material`. :rtype: bool :raises: ValueError if `material` isn't \'dna\', \'rna\', or \'peptide\'. ValueError if `seq` contains invalid characters for its material type. ''' errs = {'dna': 'DNA', 'rna': 'RNA', 'peptide': 'peptide'} if material == 'dna' or material == 'rna' or material == 'peptide': alphabet = ALPHABETS[material] err_msg
python
{ "resource": "" }
q2133
process_seq
train
def process_seq(seq, material): '''Validate and process sequence inputs. :param seq: input sequence :type seq: str :param material: DNA, RNA, or peptide :type: str :returns: Uppercase version of `seq` with the alphabet checked by
python
{ "resource": "" }
q2134
palindrome
train
def palindrome(seq): '''Test whether a sequence is palindrome. :param seq: Sequence to analyze (DNA or RNA). :type seq: coral.DNA or coral.RNA :returns: Whether a sequence is a palindrome. :rtype: bool ''' seq_len = len(seq) if seq_len % 2 ==
python
{ "resource": "" }
q2135
Feature.copy
train
def copy(self): '''Return a copy of the Feature. :returns: A safely editable copy of the current feature. :rtype: coral.Feature ''' return type(self)(self.name, self.start, self.stop, self.feature_type,
python
{ "resource": "" }
q2136
nupack_multi
train
def nupack_multi(seqs, material, cmd, arguments, report=True): '''Split Nupack commands over processors. :param inputs: List of sequences, same format as for coral.analysis.Nupack. :type inpus: list :param material: Input material: 'dna' or 'rna'. :type material: str :param cmd: Command: 'mfe', 'pairs', 'complexes', or 'concentrations'. :type cmd: str :param arguments: Arguments for the command. :type arguments: str :returns: A list of the same return value you would get from `cmd`. :rtype: list ''' nupack_pool = multiprocessing.Pool() try: args = [{'seq': seq, 'cmd': cmd, 'material': material, 'arguments': arguments} for seq in seqs] nupack_iterator = nupack_pool.imap(run_nupack, args) total = len(seqs) msg = ' calculations complete.' passed = 4 while report: completed =
python
{ "resource": "" }
q2137
run_nupack
train
def run_nupack(kwargs): '''Run picklable Nupack command. :param kwargs: keyword arguments to pass to Nupack as well as 'cmd'. :returns: Variable - whatever `cmd` returns. '''
python
{ "resource": "" }
q2138
NUPACK.pfunc_multi
train
def pfunc_multi(self, strands, permutation=None, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the partition function for an ordered complex of strands. Runs the \'pfunc\' command. :param strands: List of strands to use as inputs to pfunc -multi. :type strands: list :param permutation: The circular permutation of strands to test in complex. e.g. to test in the order that was input for 4 strands, the permutation would be [1,2,3,4]. If set to None, defaults to the order of the input strands. :type permutation: list :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and 'rna1999' for the RNA 1999 parameters. :type material: str :param dangles: How to treat dangles in the computation. From the user guide: For \'none\': Dangle energies are ignored. For \'some\': \'A dangle energy is incorporated for each unpaired base flanking a duplex\'. For 'all': all dangle energy is considered. :type dangles: str :param sodium: Sodium concentration in solution (molar), only applies to DNA.
python
{ "resource": "" }
q2139
NUPACK.subopt
train
def subopt(self, strand, gap, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the suboptimal structures within a defined energy gap of the MFE. Runs the \'subopt\' command. :param strand: Strand on which to run subopt. Strands must be either coral.DNA or coral.RNA). :type strand: coral.DNA or coral.RNA :param gap: Energy gap within to restrict results, e.g. 0.1. :type gap: float :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and 'rna1999' for the RNA 1999 parameters. :type material: str :param dangles: How to treat dangles in the computation. From the user guide: For \'none\': Dangle energies are ignored. For \'some\': \'A dangle energy is incorporated for each unpaired base flanking a duplex\'. For 'all': all dangle energy is considered. :type dangles: str :param sodium: Sodium concentration in solution (molar), only applies to DNA. :type sodium: float :param magnesium: Magnesium concentration in solution (molar), only
python
{ "resource": "" }
q2140
NUPACK.energy
train
def energy(self, strand, dotparens, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Calculate the free energy of a given sequence structure. Runs the \'energy\' command. :param strand: Strand on which to run energy. Strands must be either coral.DNA or coral.RNA). :type strand: coral.DNA or coral.RNA :param dotparens: The structure in dotparens notation. :type dotparens: str :param temp: Temperature setting for the computation. Negative values are not allowed. :type temp: float :param pseudo: Enable pseudoknots. :type pseudo: bool :param material: The material setting to use in the computation. If set to None (the default), the material type is inferred from the strands. Other settings available: 'dna' for DNA parameters, 'rna' for RNA (1995) parameters, and
python
{ "resource": "" }
q2141
NUPACK.complexes_timeonly
train
def complexes_timeonly(self, strands, max_size): '''Estimate the amount of time it will take to calculate all the partition functions for each circular permutation - estimate the time the actual \'complexes\' command will take to run. :param strands: Strands on which to run energy. Strands must be either coral.DNA or coral.RNA). :type strands: list of coral.DNA or coral.RNA :param max_size: Maximum complex size to consider (maximum number of strand species in complex). :type max_size: int
python
{ "resource": "" }
q2142
NUPACK._multi_lines
train
def _multi_lines(self, strands, permutation): '''Prepares lines to write to file for pfunc command input. :param strand: Strand input (cr.DNA or cr.RNA). :type strand: cr.DNA or cr.DNA :param permutation: Permutation (e.g. [1, 2, 3, 4]) of the type used by pfunc_multi. :type permutation: list ''' lines = [] # Write
python
{ "resource": "" }
q2143
NUPACK._read_tempfile
train
def _read_tempfile(self, filename): '''Read in and return file that's in the tempdir. :param filename: Name of
python
{ "resource": "" }
q2144
NUPACK._pairs_to_np
train
def _pairs_to_np(self, pairlist, dim): '''Given a set of pair probability lines, construct a numpy array. :param pairlist: a list of pair probability triples :type pairlist: list :returns: An upper triangular matrix of pair probabilities augmented with one extra column that represents the unpaired probabilities. :rtype: numpy.array '''
python
{ "resource": "" }
q2145
_flip_feature
train
def _flip_feature(self, feature, parent_len): '''Adjust a feature's location when flipping DNA. :param feature: The feature to flip. :type feature: coral.Feature :param parent_len: The length of the sequence to which the feature belongs. :type parent_len: int
python
{ "resource": "" }
q2146
DNA.ape
train
def ape(self, ape_path=None): '''Open in ApE if `ApE` is in your command line path.''' # TODO: simplify - make ApE look in PATH only cmd = 'ApE' if ape_path is None: # Check for ApE in PATH ape_executables = [] for path in os.environ['PATH'].split(os.pathsep): exepath = os.path.join(path, cmd) ape_executables.append(os.access(exepath, os.X_OK)) if not any(ape_executables): raise Exception('Ape not in PATH. Use ape_path kwarg.') else: cmd = ape_path # Check whether ApE exists in PATH
python
{ "resource": "" }
q2147
DNA.circularize
train
def circularize(self): '''Circularize linear DNA. :returns: A circularized version of the current sequence. :rtype: coral.DNA ''' if self.top[-1].seq == '-' and self.bottom[0].seq == '-': raise ValueError('Cannot circularize - termini disconnected.') if self.bottom[-1].seq == '-' and self.top[0].seq == '-':
python
{ "resource": "" }
q2148
DNA.flip
train
def flip(self): '''Flip the DNA - swap the top and bottom strands. :returns: Flipped DNA (bottom strand is now top strand, etc.). :rtype: coral.DNA ''' copy = self.copy()
python
{ "resource": "" }
q2149
DNA.linearize
train
def linearize(self, index=0): '''Linearize circular DNA at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.DNA :raises: ValueError if the input
python
{ "resource": "" }
q2150
DNA.locate
train
def locate(self, pattern): '''Find sequences matching a pattern. For a circular sequence, the search extends over the origin. :param pattern: str or NucleicAcidSequence for which to find matches. :type pattern: str or coral.DNA :returns: A list of top and bottom strand indices
python
{ "resource": "" }
q2151
DNA.reverse_complement
train
def reverse_complement(self): '''Reverse complement the DNA. :returns: A reverse-complemented instance of the current sequence. :rtype: coral.DNA ''' copy = self.copy() # Note: if sequence is double-stranded,
python
{ "resource": "" }
q2152
DNA.to_feature
train
def to_feature(self, name=None, feature_type='misc_feature'): '''Create a feature from the current object. :param name: Name for the new feature. Must be specified if the DNA instance has no .name attribute. :type name: str :param feature_type: The type of feature (genbank standard). :type feature_type: str ''' if name is None: if not self.name: raise ValueError('name
python
{ "resource": "" }
q2153
RestrictionSite.cuts_outside
train
def cuts_outside(self): '''Report whether the enzyme cuts outside its recognition site. Cutting at the very end of the site returns True. :returns: Whether the enzyme will cut outside its recognition site. :rtype: bool '''
python
{ "resource": "" }
q2154
Primer.copy
train
def copy(self): '''Generate a Primer copy. :returns: A safely-editable copy of the current primer. :rtype: coral.DNA
python
{ "resource": "" }
q2155
_pair_deltas
train
def _pair_deltas(seq, pars): '''Add up nearest-neighbor parameters for a given sequence. :param seq: DNA sequence for which to sum nearest neighbors :type seq: str :param pars: parameter set to use :type pars: dict :returns: nearest-neighbor delta_H and delta_S sums. :rtype: tuple of floats ''' delta0
python
{ "resource": "" }
q2156
breslauer_corrections
train
def breslauer_corrections(seq, pars_error): '''Sum corrections for Breslauer '84 method. :param seq: sequence for which to calculate corrections. :type seq: str :param pars_error: dictionary of error corrections :type pars_error: dict :returns: Corrected delta_H and delta_S parameters :rtype: list of floats ''' deltas_corr = [0, 0] contains_gc = 'G' in str(seq) or 'C' in str(seq)
python
{ "resource": "" }
q2157
MAFFT
train
def MAFFT(sequences, gap_open=1.53, gap_extension=0.0, retree=2): '''A Coral wrapper for the MAFFT command line multiple sequence aligner. :param sequences: A list of sequences to align. :type sequences: List of homogeneous sequences (all DNA, or all RNA, etc.) :param gap_open: --op (gap open) penalty in MAFFT cli. :type gap_open: float :param gap_extension: --ep (gap extension) penalty in MAFFT cli. :type gap_extension: float :param retree: Number of times to build the guide tree. :type retree: int ''' arguments = ['mafft'] arguments += ['--op', str(gap_open)] arguments += ['--ep', str(gap_extension)] arguments += ['--retree', str(retree)] arguments.append('input.fasta') tempdir = tempfile.mkdtemp() try: with open(os.path.join(tempdir, 'input.fasta'), 'w') as f: for i, sequence in enumerate(sequences): if hasattr(sequence, 'name'): name = sequence.name else: name = 'sequence{}'.format(i)
python
{ "resource": "" }
q2158
repeats
train
def repeats(seq, size): '''Count times that a sequence of a certain size is repeated. :param seq: Input sequence. :type seq: coral.DNA or coral.RNA :param size: Size of the repeat to count. :type size: int :returns: Occurrences of repeats and how many :rtype: tuple of the matched sequence and how many times it occurs ''' seq = str(seq) n_mers =
python
{ "resource": "" }
q2159
gibson
train
def gibson(seq_list, linear=False, homology=10, tm=63.0): '''Simulate a Gibson reaction. :param seq_list: list of DNA sequences to Gibson :type seq_list: list of coral.DNA :param linear: Attempt to produce linear, rather than circular, fragment from input fragments. :type linear: bool :param homology_min: minimum bp of homology allowed :type homology_min: int :param tm: Minimum tm of overlaps :type tm: float :returns: coral.reaction.Gibson instance. :raises: ValueError if any input sequences are circular DNA. ''' # FIXME: Preserve features in overlap # TODO: set a max length? # TODO: add 'expected' keyword argument somewhere to automate # validation # Remove any redundant (identical) sequences seq_list = list(set(seq_list)) for seq in seq_list:
python
{ "resource": "" }
q2160
_fuse_last
train
def _fuse_last(working_list, homology, tm): '''With one sequence left, attempt to fuse it to itself. :param homology: length of terminal homology in bp. :type homology: int :raises: AmbiguousGibsonError if either of the termini are palindromic (would bind self-self). ValueError if the ends are not compatible. ''' # 1. Construct graph on self-self # (destination, size, strand1, strand2) pattern = working_list[0] def graph_strands(strand1, strand2): matchlen = homology_report(pattern, pattern, strand1, strand2, cutoff=homology, min_tm=tm, top_two=True) if matchlen: # Ignore full-sequence matches # HACK: modified homology_report to accept top_two. It should # really just ignore full-length matches for length in matchlen: if length != len(pattern):
python
{ "resource": "" }
q2161
get_gene_id
train
def get_gene_id(gene_name): '''Retrieve systematic yeast gene name from the common name. :param gene_name: Common name for yeast gene (e.g. ADE2). :type gene_name: str :returns: Systematic name for yeast gene (e.g. YOR128C). :rtype: str ''' from intermine.webservice import Service service = Service('http://yeastmine.yeastgenome.org/yeastmine/service') # Get a new query on the class (table) you will be querying: query = service.new_query('Gene') # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'crossReferences.identifier', 'crossReferences.source.name') # Uncomment and edit the line below (the default) to select a custom sort
python
{ "resource": "" }
q2162
_grow_overlaps
train
def _grow_overlaps(dna, melting_temp, require_even, length_max, overlap_min, min_exception): '''Grows equidistant overlaps until they meet specified constraints. :param dna: Input sequence. :type dna: coral.DNA :param melting_temp: Ideal Tm of the overlaps, in degrees C. :type melting_temp: float :param require_even: Require that the number of oligonucleotides is even. :type require_even: bool :param length_max: Maximum oligo size (e.g. 60bp price point cutoff) range. :type length_range: int :param overlap_min: Minimum overlap size. :type overlap_min: int :param min_exception: In order to meet melting_temp and overlap_min settings, allow overlaps less than overlap_min to continue growing above melting_temp. :type min_exception: bool :returns: Oligos, their overlapping regions, overlap Tms, and overlap indices. :rtype: tuple ''' # TODO: prevent growing overlaps from bumping into each other - # should halt when it happens, give warning, let user decide if they still # want the current construct # Another option would be to start over, moving the starting positions # near the problem region a little farther from each other - this would # put the AT-rich region in the middle of the spanning oligo # Try bare minimum number of oligos oligo_n = len(dna) // length_max + 1 # Adjust number of oligos if even number required if require_even: oligo_increment = 2 if oligo_n % 2 == 1: oligo_n += 1 else: oligo_increment = 1 # Increase oligo number until the minimum oligo_len is less than length_max while float(len(dna)) / oligo_n > length_max: oligo_n += oligo_increment # Loop until all overlaps meet minimum Tm and length tm_met = False len_met = False while(not tm_met or not len_met): # Calculate initial number of overlaps overlap_n = oligo_n - 1 # Place overlaps approximately equidistant over sequence length overlap_interval = float(len(dna)) / oligo_n starts = [int(overlap_interval * (i + 1)) for i in range(overlap_n)] ends = [index + 1 for index in starts] # Fencepost for while loop # Initial overlaps (1 base) and their tms overlaps = [dna[start:end] for start, end in zip(starts, ends)] overlap_tms =
python
{ "resource": "" }
q2163
_recalculate_overlaps
train
def _recalculate_overlaps(dna, overlaps, oligo_indices): '''Recalculate overlap sequences based on the current overlap indices. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param overlaps: Current overlaps - a list of DNA sequences. :type overlaps: coral.DNA list :param oligo_indices: List of oligo indices (starts and stops). :type oligo_indices: list :returns: Overlap sequences. :rtype: coral.DNA
python
{ "resource": "" }
q2164
_expand_overlap
train
def _expand_overlap(dna, oligo_indices, index, oligos, length_max): '''Given an overlap to increase, increases smaller oligo. :param dna: Sequence being split into oligos. :type dna: coral.DNA :param oligo_indices: index of oligo starts and stops :type oligo_indices: list :param index: index of the oligo :type index: int :param left_len: length of left oligo :type left_len: int :param right_len: length of right oligo :type right_len: int :param length_max: length ceiling :type length_max: int :returns: New oligo list with one expanded. :rtype: list ''' left_len = len(oligos[index]) right_len = len(oligos[index + 1]) # If one of the oligos is max size, increase the other one if right_len == length_max: oligo_indices[1] = _adjust_overlap(oligo_indices[1],
python
{ "resource": "" }
q2165
_adjust_overlap
train
def _adjust_overlap(positions_list, index, direction): '''Increase overlap to the right or left of an index. :param positions_list: list of overlap positions :type positions_list: list :param index: index of the overlap to increase. :type index: int :param direction: which side of the overlap to increase - left or right. :type direction: str :returns: A list of overlap positions (2-element lists) :rtype: list
python
{ "resource": "" }
q2166
OligoAssembly.design_assembly
train
def design_assembly(self): '''Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict ''' # Input parameters needed to design the oligos length_range = self.kwargs['length_range'] oligo_number = self.kwargs['oligo_number'] require_even = self.kwargs['require_even'] melting_temp = self.kwargs['tm'] overlap_min = self.kwargs['overlap_min'] min_exception = self.kwargs['min_exception'] start_5 = self.kwargs['start_5'] if len(self.template) < length_range[0]: # If sequence can be built with just two oligos, do that oligos = [self.template, self.template.reverse_complement()] overlaps = [self.template] overlap_tms = [coral.analysis.tm(self.template)] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] return assembly_dict if oligo_number: # Make first attempt using length_range[1] and see what happens step = 3 # Decrease max range by this amount each iteration length_max = length_range[1] current_oligo_n = oligo_number + 1 oligo_n_met = False above_min_len = length_max > length_range[0] if oligo_n_met or not above_min_len: raise Exception('Failed to design assembly.') while not oligo_n_met and above_min_len: # Starting with low range and going up doesnt work for longer # sequence (overlaps become longer than 80) assembly = _grow_overlaps(self.template, melting_temp, require_even, length_max, overlap_min, min_exception) current_oligo_n = len(assembly[0]) if current_oligo_n > oligo_number: break
python
{ "resource": "" }
q2167
OligoAssembly.primers
train
def primers(self, tm=60): '''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best).
python
{ "resource": "" }
q2168
OligoAssembly.write_map
train
def write_map(self, path): '''Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str ''' starts = [index[0] for index in self.overlap_indices] features = [] for i, start in enumerate(starts): stop = start + len(self.overlaps[i]) name = 'overlap {}'.format(i + 1) feature_type = 'misc' strand = 0
python
{ "resource": "" }
q2169
coding_sequence
train
def coding_sequence(rna): '''Extract coding sequence from an RNA template. :param seq: Sequence from which to extract a coding sequence. :type seq: coral.RNA :param material: Type of sequence ('dna' or 'rna') :type material: str :returns: The first coding sequence (start codon -> stop codon) matched from 5' to 3'. :rtype: coral.RNA :raises: ValueError if rna argument has no start codon. ValueError if rna argument has no stop codon in-frame with the first start codon. ''' if isinstance(rna, coral.DNA):
python
{ "resource": "" }
q2170
Rebase.update
train
def update(self): '''Update definitions.''' # Download http://rebase.neb.com/rebase/link_withref to tmp self._tmpdir = tempfile.mkdtemp() try: self._rebase_file = self._tmpdir + '/rebase_file' print 'Downloading latest enzyme definitions' url = 'http://rebase.neb.com/rebase/link_withref' header = {'User-Agent': 'Mozilla/5.0'} req = urllib2.Request(url, headers=header) con = urllib2.urlopen(req) with open(self._rebase_file, 'wb') as rebase_file: rebase_file.write(con.read()) # Process into self._enzyme_dict self._process_file() except urllib2.HTTPError, e: print 'HTTP Error: {} {}'.format(e.code, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes except urllib2.URLError, e: print 'URL Error: {} {}'.format(e.reason, url) print 'Falling back on default enzyme list' self._enzyme_dict = coral.constants.fallback_enzymes # Process into RestrictionSite objects? (depends on speed) print 'Processing into RestrictionSite instances.'
python
{ "resource": "" }
q2171
Rebase._process_file
train
def _process_file(self): '''Process rebase file into dict with name and cut site information.''' print 'Processing file' with open(self._rebase_file, 'r') as f: raw = f.readlines() names = [line.strip()[3:] for line in raw if line.startswith('<1>')] seqs = [line.strip()[3:] for line in raw if line.startswith('<5>')] if len(names) != len(seqs): raise Exception('Found different number of enzyme names and ' 'sequences.') self._enzyme_dict = {} for name, seq in zip(names, seqs): if '?' in seq: # Is unknown sequence, don't keep it pass elif seq.startswith('(') and seq.endswith(')'): # Has four+ cut sites, don't keep it pass elif '^' in seq: # Has reasonable internal cut sites, keep it top_cut = seq.index('^')
python
{ "resource": "" }
q2172
tempdir
train
def tempdir(fun): '''For use as a decorator of instance methods - creates a temporary dir named self._tempdir and then deletes it after the method runs. :param fun: function to decorate :type fun: instance method ''' def wrapper(*args, **kwargs): self = args[0]
python
{ "resource": "" }
q2173
convert_sequence
train
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide') :param seq: DNA or RNA sequence. :type seq: coral.DNA or coral.RNA :param to_material: material to which to convert ('rna', 'dna', or 'peptide'). :type to_material: str :returns: sequence of type coral.sequence.[material type] ''' if isinstance(seq, coral.DNA) and to_material == 'rna': # Transcribe # Can't transcribe a gap if '-' in seq: raise ValueError('Cannot transcribe gapped DNA') # Convert DNA chars to RNA chars origin = ALPHABETS['dna'][:-1] destination = ALPHABETS['rna'] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate RNA object
python
{ "resource": "" }
q2174
NucleicAcid.gc
train
def gc(self): '''Find the frequency of G and C in the current sequence.'''
python
{ "resource": "" }
q2175
NucleicAcid.is_rotation
train
def is_rotation(self, other): '''Determine whether two sequences are the same, just at different rotations. :param other: The sequence to check for rotational equality. :type other: coral.sequence._sequence.Sequence ''' if len(self) != len(other):
python
{ "resource": "" }
q2176
NucleicAcid.linearize
train
def linearize(self, index=0): '''Linearize the Sequence at an index. :param index: index at which to linearize. :type index: int :returns: A linearized version of the current sequence. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if the input is a linear sequence. ''' if
python
{ "resource": "" }
q2177
NucleicAcid.mw
train
def mw(self): '''Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float ''' counter = collections.Counter(self.seq.lower()) mw_a = counter['a'] * 313.2 mw_t = counter['t'] * 304.2 mw_g = counter['g'] *
python
{ "resource": "" }
q2178
five_resect
train
def five_resect(dna, n_bases): '''Remove bases from 5' end of top strand. :param dna: Sequence to resect. :type dna: coral.DNA :param n_bases: Number of bases cut back. :type n_bases: int :returns: DNA sequence resected at the 5' end by n_bases. :rtype: coral.DNA ''' new_instance = dna.copy() if n_bases >= len(dna):
python
{ "resource": "" }
q2179
_remove_end_gaps
train
def _remove_end_gaps(sequence): '''Removes double-stranded gaps from ends of the sequence. :returns: The current sequence with terminal double-strand gaps ('-') removed. :rtype: coral.DNA ''' # Count terminal blank sequences def count_end_gaps(seq): gap = coral.DNA('-') count = 0 for base in seq: if base == gap: count += 1 else: break
python
{ "resource": "" }
q2180
needle
train
def needle(reference, query, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Do a Needleman-Wunsch alignment. :param reference: Reference sequence. :type reference: coral.DNA :param query: Sequence to align against the reference. :type query: coral.DNA :param gapopen: Penalty for opening a gap. :type gapopen: float :param gapextend: Penalty for extending a gap. :type gapextend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: (aligned reference, aligned query, score) :rtype: tuple of two coral.DNA instances and a float ''' # Align using cython Needleman-Wunsch aligned_ref, aligned_res = aligner(str(reference), str(query), gap_open=gap_open,
python
{ "resource": "" }
q2181
needle_msa
train
def needle_msa(reference, results, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Create a multiple sequence alignment based on aligning every result sequence against the reference, then inserting gaps until every aligned reference is identical ''' gap = '-' # Convert alignments to list of strings alignments = [] for result in results: ref_dna, res_dna, score = needle(reference, result, gap_open=gap_open, gap_extend=gap_extend, matrix=matrix) alignments.append([str(ref_dna), str(res_dna), score]) def insert_gap(sequence, position): return sequence[:position] + gap + sequence[position:] i = 0 while True: # Iterate over 'columns' in every reference refs = [alignment[0][i] for alignment in alignments] # If there's a non-unanimous gap, insert gap into alignments gaps = [ref == gap for ref in refs] if any(gaps) and not all(gaps): for alignment in alignments: if alignment[0][i] != gap: alignment[0] = insert_gap(alignment[0], i)
python
{ "resource": "" }
q2182
needle_multi
train
def needle_multi(references, queries, gap_open=-15, gap_extend=0, matrix=submat.DNA_SIMPLE): '''Batch process of sequencing split over several cores. Acts just like needle but sequence inputs are lists. :param references: References sequence. :type references: coral.DNA list :param queries: Sequences to align against the reference. :type queries: coral.DNA list :param gap_open: Penalty for opening a gap. :type gap_open: float :param gap_extend: Penalty for extending a gap. :type gap_extend: float :param matrix: Matrix to use for alignment - options are DNA_simple (for DNA) and BLOSUM62 (for proteins). :type matrix: str :returns: a list of the same output as coral.sequence.needle
python
{ "resource": "" }
q2183
import_global
train
def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (str): the modules to import, use None for everything exception (Exception): the exception to catch, e.g. ImportError `locals_`: the `locals()` method (in case you need a different scope) `globals_`: the `globals()` method (in case you need a different scope) level (int): the level to import from, this can be used for relative imports ''' frame = None try: # If locals_ or globals_ are not given, autodetect them by inspecting # the current stack if locals_ is None or globals_ is None: import inspect frame = inspect.stack()[1][0] if locals_ is None: locals_ = frame.f_locals if globals_ is None: globals_ = frame.f_globals try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.', globals=globals_, locals=locals_, fromlist=name[1:], level=max(level, 0),
python
{ "resource": "" }
q2184
camel_to_underscore
train
def camel_to_underscore(name): '''Convert camel case style naming to underscore style naming If there are existing underscores they will be collapsed with the to-be-added underscores. Multiple consecutive capital letters will not be split except for the last one. >>> camel_to_underscore('SpamEggsAndBacon') 'spam_eggs_and_bacon' >>> camel_to_underscore('Spam_and_bacon') 'spam_and_bacon' >>> camel_to_underscore('Spam_And_Bacon') 'spam_and_bacon' >>> camel_to_underscore('__SpamAndBacon__') '__spam_and_bacon__'
python
{ "resource": "" }
q2185
timedelta_to_seconds
train
def timedelta_to_seconds(delta): '''Convert a timedelta to seconds with the microseconds as fraction Note that this method has become largely obsolete with the `timedelta.total_seconds()` method introduced in Python 2.7. >>> from datetime import timedelta >>> '%d' % timedelta_to_seconds(timedelta(days=1)) '86400' >>> '%d' % timedelta_to_seconds(timedelta(seconds=1)) '1' >>> '%.6f' % timedelta_to_seconds(timedelta(seconds=1, microseconds=1)) '1.000001'
python
{ "resource": "" }
q2186
get_terminal_size
train
def get_terminal_size(): # pragma: no cover '''Get the current size of your terminal Multiple returns are not always a good idea, but in this case it greatly simplifies the code so I believe it's justified. It's not the prettiest function but that's never really possible with cross-platform code. Returns: width, height: Two integers containing width and height ''' try: # Default to 79 characters for IPython notebooks from IPython import get_ipython ipython = get_ipython() from ipykernel import zmqshell if isinstance(ipython, zmqshell.ZMQInteractiveShell): return 79, 24 except Exception: # pragma: no cover pass try: # This works for Python 3, but not Pypy3. Probably the best method if # it's supported so let's always try import shutil w, h = shutil.get_terminal_size()
python
{ "resource": "" }
q2187
Skype.AsyncSearchUsers
train
def AsyncSearchUsers(self, Target): """Asynchronously searches for Skype users. :Parameters: Target : unicode Search target (name or email address). :return: A search identifier. It will be passed along with the results to the `SkypeEvents.AsyncSearchUsersFinished` event after the search is completed.
python
{ "resource": "" }
q2188
Skype.Attach
train
def Attach(self, Protocol=5, Wait=True): """Establishes a connection to Skype. :Parameters: Protocol : int Minimal Skype protocol version. Wait : bool If set to False, blocks forever until the connection is established. Otherwise, timeouts after the `Timeout`.
python
{ "resource": "" }
q2189
Skype.Call
train
def Call(self, Id=0): """Queries a call object. :Parameters: Id : int Call identifier.
python
{ "resource": "" }
q2190
Skype.ChangeUserStatus
train
def ChangeUserStatus(self, Status): """Changes the online status for the current user. :Parameters: Status : `enums`.cus* New online status for the user. :note: This function waits until the online status changes. Alternatively, use the `CurrentUserStatus` property to perform an immediate change of status.
python
{ "resource": "" }
q2191
Skype.Chat
train
def Chat(self, Name=''): """Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat` """
python
{ "resource": "" }
q2192
Skype.ClearCallHistory
train
def ClearCallHistory(self, Username='ALL', Type=chsAllCalls): """Clears the call history. :Parameters: Username : str Skypename of the user. A special value of 'ALL' means that entries of all users should be removed.
python
{ "resource": "" }
q2193
Skype.Command
train
def Command(self, Command, Reply=u'', Block=False, Timeout=30000, Id=-1): """Creates an API command object. :Parameters: Command : unicode Command string. Reply : unicode Expected reply. By default any reply is accepted (except errors which raise an `SkypeError` exception). Block : bool If set to True, `SendCommand` method waits for a response from Skype API before returning. Timeout : float, int or long Timeout. Used if Block == True. Timeout may be expressed in milliseconds if the type
python
{ "resource": "" }
q2194
Skype.Conference
train
def Conference(self, Id=0): """Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference` """
python
{ "resource": "" }
q2195
Skype.CreateChatWith
train
def CreateChatWith(self, *Usernames): """Creates a chat with one or more users. :Parameters: Usernames : str One or more Skypenames of the users. :return: A chat object :rtype: `Chat`
python
{ "resource": "" }
q2196
Skype.CreateGroup
train
def CreateGroup(self, GroupName): """Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup` """ groups = self.CustomGroups
python
{ "resource": "" }
q2197
Skype.CreateSms
train
def CreateSms(self, MessageType, *TargetNumbers): """Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers.
python
{ "resource": "" }
q2198
Skype.Greeting
train
def Greeting(self, Username=''): """Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail` """ for v in self.Voicemails:
python
{ "resource": "" }
q2199
Skype.Message
train
def Message(self, Id=0): """Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage` """
python
{ "resource": "" }