code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
'''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) f.write('>{}\n'.format(name)) f.write(str(sequence) + '\n') process = subprocess.Popen(arguments, stdout=subprocess.PIPE, stderr=open(os.devnull, 'w'), cwd=tempdir) stdout = process.communicate()[0] finally: shutil.rmtree(tempdir) # Process stdout into something downstream process can use records = stdout.split('>') # First line is now blank records.pop(0) aligned_list = [] for record in records: lines = record.split('\n') name = lines.pop(0) aligned_list.append(coral.DNA(''.join(lines))) return aligned_list
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
3.00216
1.923736
1.560589
'''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 = [seq[i:i + size] for i in range(len(seq) - size + 1)] counted = Counter(n_mers) # No one cares about patterns that appear once, so exclude them found_repeats = [(key, value) for key, value in counted.iteritems() if value > 1] return found_repeats
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
4.720528
2.454477
1.923232
'''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: if seq.circular: raise ValueError('Input sequences must be linear.') # Copy input list working_list = [s.copy() for s in seq_list] # Attempt to fuse fragments together until only one is left while len(working_list) > 1: working_list = _find_fuse_next(working_list, homology, tm) if not linear: # Fuse the final fragment to itself working_list = _fuse_last(working_list, homology, tm) # Clear features working_list[0].features = [] return _annotate_features(working_list[0], seq_list)
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.
5.592823
3.149647
1.775698
'''Find the next sequence to fuse, and fuse it (or raise exception). :param homology: length of terminal homology in bp :type homology: int :raises: AmbiguousGibsonError if there is more than one way for the fragment ends to combine. GibsonOverlapError if no homology match can be found. ''' # 1. Take the first sequence and find all matches # Get graphs: # a) pattern watson : targets watson # b) pattern watson : targets crick # c) pattern crick: targets watson # d) pattern crick: targets crick pattern = working_list[0] targets = working_list[1:] # Output graph nodes of terminal binders: # (destination, size, strand1, strand2) def graph_strands(strand1, strand2): graph = [] for i, target in enumerate(targets): matchlen = homology_report(pattern, target, strand1, strand2, cutoff=homology, min_tm=tm) if matchlen: graph.append((i, matchlen, strand1, strand2)) return graph graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cw = graph_strands('c', 'w') graph_cc = graph_strands('c', 'c') graphs_w = graph_ww + graph_wc graphs_c = graph_cw + graph_cc graphs = graphs_w + graphs_c # 2. See if there's more than one result on a strand. # If so, throw an exception. if len(graphs_w) > 1 or len(graphs_c) > 1: raise AmbiguousGibsonError('multiple compatible ends.') if len(graphs_w) == len(graphs_c) == 0: raise GibsonOverlapError('Failed to find compatible Gibson ends.') # 3. There must be one result. Where is it? # If there's one result on each strand, go with the one that matches the # pattern watson strand (will occur first - index 0) match = graphs[0] # 4. Combine pieces together # 4a. Orient pattern sequence if match[2] == 'c': left_side = pattern.reverse_complement() else: left_side = pattern # 4b. Orient target sequence if match[3] == 'w': right_side = working_list.pop(match[0] + 1).reverse_complement() else: right_side = working_list.pop(match[0] + 1) working_list[0] = left_side + right_side[match[1]:] return working_list
def _find_fuse_next(working_list, homology, tm)
Find the next sequence to fuse, and fuse it (or raise exception). :param homology: length of terminal homology in bp :type homology: int :raises: AmbiguousGibsonError if there is more than one way for the fragment ends to combine. GibsonOverlapError if no homology match can be found.
3.936051
3.064308
1.284483
'''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): return (0, length, strand1, strand2) else: return [] # cw is redundant with wc graph_ww = graph_strands('w', 'w') graph_wc = graph_strands('w', 'c') graph_cc = graph_strands('c', 'c') if graph_ww + graph_cc: raise AmbiguousGibsonError('Self-self binding during circularization.') if not graph_wc: raise ValueError('Failed to find compatible ends for circularization.') working_list[0] = working_list[0][:-graph_wc[1]].circularize() return working_list
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.
7.771422
4.717115
1.647495
'''Acquire a sequence from SGD http://www.yeastgenome.org. :param locus_name: Common name or systematic name for the locus (e.g. ACT1 or YFL039C). :type locus_name: str :param flanking_size: The length of flanking DNA (on each side) to return :type flanking_size: int ''' 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') if flanking_size > 0: # The view specifies the output columns # secondaryIdentifier: the systematic name (e.g. YFL039C) # symbol: short name (e.g. ACT1) # length: sequence length # flankingRegions.direction: Upstream or downstream (or both) of locus # flankingRegions.sequence.length: length of the flanking regions # flankingRegions.sequence.residues: sequence of the flanking regions query.add_view('secondaryIdentifier', 'symbol', 'length', 'flankingRegions.direction', 'flankingRegions.sequence.length', 'flankingRegions.sequence.residues') # You can edit the constraint values below query.add_constraint('flankingRegions.direction', '=', 'both', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='B') query.add_constraint('flankingRegions.distance', '=', '{:.1f}kb'.format(flanking_size / 1000.), code='C') # Uncomment and edit the code below to specify your own custom logic: query.set_logic('A and B and C') # TODO: What to do when there's more than one result? first_result = query.rows().next() # FIXME: Use logger module instead # print first_result['secondaryIdentifier'] # print first_result['symbol'], row['length'] # print first_result['flankingRegions.direction'] # print first_result['flankingRegions.sequence.length'] # print first_result['flankingRegions.sequence.residues'] seq = coral.DNA(first_result['flankingRegions.sequence.residues']) # TODO: add more metadata elif flanking_size == 0: # The view specifies the output columns query.add_view('primaryIdentifier', 'secondaryIdentifier', 'symbol', 'name', 'sgdAlias', 'organism.shortName', 'sequence.length', 'sequence.residues', 'description', 'qualifier') query.add_constraint('status', 'IS NULL', code='D') query.add_constraint('status', '=', 'Active', code='C') query.add_constraint('qualifier', 'IS NULL', code='B') query.add_constraint('qualifier', '!=', 'Dubious', code='A') query.add_constraint('Gene', 'LOOKUP', locus_name, 'S. cerevisiae', code='E') # Your custom constraint logic is specified with the code below: query.set_logic('(A or B) and (C or D) and E') first_result = query.rows().next() seq = coral.DNA(first_result['sequence.residues']) else: print 'Problem with the flanking region size....' seq = coral.DNA('') return seq
def fetch_yeast_locus_sequence(locus_name, flanking_size=0)
Acquire a sequence from SGD http://www.yeastgenome.org. :param locus_name: Common name or systematic name for the locus (e.g. ACT1 or YFL039C). :type locus_name: str :param flanking_size: The length of flanking DNA (on each side) to return :type flanking_size: int
3.373528
2.846654
1.185085
'''Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :returns: A DNA sequence. :rtype: coral.DNA ''' import requests if start != end: if reverse_complement: rev_option = '-REV' else: rev_option = '' param_url = '&chr=' + str(chromosome) + '&beg=' + str(start) + \ '&end=' + str(end) + '&rev=' + rev_option url = 'http://www.yeastgenome.org/cgi-bin/getSeq?map=a2map' + \ param_url res = requests.get(url) # ok... sadely, I contacted SGD and they haven;t implemented this so # I have to parse their yeastgenome page, but # it is easy between the raw sequence is between <pre> tags! # warning that's for the first < so we need +5! begin_index = res.text.index('<pre>') end_index = res.text.index('</pre>') sequence = res.text[begin_index + 5:end_index] sequence = sequence.replace('\n', '').replace('\r', '') else: sequence = '' return coral.DNA(sequence)
def get_yeast_sequence(chromosome, start, end, reverse_complement=False)
Acquire a sequence from SGD http://www.yeastgenome.org :param chromosome: Yeast chromosome. :type chromosome: int :param start: A biostart. :type start: int :param end: A bioend. :type end: int :param reverse_complement: Get the reverse complement. :type revervse_complement: bool :returns: A DNA sequence. :rtype: coral.DNA
5.329413
3.74203
1.424204
'''Acquire the location of a gene from SGD http://www.yeastgenome.org :param gene_name: Name of the gene. :type gene_name: string :returns location: [int: chromosome, int:biostart, int:bioend, int:strand] :rtype location: list ''' 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', 'organism.shortName', 'chromosome.primaryIdentifier', 'chromosomeLocation.start', 'chromosomeLocation.end', 'chromosomeLocation.strand') # Uncomment and edit the line below (the default) to select a custom sort # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') chromosomes = {'chrI': 1, 'chrII': 2, 'chrIII': 3, 'chrIV': 4, 'chrV': 5, 'chrVI': 6, 'chrVII': 7, 'chrVIII': 8, 'chrIX': 9, 'chrX': 10, 'chrXI': 11, 'chrXII': 12, 'chrXIII': 13, 'chrXIV': 14, 'chrXV': 15, 'chrXVI': 16} first_result = query.rows().next() return [chromosomes[first_result['chromosome.primaryIdentifier']], first_result['chromosomeLocation.start'], first_result['chromosomeLocation.end'], int(first_result['chromosomeLocation.strand'])]
def get_yeast_gene_location(gene_name)
Acquire the location of a gene from SGD http://www.yeastgenome.org :param gene_name: Name of the gene. :type gene_name: string :returns location: [int: chromosome, int:biostart, int:bioend, int:strand] :rtype location: list
2.942832
2.488595
1.182528
'''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 # order: # query.add_sort_order('Gene.primaryIdentifier', 'ASC') # You can edit the constraint values below query.add_constraint('organism.shortName', '=', 'S. cerevisiae', code='B') query.add_constraint('Gene', 'LOOKUP', gene_name, code='A') # Uncomment and edit the code below to specify your own custom logic: # query.set_logic('A and B') for row in query.rows(): gid = row['secondaryIdentifier'] return gid
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
5.230052
4.018372
1.301535
'''Retrieve promoter from Yeast Promoter Atlas (http://ypa.csbb.ntu.edu.tw). :param gene_name: Common name for yeast gene. :type gene_name: str :returns: Double-stranded DNA sequence of the promoter. :rtype: coral.DNA ''' import requests loc = get_yeast_gene_location(gene_name) gid = get_gene_id(gene_name) ypa_baseurl = 'http://ypa.csbb.ntu.edu.tw/do' params = {'act': 'download', 'nucle': 'InVitro', 'right': str(loc[2]), 'left': str(loc[1]), 'gene': str(gid), 'chr': str(loc[0])} response = requests.get(ypa_baseurl, params=params) text = response.text # FASTA records are just name-sequence pairs split up by > e.g. # >my_dna_name # GACGATA # TODO: most of this is redundant, as we just want the 2nd record record_split = text.split('>') record_split.pop(0) parsed = [] for record in record_split: parts = record.split('\n') sequence = coral.DNA(''.join(parts[1:])) sequence.name = parts[0] parsed.append(sequence) return parsed[1]
def get_yeast_promoter_ypa(gene_name)
Retrieve promoter from Yeast Promoter Atlas (http://ypa.csbb.ntu.edu.tw). :param gene_name: Common name for yeast gene. :type gene_name: str :returns: Double-stranded DNA sequence of the promoter. :rtype: coral.DNA
4.868456
3.352904
1.452012
'''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 list ''' for i, overlap in enumerate(overlaps): first_index = oligo_indices[0][i + 1] second_index = oligo_indices[1][i] overlap = dna[first_index:second_index] overlaps[i] = overlap return overlaps
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 list
3.05727
1.556419
1.964297
'''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], index, 'right') elif left_len == length_max: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: if left_len > right_len: oligo_indices[0] = _adjust_overlap(oligo_indices[0], index, 'left') else: oligo_indices[1] = _adjust_overlap(oligo_indices[1], index, 'right') # Recalculate oligos from start and end indices oligos = [dna[start:end] for start, end in zip(*oligo_indices)] return oligos
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
2.512723
1.633985
1.537789
'''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 :raises: ValueError if direction isn't \'left\' or \'right\'. ''' if direction == 'left': positions_list[index + 1] -= 1 elif direction == 'right': positions_list[index] += 1 else: raise ValueError('direction must be \'left\' or \'right\'.') return positions_list
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 :raises: ValueError if direction isn't \'left\' or \'right\'.
2.71947
1.417718
1.918202
'''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 length_max -= step oligo_n_met = current_oligo_n == oligo_number else: assembly = _grow_overlaps(self.template, melting_temp, require_even, length_range[1], overlap_min, min_exception) oligos, overlaps, overlap_tms, overlap_indices = assembly if start_5: for i in [x for x in range(len(oligos)) if x % 2 == 1]: oligos[i] = oligos[i].reverse_complement() else: for i in [x for x in range(len(oligos)) if x % 2 == 0]: oligos[i] = oligos[i].reverse_complement() # Make single-stranded oligos = [oligo.top for oligo in oligos] assembly_dict = {'oligos': oligos, 'overlaps': overlaps, 'overlap_tms': overlap_tms, 'overlap_indices': overlap_indices} self.oligos = assembly_dict['oligos'] self.overlaps = assembly_dict['overlaps'] self.overlap_tms = assembly_dict['overlap_tms'] self.overlap_indices = assembly_dict['overlap_indices'] for i in range(len(self.overlap_indices) - 1): # TODO: either raise an exception or prevent this from happening # at all current_start = self.overlap_indices[i + 1][0] current_end = self.overlap_indices[i][1] if current_start <= current_end: self.warning = 'warning: overlapping overlaps!' print self.warning self._has_run = True return assembly_dict
def design_assembly(self)
Design the overlapping oligos. :returns: Assembly oligos, and the sequences, Tms, and indices of their overlapping regions. :rtype: dict
3.199106
2.893389
1.105661
'''Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list ''' self.primers = coral.design.primers(self.template, tm=tm) return self.primers
def primers(self, tm=60)
Design primers for amplifying the assembled sequence. :param tm: melting temperature (lower than overlaps is best). :type tm: float :returns: Primer list (the output of coral.design.primers). :rtype: list
7.827956
1.933184
4.049256
'''Write assembly oligos and (if applicable) primers to csv. :param path: path to csv file, including .csv extension. :type path: str ''' with open(path, 'wb') as oligo_file: oligo_writer = csv.writer(oligo_file, delimiter=',', quoting=csv.QUOTE_MINIMAL) oligo_writer.writerow(['name', 'oligo', 'notes']) for i, oligo in enumerate(self.oligos): name = 'oligo {}'.format(i + 1) oligo_len = len(oligo) if i != len(self.oligos) - 1: oligo_tm = self.overlap_tms[i] notes = 'oligo length: {}, '.format(oligo_len) + \ 'overlap Tm: {:.2f}'.format(oligo_tm) else: notes = 'oligo length: {}'.format(oligo_len) oligo_writer.writerow([name, oligo, notes]) if self.primers: for i, (primer, melt) in enumerate(self.primers): oligo_writer.writerow(['primer {}'.format(i + 1), primer, 'Tm: {:.2f}'.format(melt)])
def write(self, path)
Write assembly oligos and (if applicable) primers to csv. :param path: path to csv file, including .csv extension. :type path: str
2.633971
2.148472
1.225974
'''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 features.append(coral.Feature(name, start, stop, feature_type, strand=strand)) seq_map = coral.DNA(self.template, features=features) coral.seqio.write_dna(seq_map, path)
def write_map(self, path)
Write genbank map that highlights overlaps. :param path: full path to .gb file to write. :type path: str
5.06349
3.652992
1.386121
'''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): rna = transcribe(rna) codons_left = len(rna) // 3 start_codon = coral.RNA('aug') stop_codons = [coral.RNA('uag'), coral.RNA('uga'), coral.RNA('uaa')] start = None stop = None valid = [None, None] index = 0 while codons_left: codon = rna[index:index + 3] if valid[0] is None: if codon in start_codon: start = index valid[0] = True else: if codon in stop_codons: stop = index + 3 valid[1] = True break index += 3 codons_left -= 1 if valid[0] is None: raise ValueError('Sequence has no start codon.') elif stop is None: raise ValueError('Sequence has no stop codon.') coding_rna = rna[start:stop] return coding_rna
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.
3.100697
1.842694
1.682698
'''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.' self.restriction_sites = {} # TODO: make sure all names are unique for key, (site, cuts) in self._enzyme_dict.iteritems(): # Make a site try: r = coral.RestrictionSite(coral.DNA(site), cuts, name=key) # Add it to dict with name as key self.restriction_sites[key] = r except ValueError: # Encountered ambiguous sequence, have to ignore it until # coral.DNA can handle ambiguous DNA pass
def update(self)
Update definitions.
4.272219
4.178168
1.02251
'''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('^') bottom_cut = len(seq) - top_cut - 1 site = seq.replace('^', '') self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) elif seq.endswith(')'): # Has reasonable external cut sites, keep it # (4-cutter also starts with '(') # separate site and cut locations site, cuts = seq.split('(') cuts = cuts.replace(')', '') top_cut, bottom_cut = [int(x) + len(site) for x in cuts.split('/')] self._enzyme_dict[name] = (site, (top_cut, bottom_cut)) shutil.rmtree(self._tmpdir)
def _process_file(self)
Process rebase file into dict with name and cut site information.
3.881324
3.373667
1.150476
'''Create a copy of the current instance. :returns: A safely editable copy of the current sequence. :rtype: coral.Peptide ''' return type(self)(str(self._sequence), features=self.features, run_checks=False)
def copy(self)
Create a copy of the current instance. :returns: A safely editable copy of the current sequence. :rtype: coral.Peptide
13.384428
5.234853
2.556791
'''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] if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) self._tempdir = tempfile.mkdtemp() # If the method raises an exception, delete the temporary dir try: retval = fun(*args, **kwargs) finally: shutil.rmtree(self._tempdir) if os.path.isdir(self._tempdir): shutil.rmtree(self._tempdir) return retval return wrapper
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
2.772648
1.817054
1.525903
'''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 converted = coral.RNA(converted) elif isinstance(seq, coral.RNA): if to_material == 'dna': # Reverse transcribe origin = ALPHABETS['rna'] destination = ALPHABETS['dna'][:-1] code = dict(zip(origin, destination)) converted = ''.join([code.get(str(k), str(k)) for k in seq]) # Instantiate DNA object converted = coral.DNA(converted) elif to_material == 'peptide': # Translate seq_list = list(str(seq)) # Convert to peptide until stop codon is found. converted = [] while True: if len(seq_list) >= 3: base_1 = seq_list.pop(0) base_2 = seq_list.pop(0) base_3 = seq_list.pop(0) codon = ''.join(base_1 + base_2 + base_3).upper() amino_acid = CODONS[codon] # Stop when stop codon is found if amino_acid == '*': break converted.append(amino_acid) else: break converted = ''.join(converted) converted = coral.Peptide(converted) else: msg1 = 'Conversion from ' msg2 = '{0} to {1} is not supported.'.format(seq.__class__.__name__, to_material) raise ValueError(msg1 + msg2) return converted
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]
2.695851
2.031673
1.326912
'''Find the frequency of G and C in the current sequence.''' gc = len([base for base in self.seq if base == 'C' or base == 'G']) return float(gc) / len(self)
def gc(self)
Find the frequency of G and C in the current sequence.
5.606518
3.225568
1.738149
'''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): return False for i in range(len(self)): if self.rotate(i) == other: return True return False
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
4.614704
2.223424
2.075494
'''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 not self.circular and index != 0: raise ValueError('Cannot relinearize a linear sequence.') copy = self.copy() # Snip at the index if index: return copy[index:] + copy[:index] copy.circular = False return copy
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.
5.574327
2.857498
1.950772
'''Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints ''' if self.circular: if len(pattern) >= 2 * len(self): raise ValueError('Search pattern longer than searchable ' + 'sequence.') seq = self + self[:len(pattern) - 1] return super(NucleicAcid, seq).locate(pattern) else: return super(NucleicAcid, self).locate(pattern)
def locate(self, pattern)
Find sequences matching a pattern. :param pattern: Sequence for which to find matches. :type pattern: str :returns: Indices of pattern matches. :rtype: list of ints
3.948117
2.815651
1.402204
'''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'] * 289.2 mw_c = counter['c'] * 329.2 mw_u = counter['u'] * 306.2 if self.material == 'dna': return mw_a + mw_t + mw_g + mw_c + 79.0 else: return mw_a + mw_u + mw_g + mw_c + 159.0
def mw(self)
Calculate the molecular weight. :returns: The molecular weight of the current sequence in amu. :rtype: float
3.13267
2.698668
1.160821
'''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is negative. ''' if not self.circular and n != 0: raise ValueError('Cannot rotate a linear sequence') else: rotated = self[-n:] + self[:-n] return rotated.circularize()
def rotate(self, n)
Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is negative.
6.575637
2.257452
2.912858
'''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): new_instance.top.seq = ''.join(['-' for i in range(len(dna))]) else: new_instance.top.seq = '-' * n_bases + str(dna)[n_bases:] new_instance = _remove_end_gaps(new_instance) return new_instance
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
3.561391
2.20389
1.615957
'''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 return count top_left = count_end_gaps(sequence.top) top_right = count_end_gaps(reversed(sequence.top)) bottom_left = count_end_gaps(reversed(sequence.bottom)) bottom_right = count_end_gaps(sequence.bottom) # Trim sequence left_index = min(top_left, bottom_left) right_index = len(sequence) - min(top_right, bottom_right) return sequence[left_index:right_index]
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
3.296053
2.374187
1.388287
'''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, gap_extend=gap_extend, method='global_cfe', matrix=matrix.matrix, alphabet=matrix.alphabet) # Score the alignment score = score_alignment(aligned_ref, aligned_res, gap_open, gap_extend, matrix.matrix, matrix.alphabet) return cr.DNA(aligned_ref), cr.DNA(aligned_res), score
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
3.027293
1.906189
1.588139
'''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) alignment[1] = insert_gap(alignment[1], i) # If all references match, we're all done alignment_set = set(alignment[0] for alignment in alignments) if len(alignment_set) == 1: break # If we've reach the end of some, but not all sequences, add end gap lens = [len(alignment[0]) for alignment in alignments] if i + 1 in lens: for alignment in alignments: if len(alignment[0]) == i + 1: alignment[0] = alignment[0] + gap alignment[1] = alignment[1] + gap i += 1 if i > 20: break # Convert into MSA format output_alignment = [cr.DNA(alignments[0][0])] for alignment in alignments: output_alignment.append(cr.DNA(alignment[1])) return output_alignment
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
3.498324
3.08079
1.135528
'''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 :rtype: list ''' pool = multiprocessing.Pool() try: args_list = [[ref, que, gap_open, gap_extend, matrix] for ref, que in zip(references, queries)] aligned = pool.map(run_needle, args_list) except KeyboardInterrupt: print('Caught KeyboardInterrupt, terminating workers') pool.terminate() pool.join() raise KeyboardInterrupt return aligned
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 :rtype: list
4.010791
1.558041
2.574252
'''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), ) # Make sure we get the right part of a dotted import (i.e. # spam.eggs should return eggs, not spam) try: for attr in name[1:]: module = getattr(module, attr) except AttributeError: raise ImportError('No module named ' + '.'.join(name)) # If no list of modules is given, autodetect from either __all__ # or a dir() of the module if not modules: modules = getattr(module, '__all__', dir(module)) else: modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules): if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
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
3.764369
2.457566
1.531747
'''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__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__' ''' output = [] for i, c in enumerate(name): if i > 0: pc = name[i - 1] if c.isupper() and not pc.isupper() and pc != '_': # Uppercase and the previous character isn't upper/underscore? # Add the underscore output.append('_') elif i > 3 and not c.isupper(): # Will return the last 3 letters to check if we are changing # case previous = name[i - 3:i] if previous.isalpha() and previous.isupper(): output.insert(len(output) - 1, '_') output.append(c.lower()) return ''.join(output)
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__' >>> camel_to_underscore('__SpamANDBacon__') '__spam_and_bacon__'
3.26305
1.950651
1.6728
'''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' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001' ''' # Only convert to float if needed if delta.microseconds: total = delta.microseconds * 1e-6 else: total = 0 total += delta.seconds total += delta.days * 60 * 60 * 24 return total
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' >>> '%.6f' % timedelta_to_seconds(timedelta(microseconds=1)) '0.000001'
2.512455
1.482897
1.694288
'''Formats timedelta/datetime/seconds >>> format_time('1') '0:00:01' >>> format_time(1.234) '0:00:01' >>> format_time(1) '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) '1:01:01' >>> format_time(None) '--:--:--' >>> format_time(format_time) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Unknown type ... ''' precision_seconds = precision.total_seconds() if isinstance(timestamp, six.string_types + six.integer_types + (float, )): try: castfunc = six.integer_types[-1] timestamp = datetime.timedelta(seconds=castfunc(timestamp)) except OverflowError: # pragma: no cover timestamp = None if isinstance(timestamp, datetime.timedelta): seconds = timestamp.total_seconds() # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) return str(datetime.timedelta(seconds=seconds)) elif isinstance(timestamp, datetime.datetime): # Python 2 doesn't have the timestamp method if hasattr(timestamp, 'timestamp'): # pragma: no cover seconds = timestamp.timestamp() else: seconds = timedelta_to_seconds(timestamp - epoch) # Truncate the number to the given precision seconds = seconds - (seconds % precision_seconds) try: # pragma: no cover if six.PY3: dt = datetime.datetime.fromtimestamp(seconds) else: dt = datetime.datetime.utcfromtimestamp(seconds) except ValueError: # pragma: no cover dt = datetime.datetime.max return str(dt) elif isinstance(timestamp, datetime.date): return str(timestamp) elif timestamp is None: return '--:--:--' else: raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))
def format_time(timestamp, precision=datetime.timedelta(seconds=1))
Formats timedelta/datetime/seconds >>> format_time('1') '0:00:01' >>> format_time(1.234) '0:00:01' >>> format_time(1) '0:00:01' >>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6)) '2000-01-02 03:04:05' >>> format_time(datetime.date(2000, 1, 2)) '2000-01-02' >>> format_time(datetime.timedelta(seconds=3661)) '1:01:01' >>> format_time(None) '--:--:--' >>> format_time(format_time) # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: Unknown type ...
1.983826
1.654048
1.199377
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() if w and h: # The off by one is needed due to progressbars in some cases, for # safety we'll always substract it. return w - 1, h except Exception: # pragma: no cover pass try: w = int(os.environ.get('COLUMNS')) h = int(os.environ.get('LINES')) if w and h: return w, h except Exception: # pragma: no cover pass try: import blessings terminal = blessings.Terminal() w = terminal.width h = terminal.height if w and h: return w, h except Exception: # pragma: no cover pass try: w, h = _get_terminal_size_linux() if w and h: return w, h except Exception: # pragma: no cover pass try: # Windows detection doesn't always work, let's try anyhow w, h = _get_terminal_size_windows() if w and h: return w, h except Exception: # pragma: no cover pass try: # needed for window's python in cygwin's xterm! w, h = _get_terminal_size_tput() if w and h: return w, h except Exception: # pragma: no cover pass return 79, 24
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
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
2.91209
2.804233
1.038462
if not hasattr(self, '_AsyncSearchUsersCommands'): self._AsyncSearchUsersCommands = [] self.RegisterEventHandler('Reply', self._AsyncSearchUsersReplyHandler) command = Command('SEARCH USERS %s' % tounicode(Target), 'USERS', False, self.Timeout) self._AsyncSearchUsersCommands.append(command) self.SendCommand(command) # return pCookie - search identifier return command.Id
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. :rtype: int
6.17803
6.586921
0.937924
try: self._Api.protocol = Protocol self._Api.attach(self.Timeout, Wait) except SkypeAPIError: self.ResetCache() raise
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`.
10.003074
9.583374
1.043795
o = Call(self, Id) o.Status # Test if such a call exists. return o
def Call(self, Id=0)
Queries a call object. :Parameters: Id : int Call identifier. :return: Call object. :rtype: `call.Call`
30.210249
26.978928
1.119772
if self.CurrentUserStatus.upper() == Status.upper(): return self._ChangeUserStatus_Event = threading.Event() self._ChangeUserStatus_Status = Status.upper() self.RegisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) self.CurrentUserStatus = Status self._ChangeUserStatus_Event.wait() self.UnregisterEventHandler('UserStatus', self._ChangeUserStatus_UserStatus) del self._ChangeUserStatus_Event, self._ChangeUserStatus_Status
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.
2.780166
2.623474
1.059727
o = Chat(self, Name) o.Status # Tests if such a chat really exists. return o
def Chat(self, Name='')
Queries a chat object. :Parameters: Name : str Chat name. :return: A chat object. :rtype: `chat.Chat`
32.840382
35.390141
0.927953
cmd = 'CLEAR CALLHISTORY %s %s' % (str(Type), Username) self._DoCommand(cmd, cmd)
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. Type : `enums`.clt* Call type.
6.454511
10.81869
0.596607
from api import Command as CommandClass return CommandClass(Command, Reply, Block, Timeout, Id)
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 is int or long or in seconds (or fractions thereof) if the type is float. Id : int Command Id. The default (-1) means it will be assigned automatically as soon as the command is sent. :return: A command object. :rtype: `Command` :see: `SendCommand`
6.265855
7.163886
0.874645
o = Conference(self, Id) if Id <= 0 or not o.Calls: raise SkypeError(0, 'Unknown conference') return o
def Conference(self, Id=0)
Queries a call conference object. :Parameters: Id : int Conference Id. :return: A conference object. :rtype: `Conference`
9.966146
11.475331
0.868484
return Chat(self, chop(self._DoCommand('CHAT CREATE %s' % ', '.join(Usernames)), 2)[1])
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` :see: `Chat.AddMembers`
14.072657
19.698591
0.714399
groups = self.CustomGroups self._DoCommand('CREATE GROUP %s' % tounicode(GroupName)) for g in self.CustomGroups: if g not in groups and g.DisplayName == GroupName: return g raise SkypeError(0, 'Group creating failed')
def CreateGroup(self, GroupName)
Creates a custom contact group. :Parameters: GroupName : unicode Group name. :return: A group object. :rtype: `Group` :see: `DeleteGroup`
8.841931
7.142536
1.237926
return SmsMessage(self, chop(self._DoCommand('CREATE SMS %s %s' % (MessageType, ', '.join(TargetNumbers))), 2)[1])
def CreateSms(self, MessageType, *TargetNumbers)
Creates an SMS message. :Parameters: MessageType : `enums`.smsMessageType* Message type. TargetNumbers : str One or more target SMS numbers. :return: An sms message object. :rtype: `SmsMessage`
9.059043
10.313389
0.878377
for v in self.Voicemails: if Username and v.PartnerHandle != Username: continue if v.Type in (vmtDefaultGreeting, vmtCustomGreeting): return v
def Greeting(self, Username='')
Queries the greeting used as voicemail. :Parameters: Username : str Skypename of the user. :return: A voicemail object. :rtype: `Voicemail`
11.256641
9.010016
1.249347
o = ChatMessage(self, Id) o.Status # Test if such an id is known. return o
def Message(self, Id=0)
Queries a chat message object. :Parameters: Id : int Message Id. :return: A chat message object. :rtype: `ChatMessage`
33.976151
36.042145
0.942678
calls = self.ActiveCalls reply = self._DoCommand('CALL %s' % ', '.join(Targets)) # Skype for Windows returns the call status which gives us the call Id; if reply.startswith('CALL '): return Call(self, chop(reply, 2)[1]) # On linux we get 'OK' as reply so we search for the new call on # list of active calls. for c in self.ActiveCalls: if c not in calls: return c raise SkypeError(0, 'Placing call failed')
def PlaceCall(self, *Targets)
Places a call to a single user or creates a conference call. :Parameters: Targets : str One or more call targets. If multiple targets are specified, a conference call is created. The call target can be a Skypename, phone number, or speed dial code. :return: A call object. :rtype: `call.Call`
8.903157
8.09979
1.099184
return self._Property(ObjectType, ObjectId, PropName, Set)
def Property(self, ObjectType, ObjectId, PropName, Set=None)
Queries/sets the properties of an object. :Parameters: ObjectType : str Object type ('USER', 'CALL', 'CHAT', 'CHATMESSAGE', ...). ObjectId : str Object Id, depends on the object type. PropName : str Name of the property to access. Set : unicode or None Value the property should be set to or None if the value should be queried. :return: Property value if Set=None, None otherwise. :rtype: unicode or None
4.407807
7.85362
0.561245
try: self._Api.send_command(Command) except SkypeAPIError: self.ResetCache() raise
def SendCommand(self, Command)
Sends an API command. :Parameters: Command : `Command` Command to send. Use `Command` method to create a command.
10.122158
11.750237
0.861443
sms = self.CreateSms(smsMessageTypeOutgoing, *TargetNumbers) for name, value in Properties.items(): if isinstance(getattr(sms.__class__, name, None), property): setattr(sms, name, value) else: raise TypeError('Unknown property: %s' % prop) sms.Send() return sms
def SendSms(self, *TargetNumbers, **Properties)
Creates and sends an SMS message. :Parameters: TargetNumbers : str One or more target SMS numbers. Properties Message properties. Properties available are same as `SmsMessage` object properties. :return: An sms message object. The message is already sent at this point. :rtype: `SmsMessage`
4.534301
5.533662
0.819403
if self._Api.protocol >= 6: self._DoCommand('CALLVOICEMAIL %s' % Username) else: self._DoCommand('VOICEMAIL %s' % Username)
def SendVoicemail(self, Username)
Sends a voicemail to a specified user. :Parameters: Username : str Skypename of the user. :note: Should return a `Voicemail` object. This is not implemented yet.
6.178834
6.921349
0.892721
if not Username: Username = self.CurrentUserHandle o = User(self, Username) o.OnlineStatus # Test if such a user exists. return o
def User(self, Username='')
Queries a user object. :Parameters: Username : str Skypename of the user. :return: A user object. :rtype: `user.User`
13.866616
15.56505
0.890882
o = Voicemail(self, Id) o.Type # Test if such a voicemail exists. return o
def Voicemail(self, Id)
Queries the voicemail object. :Parameters: Id : int Voicemail Id. :return: A voicemail object. :rtype: `Voicemail`
14.076264
15.715789
0.895677
if WaitConnected: self._Connect_Event = threading.Event() self._Connect_Stream = [None] self._Connect_Username = Username self._Connect_ApplicationStreams(self, self.Streams) self._Owner.RegisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) self._Alter('CONNECT', Username) self._Connect_Event.wait() self._Owner.UnregisterEventHandler('ApplicationStreams', self._Connect_ApplicationStreams) try: return self._Connect_Stream[0] finally: del self._Connect_Stream, self._Connect_Event, self._Connect_Username else: self._Alter('CONNECT', Username)
def Connect(self, Username, WaitConnected=False)
Connects application to user. :Parameters: Username : str Name of the user to connect to. WaitConnected : bool If True, causes the method to wait until the connection is established. :return: If ``WaitConnected`` is True, returns the stream which can be used to send the data. Otherwise returns None. :rtype: `ApplicationStream` or None
3.569069
3.454292
1.033228
if Streams is None: Streams = self.Streams for s in Streams: s.SendDatagram(Text)
def SendDatagram(self, Text, Streams=None)
Sends datagram to application streams. :Parameters: Text : unicode Text to send. Streams : sequence of `ApplicationStream` Streams to send the datagram to or None if all currently connected streams should be used.
3.054992
3.895204
0.784296
self.Application._Alter('DATAGRAM', '%s %s' % (self.Handle, tounicode(Text)))
def SendDatagram(self, Text)
Sends datagram to stream. :Parameters: Text : unicode Datagram to send.
21.667595
29.397186
0.737064
self.Application._Alter('WRITE', '%s %s' % (self.Handle, tounicode(Text)))
def Write(self, Text)
Writes data to stream. :Parameters: Text : unicode Data to send.
25.18796
33.584129
0.749996
self._Skype._DoCommand('CREATE EVENT %s CAPTION %s HINT %s' % (tounicode(EventId), quote(tounicode(Caption)), quote(tounicode(Hint)))) return PluginEvent(self._Skype, EventId)
def CreateEvent(self, EventId, Caption, Hint)
Creates a custom event displayed in Skype client's events pane. :Parameters: EventId : unicode Unique identifier for the event. Caption : unicode Caption text. Hint : unicode Hint text. Shown when mouse hoovers over the event. :return: Event object. :rtype: `PluginEvent`
5.692331
4.644181
1.225691
cmd = 'CREATE MENU_ITEM %s CONTEXT %s CAPTION %s ENABLED %s' % (tounicode(MenuItemId), PluginContext, quote(tounicode(CaptionText)), cndexp(Enabled, 'true', 'false')) if HintText: cmd += ' HINT %s' % quote(tounicode(HintText)) if IconPath: cmd += ' ICON %s' % quote(path2unicode(IconPath)) if MultipleContacts: cmd += ' ENABLE_MULTIPLE_CONTACTS true' if PluginContext == pluginContextContact: cmd += ' CONTACT_TYPE_FILTER %s' % ContactType self._Skype._DoCommand(cmd) return PluginMenuItem(self._Skype, MenuItemId, CaptionText, HintText, Enabled)
def CreateMenuItem(self, MenuItemId, PluginContext, CaptionText, HintText=u'', IconPath='', Enabled=True, ContactType=pluginContactTypeAll, MultipleContacts=False)
Creates custom menu item in Skype client's "Do More" menus. :Parameters: MenuItemId : unicode Unique identifier for the menu item. PluginContext : `enums`.pluginContext* Menu item context. Allows to choose in which client windows will the menu item appear. CaptionText : unicode Caption text. HintText : unicode Hint text (optional). Shown when mouse hoovers over the menu item. IconPath : unicode Path to the icon (optional). Enabled : bool Initial state of the menu item. True by default. ContactType : `enums`.pluginContactType* In case of `enums.pluginContextContact` tells which contacts the menu item should appear for. Defaults to `enums.pluginContactTypeAll`. MultipleContacts : bool Set to True if multiple contacts should be allowed (defaults to False). :return: Menu item object. :rtype: `PluginMenuItem`
3.489574
3.427264
1.018181
self._Skype._Api.allow_focus(self._Skype.Timeout) self._Skype._DoCommand('FOCUS')
def Focus(self)
Brings the client window into focus.
21.35745
16.613121
1.285577
self._Skype._Api.allow_focus(self._Skype.Timeout) params = filter(None, (str(Name),) + Params) self._Skype._DoCommand('OPEN %s' % tounicode(' '.join(params)))
def OpenDialog(self, Name, *Params)
Open dialog. Use this method to open dialogs added in newer Skype versions if there is no dedicated method in Skype4Py. :Parameters: Name : str Dialog name. Params : unicode One or more optional parameters.
11.030926
12.052468
0.915242
self.OpenDialog('IM', Username, tounicode(Text))
def OpenMessageDialog(self, Username, Text=u'')
Opens "Send an IM Message" dialog. :Parameters: Username : str Message target. Text : unicode Message text.
32.07729
31.65089
1.013472
self._Skype._Api.startup(Minimized, Nosplash)
def Start(self, Minimized=False, Nosplash=False)
Starts Skype application. :Parameters: Minimized : bool If True, Skype is started minimized in system tray. Nosplash : bool If True, no splash screen is displayed upon startup.
18.91917
16.122564
1.173459
if not self.thread_started: super(SkypeAPI, self).start() self.thread_started = True
def start(self)
Start the thread associated with this API object. Ensure that the call is made no more than once, to avoid raising a RuntimeError.
6.193736
4.431683
1.397604
# enable X11 multithreading x11.XInitThreads() if gtk: from gtk.gdk import threads_init threads_init()
def threads_init(gtk=True)
Enables multithreading support in Xlib and PyGTK. See the module docstring for more info. :Parameters: gtk : bool May be set to False to skip the PyGTK module.
5.223462
6.478714
0.80625
skype_inst = x11.XInternAtom(self.disp, '_SKYPE_INSTANCE', True) if not skype_inst: return type_ret = Atom() format_ret = c_int() nitems_ret = c_ulong() bytes_after_ret = c_ulong() winp = pointer(Window()) fail = x11.XGetWindowProperty(self.disp, self.win_root, skype_inst, 0, 1, False, 33, byref(type_ret), byref(format_ret), byref(nitems_ret), byref(bytes_after_ret), byref(winp)) if not fail and format_ret.value == 32 and nitems_ret.value == 1: return winp.contents.value
def get_skype(self)
Returns Skype window ID or None if Skype not running.
4.216063
3.897184
1.081823
#self._Alter('JOIN_CONFERENCE', Id) reply = self._Owner._DoCommand('SET CALL %s JOIN_CONFERENCE %s' % (self.Id, Id), 'CALL %s CONF_ID' % self.Id) return Conference(self._Owner, reply.split()[-1])
def Join(self, Id)
Joins with another call to form a conference. :Parameters: Id : int Call Id of the other call to join to the conference. :return: Conference object. :rtype: `Conference`
10.840034
7.253339
1.494489
from warnings import warn warn('Settings.Avatar: Use Settings.LoadAvatarFromFile instead.', DeprecationWarning, stacklevel=2) if Set is None: raise TypeError('Argument \'Set\' is mandatory!') self.LoadAvatarFromFile(Set, Id)
def Avatar(self, Id=1, Set=None)
Sets user avatar picture from file. :Parameters: Id : int Optional avatar Id. Set : str New avatar file name. :deprecated: Use `LoadAvatarFromFile` instead.
5.980585
4.440217
1.346913
s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('SET %s' % s, s)
def LoadAvatarFromFile(self, Filename, AvatarId=1)
Loads user avatar picture from file. :Parameters: Filename : str Name of the avatar file. AvatarId : int Optional avatar Id.
12.102699
16.102324
0.751612
if Set is None: return unicode2path(self._Skype._Property('RINGTONE', Id, '')) self._Skype._Property('RINGTONE', Id, '', path2unicode(Set))
def RingTone(self, Id=1, Set=None)
Returns/sets a ringtone. :Parameters: Id : int Ringtone Id Set : str Path to new ringtone or None if the current path should be queried. :return: Current path if Set=None, None otherwise. :rtype: str or None
9.004467
8.605948
1.046307
if Set is None: return (self._Skype._Property('RINGTONE', Id, 'STATUS') == 'ON') self._Skype._Property('RINGTONE', Id, 'STATUS', cndexp(Set, 'ON', 'OFF'))
def RingToneStatus(self, Id=1, Set=None)
Enables/disables a ringtone. :Parameters: Id : int Ringtone Id Set : bool True/False if the ringtone should be enabled/disabled or None if the current status should be queried. :return: Current status if Set=None, None otherwise. :rtype: bool
6.847951
7.789936
0.879077
s = 'AVATAR %s %s' % (AvatarId, path2unicode(Filename)) self._Skype._DoCommand('GET %s' % s, s)
def SaveAvatarToFile(self, Filename, AvatarId=1)
Saves user avatar picture to file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id
12.205852
16.592743
0.735614
s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename)) self._Owner._DoCommand('GET %s' % s, s)
def SaveAvatarToFile(self, Filename, AvatarId=1)
Saves user avatar to a file. :Parameters: Filename : str Destination path. AvatarId : int Avatar Id.
11.631956
14.393993
0.808112
self._Property('BUDDYSTATUS', '%d %s' % (budPendingAuthorization, tounicode(Text)), Cache=False)
def SetBuddyStatusPendingAuthorization(self, Text=u'')
Sets the BuddyStaus property to `enums.budPendingAuthorization` additionally specifying the authorization text. :Parameters: Text : unicode The authorization text. :see: `BuddyStatus`
25.929173
20.117542
1.288884
stream.Write(base64.encodestring(pickle.dumps(obj)))
def StreamWrite(stream, *obj)
Writes Python object to Skype application stream.
5.423642
6.294531
0.861643
try: self.sock.shutdown(socket.SHUT_RDWR) self.sock.close() except socket.error: pass
def close(self)
Closes the tunnel.
2.949215
2.320034
1.271195
# we should only proceed if we are in TCP mode if stype != socket.SOCK_STREAM: return # handle all streams for stream in streams: # read object from the stream obj = StreamRead(stream) if obj: if obj[0] == cmdData: # data were received, reroute it to the tunnel based on the tunnel ID try: TCPTunnel.threads[obj[1]].send(obj[2]) except KeyError: pass elif obj[0] == cmdConnect: # a connection request received, connect the socket n = obj[1] sock = socket.socket(type=stype) try: sock.connect(addr) # start the tunnel thread TCPTunnel(sock, stream, n).start() except socket.error, e: # connection failed, send an error report back through the stream print 'error (%s): %s' % (n, e) StreamWrite(stream, cmdError, n, tuple(e)) StreamWrite(stream, cmdDisconnect, n) elif obj[0] == cmdDisconnect: # an disconnection request received, close the tunnel try: TCPTunnel.threads[obj[1]].close() except KeyError: pass elif obj[0] == cmdError: # connection failed on the other side, display the error print 'error (%s): %s' % obj[1:2]
def ApplicationReceiving(self, app, streams)
Called when the list of streams with data ready to be read changes.
4.155594
4.17115
0.996271
# we should only proceed if we are in UDP mode if stype != socket.SOCK_DGRAM: return # decode the data data = base64.decodestring(text) # open an UDP socket sock = socket.socket(type=stype) # send the data try: sock.sendto(data, addr) except socket.error, e: print 'error: %s' % e
def ApplicationDatagram(self, app, stream, text)
Called when a datagram is received over a stream.
4.21811
4.383206
0.962334
spl = s.split(d, n) if len(spl) == n: spl.append(s[:0]) if len(spl) != n + 1: raise ValueError('chop: Could not chop %d words from \'%s\'' % (n, s)) return spl
def chop(s, n=1, d=None)
Chops initial words from a string and returns a list of them and the rest of the string. The returned list is guaranteed to be n+1 long. If too little words are found in the string, a ValueError exception is raised. :Parameters: s : str or unicode String to chop from. n : int Number of words to chop. d : str or unicode Optional delimiter. Any white-char by default. :return: A list of n first words from the string followed by the rest of the string (``[w1, w2, ..., wn, rest_of_string]``). :rtype: list of: str or unicode
4.007934
3.484749
1.150135
d = {} while s: t, s = chop(s, 1, '=') if s.startswith('"'): # XXX: This function is used to parse strings from Skype. The question is, # how does Skype escape the double-quotes. The code below implements the # VisualBasic technique ("" -> "). i = 0 while True: i = s.find('"', i+1) try: if s[i+1] != '"': break else: i += 1 except IndexError: break if i > 0: d[t] = s[1:i].replace('""', '"') if s[i+1:i+3] == ', ': i += 2 s = s[i+1:] else: d[t] = s break else: i = s.find(', ') if i >= 0: d[t] = s[:i] s = s[i+2:] else: d[t] = s break return d
def args2dict(s)
Converts a string or comma-separated 'ARG="a value"' or 'ARG=value2' strings into a dictionary. :Parameters: s : str or unicode Input string. :return: ``{'ARG': 'value'}`` dictionary. :rtype: dict
3.499894
3.63662
0.962403
if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) args = map(repr, Args) + ['%s=%s' % (key, repr(value)) for key, value in KwArgs.items()] self.__Logger.debug('calling %s: %s', Event, ', '.join(args)) # Get a list of handlers for this event. try: handlers = [self._DefaultEventHandlers[Event]] except KeyError: handlers = [] try: handlers.append(getattr(self._EventHandlerObject, Event)) except AttributeError: pass handlers.extend(self._EventHandlers[Event]) # Proceed only if there are handlers. if handlers: # Get the last thread for this event. after = self._EventThreads.get(Event, None) # Create a new thread, pass the last one to it so it can wait until it is finished. thread = EventSchedulerThread(Event, after, handlers, Args, KwArgs) # Store a weak reference to the new thread for this event. self._EventThreads[Event] = thread # Start the thread. thread.start()
def _CallEventHandler(self, Event, *Args, **KwArgs)
Calls all event handlers defined for given Event, additional parameters will be passed unchanged to event handlers, all event handlers are fired on separate threads. :Parameters: Event : str Name of the event. Args Positional arguments for the event handlers. KwArgs Keyword arguments for the event handlers.
3.302356
3.238678
1.019662
if not callable(Target): raise TypeError('%s is not callable' % repr(Target)) if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) if Target in self._EventHandlers[Event]: return False self._EventHandlers[Event].append(Target) self.__Logger.info('registered %s: %s', Event, repr(Target)) return True
def RegisterEventHandler(self, Event, Target)
Registers any callable as an event handler. :Parameters: Event : str Name of the event. For event names, see the respective ``...Events`` class. Target : callable Callable to register as the event handler. :return: True is callable was successfully registered, False if it was already registered. :rtype: bool :see: `UnregisterEventHandler`
2.729875
2.648149
1.030861
if not callable(Target): raise TypeError('%s is not callable' % repr(Target)) if Event not in self._EventHandlers: raise ValueError('%s is not a valid %s event name' % (Event, self.__class__.__name__)) if Target in self._EventHandlers[Event]: self._EventHandlers[Event].remove(Target) self.__Logger.info('unregistered %s: %s', Event, repr(Target)) return True return False
def UnregisterEventHandler(self, Event, Target)
Unregisters an event handler previously registered with `RegisterEventHandler`. :Parameters: Event : str Name of the event. For event names, see the respective ``...Events`` class. Target : callable Callable to unregister. :return: True if callable was successfully unregistered, False if it wasn't registered first. :rtype: bool :see: `RegisterEventHandler`
2.603627
2.518949
1.033617
self._EventHandlerObject = Object self.__Logger.info('set object: %s', repr(Object))
def _SetEventHandlerObject(self, Object)
Registers an object as events handler, object should contain methods with names corresponding to event names, only one object may be registered at a time. :Parameters: Object Object to register. May be None in which case the currently registered object will be unregistered.
8.087513
17.106846
0.472765
def make_event(event): return property(lambda self: self._GetDefaultEventHandler(event), lambda self, Value: self._SetDefaultEventHandler(event, Value)) for event in dir(Class): if not event.startswith('_'): setattr(cls, 'On%s' % event, make_event(event)) cls._EventNames.append(event)
def _AddEvents(cls, Class)
Adds events based on the attributes of the given ``...Events`` class. :Parameters: Class : class An `...Events` class whose methods define events that may occur in the instances of the current class.
3.658057
4.112279
0.889545
''' --- Prajna bug fix --- Original code: return self._Owner._Alter('CHAT', self.Name, AlterName, Args, 'ALTER CHAT %s %s' % (self.Name, AlterName)) Whereas most of the ALTER commands echo the command in the reply, the ALTER CHAT commands strip the <chat_id> from the reply, so we need to do the same for the expected reply ''' return self._Owner._Alter('CHAT', self.Name, AlterName, Args, 'ALTER CHAT %s' % (AlterName))
def _Alter(self, AlterName, Args=None)
--- Prajna bug fix --- Original code: return self._Owner._Alter('CHAT', self.Name, AlterName, Args, 'ALTER CHAT %s %s' % (self.Name, AlterName)) Whereas most of the ALTER commands echo the command in the reply, the ALTER CHAT commands strip the <chat_id> from the reply, so we need to do the same for the expected reply
8.381949
1.535296
5.459501
self._Alter('ADDMEMBERS', ', '.join([x.Handle for x in Members]))
def AddMembers(self, *Members)
Adds new members to the chat. :Parameters: Members : `User` One or more users to add.
19.424555
17.842346
1.088677
return ChatMessage(self._Owner, chop(self._Owner._DoCommand('CHATMESSAGE %s %s' % (self.Name, tounicode(MessageText))), 2)[1])
def SendMessage(self, MessageText)
Sends a chat message. :Parameters: MessageText : unicode Message text :return: Message object :rtype: `ChatMessage`
18.99052
15.939077
1.191444
if ' ' in Password: raise ValueError('Password mut be one word') self._Alter('SETPASSWORD', '%s %s' % (tounicode(Password), tounicode(Hint)))
def SetPassword(self, Password, Hint='')
Sets the chat password. :Parameters: Password : unicode Password Hint : unicode Password hint
10.801139
11.638659
0.92804
t = self._Owner._Alter('CHATMEMBER', self.Id, 'CANSETROLETO', Role, 'ALTER CHATMEMBER CANSETROLETO') return (chop(t, 1)[-1] == 'TRUE')
def CanSetRoleTo(self, Role)
Checks if the new role can be applied to the member. :Parameters: Role : `enums`.chatMemberRole* New chat member role. :return: True if the new role can be applied, False otherwise. :rtype: bool
16.245695
16.472498
0.986231
self._Skype = Skype self._Skype.RegisterEventHandler('CallStatus', self._CallStatus) del self._Channels[:]
def Connect(self, Skype)
Connects this call channel manager instance to Skype. This is the first thing you should do after creating this object. :Parameters: Skype : `Skype` The Skype object. :see: `Disconnect`
7.728273
8.108068
0.953158
if ApplicationName is not None: self.Name = tounicode(ApplicationName) self._App = self._Skype.Application(self.Name) self._Skype.RegisterEventHandler('ApplicationStreams', self._ApplicationStreams) self._Skype.RegisterEventHandler('ApplicationReceiving', self._ApplicationReceiving) self._Skype.RegisterEventHandler('ApplicationDatagram', self._ApplicationDatagram) self._App.Create() self._CallEventHandler('Created', self)
def CreateApplication(self, ApplicationName=None)
Creates an APP2APP application context. The application is automatically created using `application.Application.Create` method. :Parameters: ApplicationName : unicode Application name. Initial name, when the manager is created, is ``u'CallChannelManager'``.
4.109419
4.671372
0.879703
if self.Type == cctReliable: self.Stream.Write(Text) elif self.Type == cctDatagram: self.Stream.SendDatagram(Text) else: raise SkypeError(0, 'Cannot send using %s channel type' & repr(self.Type))
def SendTextMessage(self, Text)
Sends a text message over channel. :Parameters: Text : unicode Text to send.
7.164337
7.327567
0.977724
conv = {'UNKNOWN': enums.apiAttachUnknown, 'SUCCESS': enums.apiAttachSuccess, 'PENDING_AUTHORIZATION': enums.apiAttachPendingAuthorization, 'REFUSED': enums.apiAttachRefused, 'NOT_AVAILABLE': enums.apiAttachNotAvailable, 'AVAILABLE': enums.apiAttachAvailable} try: return self._TextTo('api', conv[Text.upper()]) except KeyError: raise ValueError('Bad text')
def TextToAttachmentStatus(self, Text)
Returns attachment status code. :Parameters: Text : unicode Text, one of 'UNKNOWN', 'SUCCESS', 'PENDING_AUTHORIZATION', 'REFUSED', 'NOT_AVAILABLE', 'AVAILABLE'. :return: Attachment status. :rtype: `enums`.apiAttach*
4.819287
2.702849
1.78304