code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self._sampleName:
sampleName = self._sampleName
elif self._sampleNameRegex:
match = self._sampleNameRegex.search(filename)
if match:
sampleName = match.group(1)
else:
sampleName = filename
else:
... | def addFile(self, filename, fp) | Read and record protein information for a sample.
@param filename: A C{str} file name.
@param fp: An open file pointer to read the file's data from.
@raise ValueError: If information for a pathogen/protein/sample
combination is given more than once. | 3.004531 | 2.870219 | 1.046795 |
for pathogenName, samples in self.pathogenNames.items():
for sampleName in samples:
self.pathogenSampleFiles.add(pathogenName, sampleName) | def _computeUniqueReadCounts(self) | Add all pathogen / sample combinations to self.pathogenSampleFiles.
This will make all de-duplicated (by id) FASTA/FASTQ files and store
the number of de-duplicated reads into C{self.pathogenNames}. | 6.662645 | 3.209373 | 2.075996 |
# Note that the string representation contains much less
# information than the HTML summary. E.g., it does not contain the
# unique (de-duplicated, by id) read count, since that is only computed
# when we are making combined FASTA files of reads matching a
# pathogen.
... | def toStr(self) | Produce a string representation of the pathogen summary.
@return: A C{str} suitable for printing. | 3.993891 | 3.852545 | 1.036689 |
readCounts = []
for i, sampleName in enumerate(sampleNames):
try:
readCount = self.pathogenNames[pathogenName][sampleName][
'uniqueReadCount']
except KeyError:
readCount = 0
readCounts.append(readCount)
... | def _pathogenSamplePlot(self, pathogenName, sampleNames, ax) | Make an image of a graph giving pathogen read count (Y axis) versus
sample id (X axis).
@param pathogenName: A C{str} pathogen name.
@param sampleNames: A sorted C{list} of sample names.
@param ax: A matplotlib C{axes} instance. | 2.874109 | 2.921542 | 0.983764 |
import matplotlib
matplotlib.use('PDF')
import matplotlib.pyplot as plt
self._computeUniqueReadCounts()
pathogenNames = sorted(self.pathogenNames)
sampleNames = sorted(self.sampleNames)
cols = 5
rows = int(len(pathogenNames) / cols) + (
... | def pathogenPanel(self, filename) | Make a panel of images, with each image being a graph giving pathogen
de-duplicated (by id) read count (Y axis) versus sample id (X axis).
@param filename: A C{str} file name to write the image to. | 3.2147 | 3.130174 | 1.027004 |
args = {}
for allowed_int_arg in allowed_int_args:
int_value = request_args.get(allowed_int_arg, default=None, type=None)
if int_value:
args[allowed_int_arg] = int(int_value)
for allowed_str_arg in allowed_str_args:
str_value = request_args.get(allowed_str_arg, def... | def get_args(request_args, allowed_int_args=[], allowed_str_args=[]) | Check allowed argument names and return is as dictionary | 1.540102 | 1.511564 | 1.018879 |
allowed_str_args = ['identifier', 'ref_id', 'ref_type', 'name', 'acronym', 'description']
args = get_args(
request_args=request.args,
allowed_str_args=allowed_str_args
)
return jsonify(query.disease(**args)) | def query_disease() | Returns list of diseases by query parameters
---
tags:
- Query functions
parameters:
- name: identifier
in: query
type: string
required: false
description: Disease identifier
default: DI-03832
- name: ref_id
in: query
type: strin... | 4.859251 | 4.240655 | 1.145873 |
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_full_name(**args)) | def query_alternative_full_name() | Returns list of alternative full name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative full name
default: 'Alzheimer disease amyloid protein'
- name: en... | 6.111324 | 5.567298 | 1.097718 |
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.alternative_short_name(**args)) | def query_alternative_short_name() | Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: entry_name
in: query
... | 6.172084 | 5.507123 | 1.120746 |
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.other_gene_name(**args)) | def query_other_gene_name() | Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Alternative short name
default: CVAP
- name: name
in: query
... | 5.945556 | 5.810113 | 1.023312 |
args = get_args(
request_args=request.args,
allowed_str_args=['accession', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.accession(**args)) | def query_accession() | Returns list of accession numbers by query query parameters
---
tags:
- Query functions
parameters:
- name: accession
in: query
type: string
required: false
description: UniProt accession number
default: P05067
- name: entry_name
in: que... | 6.26806 | 5.808343 | 1.079148 |
args = get_args(
request_args=request.args,
allowed_str_args=['first', 'last', 'volume', 'name', 'date', 'title', 'entry_name'],
allowed_int_args=['pmid', 'limit']
)
return jsonify(query.pmid(**args)) | def query_pmid() | Returns list of PubMed identifier by query parameters
---
tags:
- Query functions
parameters:
- name: pmid
in: query
type: string
required: false
description: PubMed identifier
default: 20697050
- name: entry_name
in: query
type:... | 6.769838 | 5.054254 | 1.339434 |
args = get_args(
request_args=request.args,
allowed_str_args=['entry_name'],
allowed_int_args=['taxid', 'limit']
)
return jsonify(query.organism_host(**args)) | def query_organism_host() | Returns list of host organism by query parameters
---
tags:
- Query functions
parameters:
- name: taxid
in: query
type: integer
required: false
description: NCBI taxonomy identifier
default: 9606
- name: entry_name
in: query
type... | 6.140364 | 6.209797 | 0.988819 |
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.db_reference(**args)) | def query_db_reference() | Returns list of cross references by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Reference type
default: EMBL
- name: identifier
in: query
type: string... | 7.208964 | 5.759315 | 1.251705 |
args = get_args(
request_args=request.args,
allowed_str_args=['type_', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.feature(**args)) | def query_feature() | Returns list of sequence feature by query parameters
---
tags:
- Query functions
parameters:
- name: type_
in: query
type: string
required: false
description: Feature type
default: 'splice variant'
- name: identifier
in: query
typ... | 8.19898 | 6.897251 | 1.188732 |
args = get_args(
request_args=request.args,
allowed_str_args=['text', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.function(**args)) | def query_function() | Returns list of functions by query parameters
---
tags:
- Query functions
parameters:
- name: text
in: query
type: string
required: false
description: Text describing protein function
default: '%axonogenesis%'
- name: entry_name
in: query... | 8.140471 | 7.839896 | 1.038339 |
args = get_args(
request_args=request.args,
allowed_str_args=['name', 'identifier', 'entry_name'],
allowed_int_args=['limit']
)
print(args)
return jsonify(query.keyword(**args)) | def query_keyword() | Returns list of keywords linked to entries by query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Disease identifier
default: 'Ubl conjugation'
- name: identifier
in: q... | 6.90847 | 6.747236 | 1.023896 |
args = get_args(
request_args=request.args,
allowed_str_args=['ec_number', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.ec_number(**args)) | def query_ec_number() | Returns list of Enzyme Commission Numbers (EC numbers) by query parameters
---
tags:
- Query functions
parameters:
- name: ec_number
in: query
type: string
required: false
description: Enzyme Commission Number
default: '1.1.1.1'
- name: entry_nam... | 5.772833 | 6.082358 | 0.949111 |
args = get_args(
request_args=request.args,
allowed_str_args=['location', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.subcellular_location(**args)) | def query_subcellular_location() | Returns list of subcellular locations by query parameters
---
tags:
- Query functions
parameters:
- name: location
in: query
type: string
required: false
description: Subcellular location
default: 'Clathrin-coated pit'
- name: entry_name
... | 6.079673 | 6.084164 | 0.999262 |
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_specificity(**args)) | def query_tissue_specificity() | Returns list of tissue specificity by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment to tissue specificity
default: '%APP695%'
- name: entry_name
in: q... | 6.704142 | 5.994501 | 1.118382 |
args = get_args(
request_args=request.args,
allowed_str_args=['tissue', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.tissue_in_reference(**args)) | def query_tissue_in_reference() | Returns list of tissues linked to references by query parameters
---
tags:
- Query functions
parameters:
- name: tissue
in: query
type: string
required: false
description: Tissue
default: brain
- name: entry_name
in: query
type: s... | 5.983441 | 5.96333 | 1.003373 |
args = get_args(
request_args=request.args,
allowed_str_args=['comment', 'entry_name'],
allowed_int_args=['limit']
)
return jsonify(query.disease_comment(**args)) | def query_disease_comment() | Returns list of diseases comments by query parameters
---
tags:
- Query functions
parameters:
- name: comment
in: query
type: string
required: false
description: Comment on disease linked to UniProt entry
default: '%mutations%'
- name: entry_nam... | 6.120545 | 5.817269 | 1.052134 |
upperCase = self._upperCase
for _file in self._files:
with asHandle(_file) as fp:
records = SeqIO.parse(fp, 'fasta')
while True:
try:
record = next(records)
except StopIteration:
... | def iter(self) | Iterate over the sequences in self.file_, yielding each as an
instance of the desired read class.
@raise ValueError: If the input file has an odd number of records or
if any sequence has a different length than its predicted
secondary structure. | 3.063829 | 2.596531 | 1.17997 |
def wrapped(self, node):
func(self, *args, **kwargs)
return wrapped | def npartial(func, *args, **kwargs) | Returns a partial node visitor function | 8.014094 | 8.117689 | 0.987238 |
if seq is None:
return None
return "".join(aa3_to_aa1_lut[aa3]
for aa3 in [seq[i:i + 3] for i in range(0, len(seq), 3)]) | def aa3_to_aa1(seq) | convert string of 3-letter amino acids to 1-letter amino acids
>>> aa3_to_aa1("CysAlaThrSerAlaArgGluLeuAlaMetGlu")
'CATSARELAME'
>>> aa3_to_aa1(None) | 2.736282 | 3.558973 | 0.76884 |
elided_sequence_len = flank + flank + len(elision)
if len(s) <= elided_sequence_len:
return s
return s[:flank] + elision + s[-flank:] | def elide_sequence(s, flank=5, elision="...") | trim a sequence to include the left and right flanking sequences of
size `flank`, with the intervening sequence elided by `elision`.
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
'ABCDE...VWXYZ'
>>> elide_sequence("ABCDEFGHIJKLMNOPQRSTUVWXYZ", flank=3)
'ABC...XYZ'
>>> elide_sequence("ABCDE... | 2.776441 | 3.367282 | 0.824535 |
nseq = re.sub(r"[\s\*]", "", seq).upper()
m = re.search("[^A-Z]", nseq)
if m:
_logger.debug("Original sequence: " + seq)
_logger.debug("Normalized sequence: " + nseq)
_logger.debug("First non-[A-Z] at {}".format(m.start()))
raise RuntimeError("Normalized sequence contai... | def normalize_sequence(seq) | return normalized representation of sequence for hashing
This really means ensuring that the sequence is represented as a
binary blob and removing whitespace and asterisks and uppercasing.
>>> normalize_sequence("ACGT")
'ACGT'
>>> normalize_sequence(" A C G T * ")
'ACGT'
>>> normalize_s... | 3.706443 | 3.289549 | 1.126733 |
if seq is None:
return None
if len(seq) == 0:
return ""
if full_codons and len(seq) % 3 != 0:
raise ValueError("Sequence length must be a multiple of three")
seq = replace_u_to_t(seq)
seq = seq.upper()
protein_seq = list()
for i in range(0, len(seq) - len(seq... | def translate_cds(seq, full_codons=True, ter_symbol="*") | translate a DNA or RNA sequence into a single-letter amino acid sequence
using the standard translation table
If full_codons is True, a sequence whose length isn't a multiple of three
generates a ValueError; else an 'X' will be added as the last amino acid.
This matches biopython's behaviour when paddi... | 2.729416 | 2.56002 | 1.06617 |
url = self._make_full_url(url)
self._log.debug('Performing %s request to %s', method, url)
return self._request(url, method=method, headers=headers, data=data,
result_callback=result_callback) | def request(self, url, *,
method='GET', headers=None, data=None, result_callback=None) | Perform request.
:param str url: request URL.
:param str method: request method.
:param dict headers: request headers.
:param object data: request data.
:param object -> object result_callback: result callback.
:rtype: dict
:raise: APIError | 2.611217 | 3.137863 | 0.832164 |
return SLASH.join([self._api_base_url, url.lstrip(SLASH)]) | def _make_full_url(self, url) | Given base and relative URL, construct the full URL.
:param str url: relative URL.
:return: full URL.
:rtype: str | 9.02305 | 12.171006 | 0.741356 |
'''
Merge two settings dictionaries, recording how many changes were needed.
'''
changes = 0
for key, value in new.items():
if key not in current:
if hasattr(global_settings, key):
current[key] = getattr(global_settings, key)
LOGGER.debug("Set %r ... | def merge_dictionaries(current, new, only_defaults=False, template_special_case=False) | Merge two settings dictionaries, recording how many changes were needed. | 2.056698 | 1.936129 | 1.062273 |
'''
Given a settings object, run automatic configuration of all
the apps in INSTALLED_APPS.
'''
changes = 1
iterations = 0
while changes:
changes = 0
app_names = ['django_autoconfig'] + list(settings['INSTALLED_APPS'])
if environment_settings:
app_names.a... | def configure_settings(settings, environment_settings=True) | Given a settings object, run automatic configuration of all
the apps in INSTALLED_APPS. | 3.771801 | 3.330995 | 1.132335 |
'''
Configure urls from a list of apps.
'''
prefixes = prefixes or {}
urlpatterns = patterns('')
if index_view:
from django.views.generic.base import RedirectView
urlpatterns += patterns('',
url(r'^$', RedirectView.as_view(pattern_name=index_view, permanent=False)),
... | def configure_urls(apps, index_view=None, prefixes=None) | Configure urls from a list of apps. | 2.706653 | 2.58639 | 1.046499 |
if isinstance(data, ndarray):
data = fromarray(data)
if not isinstance(data, Images):
data = fromarray(asarray(data))
if len(data.shape) not in set([3, 4]):
raise Exception('Number of image dimensions %s must be 2 or 3' % (len(data.shape)))
return data | def check_images(data) | Check and reformat input images if needed | 4.142263 | 3.794682 | 1.091597 |
if not images.shape[1:] == reference.shape:
raise Exception('Image shape %s and reference shape %s must match'
% (images.shape[1:], reference.shape))
return reference | def check_reference(images, reference) | Ensure the reference matches image dimensions | 3.494411 | 3.136291 | 1.114186 |
assert isinstance(data, dict)
if 'ensembl_id' not in data:
raise ValueError('An "ensembl_id" key is missing!')
# make a copy
data = dict(data)
for attr in ['name', 'chromosome', 'position', 'length',
'type', 'source']:
... | def from_dict(cls, data: Dict[str, Union[str, int]]) | Generate an `ExpGene` object from a dictionary.
Parameters
----------
data : dict
A dictionary with keys corresponding to attribute names.
Attributes with missing keys will be assigned `None`.
Returns
-------
`ExpGene`
The gene. | 4.147451 | 4.199672 | 0.987565 |
assert start <= end
self._intervals.append((start, end)) | def add(self, start, end) | Add the start and end offsets of a matching read.
@param start: The C{int} start offset of the read match in the subject.
@param end: The C{int} end offset of the read match in the subject.
This is Python-style: the end offset is not included in the match. | 6.819018 | 12.867745 | 0.529931 |
intervals = sorted(self._intervals)
def nextFull():
start, stop = intervals.pop(0)
while intervals:
if intervals[0][0] <= stop:
_, thisStop = intervals.pop(0)
if thisStop > stop:
stop = this... | def walk(self) | Get the non-overlapping read intervals that match the subject.
@return: A generator that produces (TYPE, (START, END)) tuples, where
where TYPE is either self.EMPTY or self.FULL and (START, STOP) is
the interval. The endpoint (STOP) of the interval is not considered
to be in... | 3.324012 | 2.956023 | 1.124488 |
if self._targetLength == 0:
return 0.0
coverage = 0
for (intervalType, (start, end)) in self.walk():
if intervalType == self.FULL:
# Adjust start and end to ignore areas where the read falls
# outside the target.
c... | def coverage(self) | Get the fraction of a subject is matched by its set of reads.
@return: The C{float} fraction of a subject matched by its reads. | 6.326952 | 6.356799 | 0.995305 |
coverageCounts = Counter()
for start, end in self._intervals:
coverageCounts.update(range(max(0, start),
min(self._targetLength, end)))
return coverageCounts | def coverageCounts(self) | For each location in the subject, return a count of how many times that
location is covered by a read.
@return: a C{Counter} where the keys are the C{int} locations on the
subject and the value is the number of times the location is
covered by a read. | 4.967186 | 5.332962 | 0.931412 |
reduction = 0
for (thisOffset, thisReduction) in self._adjustments:
if offset >= thisOffset:
reduction += thisReduction
else:
break
return reduction | def _reductionForOffset(self, offset) | Calculate the total reduction for a given X axis offset.
@param offset: The C{int} offset.
@return: The total C{float} reduction that should be made for this
offset. | 4.150812 | 4.375554 | 0.948637 |
reduction = self._reductionForOffset(
min(hsp.readStartInSubject, hsp.subjectStart))
hsp.readEndInSubject = hsp.readEndInSubject - reduction
hsp.readStartInSubject = hsp.readStartInSubject - reduction
hsp.subjectEnd = hsp.subjectEnd - reduction
hsp.subjectSt... | def adjustHSP(self, hsp) | Adjust the read and subject start and end offsets in an HSP.
@param hsp: a L{dark.hsp.HSP} or L{dark.hsp.LSP} instance. | 3.570033 | 3.142956 | 1.135884 |
if i >= self.n:
raise ValueError('Index %d out of bounds ' % i +
'for database with %d gene sets.' % self.n)
return self._gene_sets[self._gene_set_ids[i]] | def get_by_index(self, i) | Look up a gene set by its index.
Parameters
----------
i: int
The index of the gene set.
Returns
-------
GeneSet
The gene set.
Raises
------
ValueError
If the given index is out of bounds. | 4.953421 | 4.688397 | 1.056528 |
gene_sets = []
n = 0
with open(path, 'rb') as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
for l in reader:
n += 1
gs = GeneSet.from_list(l)
gene_sets.append(gs)
logger.debug('Read %d ... | def read_tsv(cls, path, encoding='utf-8') | Read a gene set database from a tab-delimited text file.
Parameters
----------
path: str
The path name of the the file.
encoding: str
The encoding of the text file.
Returns
-------
None | 2.650302 | 2.809511 | 0.943332 |
with open(path, 'wb') as ofh:
writer = csv.writer(
ofh, dialect='excel-tab',
quoting=csv.QUOTE_NONE, lineterminator=os.linesep
)
for gs in self._gene_sets.values():
writer.writerow(gs.to_list()) | def write_tsv(self, path) | Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None | 2.765686 | 3.148452 | 0.878427 |
# callback function for xmltodict.parse()
total_gs[0] += 1
data = pth[1][1]
spec = data['ORGANISM']
# filter by species
if species is not None and spec != species:
species_excl[0] += 1
return True
id_ ... | def read_msigdb_xml(cls, path, entrez2gene, species=None): # pragma: no cover
# note: is XML file really encoded in UTF-8?
assert isinstance(path, (str, _oldstr))
assert isinstance(entrez2gene, (dict, OrderedDict))
assert species is None or isinstance(species, (str, _oldstr))... | Read the complete MSigDB database from an XML file.
The XML file can be downloaded from here:
http://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/5.0/msigdb_v5.0.xml
Parameters
----------
path: str
The path name of the XML fil... | 2.544271 | 2.754619 | 0.923638 |
excludedQualifiers = set((
'codon_start', 'db_xref', 'protein_id', 'region_name',
'ribosomal_slippage', 'rpt_type', 'translation', 'transl_except',
'transl_table')
)
maxValueLength = 30
result = []
if self.feature.qualifiers:
... | def legendLabel(self) | Provide a textual description of the feature and its qualifiers to be
used as a label in a plot legend.
@return: A C{str} description of the feature. | 3.079912 | 3.083921 | 0.9987 |
offsetAdjuster = offsetAdjuster or (lambda x: x)
fig.set_title('Target sequence features', fontsize=self.TITLE_FONTSIZE)
fig.set_yticks([])
features = FeatureList(title, self.DATABASE, self.WANTED_TYPES,
sequenceFetcher=sequenceFetcher)
... | def add(self, fig, title, minX, maxX, offsetAdjuster=None,
sequenceFetcher=None) | Find the features for a sequence title. If there aren't too many, add
the features to C{fig}. Return information about the features, as
described below.
@param fig: A matplotlib figure.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011... | 2.764951 | 2.57799 | 1.072522 |
labels = []
for index, feature in enumerate(features):
fig.plot([offsetAdjuster(feature.start),
offsetAdjuster(feature.end)],
[index * -0.2, index * -0.2], color=feature.color,
linewidth=2)
labels.append(fea... | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster) | Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
... | 3.197099 | 3.234694 | 0.988378 |
frame = None
labels = []
for feature in features:
start = offsetAdjuster(feature.start)
end = offsetAdjuster(feature.end)
if feature.subfeature:
subfeatureFrame = start % 3
if subfeatureFrame == frame:
... | def _displayFeatures(self, fig, features, minX, maxX, offsetAdjuster) | Add the given C{features} to the figure in C{fig}.
@param fig: A matplotlib figure.
@param features: A C{FeatureList} instance.
@param minX: The smallest x coordinate.
@param maxX: The largest x coordinate.
@param offsetAdjuster: a function for adjusting feature X axis offsets
... | 3.561224 | 3.580938 | 0.994495 |
queryset = Article.objects.filter(published=True).order_by('-modified')
if exclude:
if hasattr(exclude, '__iter__'):
queryset = queryset.exclude(pk__in=exclude)
else:
queryset = queryset.exclude(pk=exclude)
return queryset | def recent_articles(limit=10, exclude=None) | Returns list of latest article | 2.044045 | 2.025406 | 1.009203 |
if isinstance(n, collections.Sequence):
for x in n:
for y in _flatten(x):
yield y
else:
yield n | def _flatten(n) | Recursively flatten a mixed sequence of sub-sequences and items | 2.197337 | 2.131282 | 1.030993 |
if hasattr(stream, 'read'):
proxy = PollingStreamAdapter(stream)
elif hasattr(stream, 'recv'):
proxy = PollingSocketStreamAdapter(stream)
else:
raise TypeError('stream must have either read or recv method')
if echo and unicode:
callback = _echo_text
elif echo an... | def wrap(stream, unicode=False, window=1024, echo=False, close_stream=True) | Wrap a stream to implement expect functionality.
This function provides a convenient way to wrap any Python stream (a
file-like object) or socket with an appropriate :class:`Expecter` class for
the stream type. The returned object adds an :func:`Expect.expect` method
to the stream, while passing normal... | 3.213919 | 3.33023 | 0.965074 |
if not isinstance(value, self.match_type):
raise TypeError('Type ' + str(type(value)) + ' does not match '
'expected type ' + str(self.match_type))
else:
return value | def _check_type(self, value) | Checks that *value* matches the type of this *Searcher*.
Checks that *value* matches the type of this *Searcher*, returning the
value if it does and raising a `TypeError` if it does not.
:return: *value* if type of *value* matches type of this *Searcher*.
:raises TypeError: if type of ... | 3.144575 | 3.280253 | 0.958638 |
idx = self._check_type(buf).find(self._bytes)
if idx < 0:
return None
else:
start = idx
end = idx + len(self._bytes)
return SequenceMatch(self, buf[start:end], start, end) | def search(self, buf) | Search the provided buffer for matching bytes.
Search the provided buffer for matching bytes. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no m... | 4.137494 | 3.627665 | 1.140539 |
self._check_type(buf)
normalized = unicodedata.normalize(self.FORM, buf)
idx = normalized.find(self._text)
if idx < 0:
return None
start = idx
end = idx + len(self._text)
return SequenceMatch(self, normalized[start:end], start, end) | def search(self, buf) | Search the provided buffer for matching text.
Search the provided buffer for matching text. If the *match* is found,
returns a :class:`SequenceMatch` object, otherwise returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`SequenceMatch` if matched, None if no mat... | 3.930158 | 3.672586 | 1.070134 |
match = self._regex.search(self._check_type(buf))
if match is not None:
start = match.start()
end = match.end()
return RegexMatch(self, buf[start:end], start, end, match.groups()) | def search(self, buf) | Search the provided buffer for a match to the object's regex.
Search the provided buffer for a match to the object's regex. If the
*match* is found, returns a :class:`RegexMatch` object, otherwise
returns ``None``.
:param buf: Buffer to search for a match.
:return: :class:`Rege... | 3.779504 | 3.295339 | 1.146924 |
self._check_type(buf)
best_match = None
best_index = sys.maxsize
for searcher in self:
match = searcher.search(buf)
if match and match.start < best_index:
best_match = match
best_index = match.start
return best_matc... | def search(self, buf) | Search the provided buffer for a match to any sub-searchers.
Search the provided buffer for a match to any of this collection's
sub-searchers. If a single matching sub-searcher is found, returns that
sub-searcher's *match* object. If multiple matches are found, the match
with the smalle... | 2.994568 | 2.486515 | 1.204323 |
timeout = float(timeout)
end_time = time.time() + timeout
while True:
# Keep reading until data is received or timeout
incoming = self.stream.read(self._max_read)
if incoming:
return incoming
if (end_time - time.time()) < 0... | def poll(self, timeout) | :param float timeout: Timeout in seconds. | 3.866234 | 3.860388 | 1.001514 |
now = time.time()
end_time = now + float(timeout)
prev_timeout = self.stream.gettimeout()
self.stream.settimeout(self._poll_period)
incoming = None
try:
while (end_time - now) >= 0:
try:
incoming = self.stream.recv(... | def poll(self, timeout) | :param float timeout: Timeout in seconds. A timeout that is less than
the poll_period will still cause a single read that may take up to
poll_period seconds. | 2.959234 | 2.896443 | 1.021678 |
return self.expect(RegexSearcher(pattern, regex_options), timeout) | def expect_regex(self, pattern, timeout=3, regex_options=0) | Wait for a match to the regex in *pattern* to appear on the stream.
Waits for input matching the regex *pattern* for up to *timeout*
seconds. If a match is found, a :class:`RegexMatch` result is returned.
If no match is found within *timeout* seconds, raise an
:class:`ExpectTimeout` exc... | 9.723516 | 19.67679 | 0.494162 |
timeout = float(timeout)
end = time.time() + timeout
match = searcher.search(self._history[self._start:])
while not match:
# poll() will raise ExpectTimeout if time is exceeded
incoming = self._stream_adapter.poll(end - time.time())
self.input... | def expect(self, searcher, timeout=3) | Wait for input matching *searcher*
Waits for input matching *searcher* for up to *timeout* seconds. If
a match is found, the match result is returned (the specific type of
returned result depends on the :class:`Searcher` type). If no match is
found within *timeout* seconds, raise an :cl... | 4.237086 | 4.326995 | 0.979221 |
self._graph = Graph()
# First add all nodes
for key in self.loader.disk_fixtures.keys():
self.graph.add_node(key)
# Then set dependencies
for key, fixture in self.loader.disk_fixtures.items():
for dependency in fixture.dependencies:
... | def init_graph(self) | Initialize graph
Load all nodes and set dependencies.
To avoid errors about missing nodes all nodes get loaded first before
setting the dependencies. | 4.207541 | 3.504092 | 1.200751 |
return [node for node in self.graph.nodes if node[0] == app_label] | def get_app_nodes(self, app_label) | Get all nodes for given app
:param str app_label: app label
:rtype: list | 4.249574 | 4.870838 | 0.872452 |
app_nodes = self.get_app_nodes(app_label=app_label)
nodes = [
node for node in app_nodes if node[1].startswith(fixture_prefix)
]
if len(nodes) > 1:
raise MultipleFixturesFound(
"The following fixtures with prefix '%s' are found in app... | def get_fixture_node(self, app_label, fixture_prefix) | Get all fixtures in given app with given prefix.
:param str app_label: App label
:param str fixture_prefix: first part of the fixture name
:return: list of found fixtures. | 2.350137 | 2.472401 | 0.950549 |
if progress_callback and not callable(progress_callback):
raise Exception('Callback should be callable')
plan = self.get_plan(nodes=nodes)
try:
with transaction.atomic():
self.load_plan(plan=plan, progress_callback=progress_callback)
... | def load_fixtures(self, nodes=None, progress_callback=None, dry_run=False) | Load all fixtures for given nodes.
If no nodes are given all fixtures will be loaded.
:param list nodes: list of nodes to be loaded.
:param callable progress_callback: Callback which will be called while
handling the nodes. | 3.863827 | 4.737261 | 0.815625 |
if nodes:
plan = self.graph.resolve_nodes(nodes)
else:
plan = self.graph.resolve_node()
return plan | def get_plan(self, nodes=None) | Retrieve a plan, e.g. a list of fixtures to be loaded sorted on
dependency.
:param list nodes: list of nodes to be loaded.
:return: | 4.581831 | 5.453723 | 0.840129 |
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right patt... | def getAPOBECFrequencies(dotAlignment, orig, new, pattern) | Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', '... | 2.745481 | 2.568513 | 1.068899 |
allFreqs = {}
for title in blastHits.titles:
allFreqs[title] = {
'C>A': {},
'C>G': {},
'C>T': {},
'T>A': {},
'T>C': {},
'T>G': {},
}
basesPlotted = basePlotter(blastHits, title)
for mutation in allFreqs[... | def getCompleteFreqs(blastHits) | Make a dictionary which collects all mutation frequencies from
all reads.
Calls basePlotter to get dotAlignment, which is passed to
getAPOBECFrequencies with the respective parameter, to collect
the frequencies.
@param blastHits: A L{dark.blast.BlastHits} instance. | 3.754701 | 3.053658 | 1.229575 |
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pat... | def makeFrequencyGraph(allFreqs, title, substitution, pattern,
color='blue', createFigure=True, showFigure=True,
readsAx=False) | For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param title: A C{str}, title of virus of which frequencies should be
plotted.
@param substitution: A C{str}, which substitution should be plotted;
must be one of 'C>A', 'C>G', 'C>T', 'T>A', 'T>... | 2.625517 | 2.48265 | 1.057546 |
titles = sorted(
iter(allFreqs.keys()),
key=lambda title: (allFreqs[title]['bitScoreMax'], title))
origMaxY = 0
cols = 6
rows = len(allFreqs)
figure, ax = plt.subplots(rows, cols, squeeze=False)
substitutions = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G']
colors = ['blue'... | def makeFrequencyPanel(allFreqs, patientName) | For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel | 3.238765 | 3.268483 | 0.990908 |
if not original:
raise ValueError('Empty original string passed.')
if n > len(original):
raise ValueError('Cannot make %d mutations in a string of length %d' %
(n, len(original)))
if len(replacements) != len(set(replacements)):
raise ValueError('Replac... | def mutateString(original, n, replacements='acgt') | Mutate C{original} in C{n} places with chars chosen from C{replacements}.
@param original: The original C{str} to mutate.
@param n: The C{int} number of locations to mutate.
@param replacements: The C{str} of replacement letters.
@return: A new C{str} with C{n} places of C{original} mutated.
@rais... | 2.708857 | 2.752983 | 0.983972 |
fp.write('%s %s\n %s\n\n' % (
'MATCH:' if accept else 'MISS: ', readId,
' | '.join(taxonomy) if taxonomy else 'No taxonomy found.')) | def writeDetails(accept, readId, taxonomy, fp) | Write read and taxonomy details.
@param accept: A C{bool} indicating whether the read was accepted,
according to its taxonomy.
@param readId: The C{str} id of the read.
@taxonomy: A C{list} of taxonomy C{str} levels.
@fp: An open file pointer to write to. | 6.156889 | 6.649193 | 0.92596 |
if docs:
if hasattr(docs, 'items'):
for (idx, doc) in sorted(getattr(docs, 'items')(),
key=lambda x: x[0]):
self.fm.push_back(doc)
else:
for doc in filter(bool, docs):
... | def build(self, docs=None, filename=None) | Build FM-index
Params:
<iterator> | <generator> docs
<str> filename | 3.447725 | 3.0863 | 1.117106 |
all_docids = reduce(add, [list(x.keys()) for x in search_results])
if _or:
return sorted(set(all_docids), key=all_docids.index)
return [docid for docid in set(all_docids) if all_docids.count(docid) > 1] | def _merge_search_result(self, search_results, _or=False) | Merge of filter search results
Params:
<str> | <Sequential> query
<bool> _or
Return:
<list> computed_dids | 2.769205 | 2.979849 | 0.929311 |
if isinstance(query, str):
dids = MapIntInt({})
self.fm.search(query, dids)
dids = dids.asdict()
result = []
for did in sorted(dids.keys()):
doc = self.fm.get_document(did)
if not any(ignore in doc for ignore in... | def search(self, query, _or=False, ignores=[]) | Search word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<list>SEARCH_RESULT(<int> document_id,
<list <int> > counts
<str> doc) | 2.86009 | 2.44918 | 1.167774 |
if isinstance(query, str):
return self.fm.count(query, MapIntInt({}))
else:
search_results = []
for q in query:
dids = MapIntInt({})
self.fm.search(q, dids)
search_results.append(dids.asdict())
merge... | def count(self, query, _or=False) | Count word from FM-index
Params:
<str> | <Sequential> query
<bool> _or
<list <str> > ignores
Return:
<int> counts | 3.83528 | 3.594984 | 1.066842 |
if not isinstance(name, Hashable):
raise TypeError(name)
parents = set(parents or ())
is_stub = False
if name in self._nodes:
if name in self._stubs:
node = Node(name, self._nodes[name].children, parents)
is_stub = True
... | def add(self, name, parents=None) | add a node to the graph.
Raises an exception if the node cannot be added (i.e., if a node
that name already exists, or if it would create a cycle.
NOTE: A node can be added before its parents are added.
name: The name of the node to add to the graph. Name can be any
unique... | 2.768333 | 2.725967 | 1.015542 |
removed = set()
stack = [name]
while stack:
current = stack.pop()
node = self._nodes.pop(current)
if strategy == Strategy.remove:
for child_name in node.children:
child_node = self._nodes[child_name]
... | def remove(self, name, strategy=Strategy.promote) | Remove a node from the graph. Returns the set of nodes that were
removed.
If the node doesn't exist, an exception will be raised.
name: The name of the node to remove.
strategy: (Optional, Strategy.promote) What to do with children
or removed nodes. The options are:
... | 2.05753 | 2.078614 | 0.989856 |
if visited is None:
visited = set()
node = self._nodes.get(name)
if node is None or name not in self._nodes:
return False
stack = list(node.parents)
while stack:
current = stack.pop()
if current == ancestor:
... | def ancestor_of(self, name, ancestor, visited=None) | Check whether a node has another node as an ancestor.
name: The name of the node being checked.
ancestor: The name of the (possible) ancestor node.
visited: (optional, None) If given, a set of nodes that have
already been traversed. NOTE: The set will be updated with
any... | 2.165772 | 2.130553 | 1.016531 |
pruned = set()
stubs = frozenset(self._stubs)
for stub in stubs:
pruned.update(self.remove(stub, strategy=Strategy.remove))
return pruned - stubs | def prune(self) | Remove any tasks that have stubs as ancestors (and the stubs
themselves).
Returns the set of nodes which were removed. | 7.235677 | 6.06862 | 1.19231 |
"Calls render_to_response with a RequestConext"
from django.http import HttpResponse
from django.template import RequestContext
from django.template.loader import render_to_string
if request:
default = context_processors.default(request)
default.update(context)
else:
... | def respond(template, context={}, request=None, **kwargs) | Calls render_to_response with a RequestConext | 3.851101 | 3.210191 | 1.199649 |
"Displays a list of all services and their current status."
service_list = Service.objects.all()
event_list = list(Event.objects\
.filter(Q(status__gt=0) | Q(date_updated__gte=datetime.datetime.now()-datetime.timedelta(days=1)))\
.order_by(... | def index(request) | Displays a list of all services and their current status. | 3.231944 | 3.000948 | 1.076974 |
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
event_list = service.event_set.order_by('-date_created')
return respond('ov... | def service(request, slug) | Displays a list of all services and their current status. | 3.357893 | 2.906763 | 1.1552 |
"Displays a list of all services and their current status."
try:
evt = Event.objects.get(pk=id)
except Event.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
update_list = list(evt.eventupdate_set.order_by('-date_created'))
return respond('overseer/... | def event(request, id) | Displays a list of all services and their current status. | 4.160089 | 3.45178 | 1.205201 |
"Displays a list of all services and their current status."
try:
service = Service.objects.get(slug=slug)
except Service.DoesNotExist:
return HttpResponseRedirect(reverse('overseer:index'))
try:
evt = service.event_set.order_by('-date_created')[0]
except IndexError:... | def last_event(request, slug) | Displays a list of all services and their current status. | 3.600731 | 2.949779 | 1.220678 |
"Shows subscriptions options for a verified subscriber."
try:
subscription = Subscription.objects.get(ident=ident)
except Subscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
if request.POST:
form = UpdateSubscriptionForm(reques... | def update_subscription(request, ident) | Shows subscriptions options for a verified subscriber. | 3.044867 | 2.667679 | 1.141392 |
"Shows subscriptions options for a new subscriber."
if request.POST:
form = NewSubscriptionForm(request.POST)
if form.is_valid():
unverified = form.save()
body = % dict(
name=conf.NAME,
link=urlparse.urljoin(conf.BASE_URL, reverse('o... | def create_subscription(request) | Shows subscriptions options for a new subscriber. | 3.799148 | 3.506907 | 1.083333 |
try:
unverified = UnverifiedSubscription.objects.get(ident=ident)
except UnverifiedSubscription.DoesNotExist:
return respond('overseer/invalid_subscription_token.html', {}, request)
subscription = Subscription.objects.get_or_create(email=unverified.email, defaults={
'i... | def verify_subscription(request, ident) | Verifies an unverified subscription and create or appends
to an existing subscription. | 3.136778 | 3.055718 | 1.026527 |
cred = get_storage_credentials(key)
return storage.Client(project=project, credentials=cred) | def get_client(key, project) | Gets a `Client` object (required by the other functions).
TODO: docstring | 4.730263 | 5.087011 | 0.929871 |
bucket = client.get_bucket(bucket)
files = list(bucket.list_blobs(prefix=prefix))
return files | def get_files(client, bucket, prefix='') | Lists files/objects on a bucket.
TODO: docstring | 3.097728 | 3.380566 | 0.916334 |
bucket = client.get_bucket(bucket)
if (not overwrite) and os.path.isfile(local_path):
raise OSError('File already exists!')
with open(local_path, 'wb') as ofh:
bucket.get_blob(remote_path).download_to_file(ofh) | def download_file(client, bucket, remote_path, local_path, overwrite=False) | Downloads a file from a bucket.
TODO: docstring | 2.323633 | 2.617081 | 0.887872 |
bucket = client.get_bucket(bucket)
bucket.delete_blob(remote_path) | def delete_file(client, bucket, remote_path) | Deletes a file from a bucket.
TODO: docstring | 3.176224 | 3.620831 | 0.877208 |
bucket = client.get_bucket(bucket)
blob = storage.Blob(remote_path, bucket)
if (not overwrite) and blob.exists():
raise Conflict('File/object already exists on the bucket!')
blob.upload_from_filename(local_path) | def upload_file(client, bucket, local_path, remote_path, overwrite=False) | Uploads a file to a bucket.
TODO: docstring | 3.168915 | 3.452517 | 0.917857 |
for readAlignments in self:
for alignment in readAlignments:
for hsp in alignment.hsps:
yield hsp | def hsps(self) | Provide access to all HSPs for all alignments of all reads.
@return: A generator that yields HSPs (or LSPs). | 4.865724 | 3.22574 | 1.508406 |
self._filters.append(ReadsAlignmentsFilter(**kwargs).filter)
return self | def filter(self, **kwargs) | Add a filter to this C{readsAlignments}.
@param kwargs: Keyword arguments, as accepted by
C{ReadsAlignmentsFilter}.
@return: C{self} | 23.119286 | 9.820073 | 2.354289 |
### type checks
assert isinstance(species, (str, _oldstr)) or isinstance(species, Iterable)
if release is not None:
assert isinstance(release, int)
if ftp is not None:
assert isinstance(ftp, ftplib.FTP)
### open FTP connection if necessary
close_connection = False
ftp_s... | def get_annotation_urls_and_checksums(species, release=None, ftp=None) | Get FTP URLs and checksums for Ensembl genome annotations.
Parameters
----------
species : str or list of str
The species or list of species for which to get genome annotations
(e.g., "Homo_sapiens").
release : int, optional
The release number to look up. If `None`, use late... | 2.760075 | 2.68061 | 1.029644 |
r
valid_biotypes = set(['protein_coding'])
if include_polymorphic_pseudogenes:
valid_biotypes.add('polymorphic_pseudogene')
df = get_genes(path_or_buffer, valid_biotypes,
remove_duplicates=remove_duplicates, **kwargs)
return df | def get_protein_coding_genes(
path_or_buffer,
include_polymorphic_pseudogenes=True,
remove_duplicates=True,
**kwargs) | r"""Get list of all protein-coding genes based on Ensembl GTF file.
Parameters
----------
See :func:`get_genes` function.
Returns
-------
`pandas.DataFrame`
Table with rows corresponding to protein-coding genes. | 2.858838 | 3.514893 | 0.81335 |
r
valid_biotypes = set(['lincRNA'])
df = get_genes(path_or_buffer, valid_biotypes,
remove_duplicates=remove_duplicates, **kwargs)
return df | def get_linc_rna_genes(
path_or_buffer,
remove_duplicates=True,
**kwargs) | r"""Get list of all protein-coding genes based on Ensembl GTF file.
Parameters
----------
See :func:`get_genes` function.
Returns
-------
`pandas.DataFrame`
Table with rows corresponding to protein-coding genes. | 5.81023 | 7.894521 | 0.735983 |
titleId = title.split(' ', 1)[0]
try:
gi = titleId.split('|')[1]
except IndexError:
# Assume we have a gi number directly, and make sure it's a string.
gi = str(titleId)
try:
client = Entrez.efetch(db=db, rettype='gb', retmode='text', id=gi)
except URLError:
... | def getSequence(title, db='nucleotide') | Get information about a sequence from Genbank.
@param title: A C{str} sequence title from a BLAST hit. Of the form
'gi|63148399|gb|DQ011818.1| Description...'.
@param db: The C{str} name of the Entrez database to consult.
NOTE: this uses the network! Also, there is a 3 requests/second limit
i... | 3.531566 | 3.644623 | 0.96898 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.