code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
lowest_layer = None for layer in self.cloud_layers: if layer.coverage not in [CloudLayer.BROKEN, CloudLayer.OVERCAST]: continue if lowest_layer is None: lowest_layer = layer continue if layer.height > lowest_lay...
def get_ceiling_cloud_layer(self)
Returns the lowest layer of broken or overcast clouds. :rtype: CloudLayer|None
3.185127
2.551364
1.248401
self.raw_text = self.xml_data.find('raw_text').text self.station = WeatherStation(self.xml_data.find('station_id').text) self.station.latitude = float(self.xml_data.find('latitude').text) self.station.longitude = float(self.xml_data.find('longitude').text) self.station.e...
def parse_xml_data(self)
Parses `xml_data` and loads it into object properties.
2.251946
2.072898
1.086376
if mock_response is not None: body = mock_response else: api_url = self.get_api_url() body = urlopen(api_url).read() xml_root = ElementTree.fromstring(body) xml_warnings = xml_root.find('warnings') if len(xml_warnings.attrib) != 0: ...
def download_data(self, mock_response=None)
Loads XML data into the `xml_data` attribute.
2.443763
2.201762
1.109912
base_counts = defaultdict(int) read_number = 0 total_length = 0 length_list = [] records = SeqIO.parse(file_handle, file_type) for record in records: total_length += len(record) read_number += 1 length_list.append(len(record)) for base in record: ...
def summarizeReads(file_handle, file_type)
open a fasta or fastq file, prints number of of reads, average length of read, total number of bases, longest, shortest and median read, total number and average of individual base (A, T, G, C, N).
1.787646
1.680752
1.063599
result = [] append = result.append get = categories.get first = True currentCategory = None currentCount = 0 suppressing = False suppressedCount = 0 if minLength < 1: raise ValueError('minLength must be at least 1') for base in read.sequence: thisCategory =...
def sequenceCategoryLengths(read, categories, defaultCategory=None, suppressedCategory='...', minLength=1)
Summarize the nucleotides or AAs found in a read by assigning each to a category and reporting the lengths of the contiguous category classes found along the sequence. @param read: A C{Read} instance or one of its subclasses. @param categories: A C{dict} mapping nucleotides or AAs to category. @par...
2.518994
2.48859
1.012217
targetLen = len(target) result = [] for word in title.split(): if len(word) >= targetLen: offset = word.lower().find(target.lower()) if offset > -1: result.append(word[:offset + targetLen]) break result.append(word) return ' '...
def simplifyTitle(title, target)
Simplify a given sequence title. Given a title, look for the first occurrence of target anywhere in any of its words. Return a space-separated string of the words of the title up to and including the occurrence of the target. Ignore case. E.g., # Suffix simplifyTitle('Bovine polyomavirus...
2.635437
2.678911
0.983772
''' Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the simulated MyHDL code will be converted analyze_cmd - str, system command that will be run to a...
def registerSimulator(self, name=None, hdl=None, analyze_cmd=None, elaborate_cmd=None, simulate_cmd=None)
Registers an HDL _simulator name - str, user defined name, used to identify this _simulator record hdl - str, case insensitive, (verilog, vhdl), the HDL to which the simulated MyHDL code will be converted analyze_cmd - str, system command that will be run to analyze the g...
3.495916
1.509368
2.316146
''' Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters ''...
def _getCosimulation(self, func, **kwargs)
Returns a co-simulation instance of func. Uses the _simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters
5.793119
3.362555
1.722832
''' Enables traces in a Verilog file''' fname, _ = os.path.splitext(verilogFile) inserted = False for _, line in enumerate(fileinput.input(verilogFile, inplace = 1)): sys.stdout.write(line) if line.startswith("end") and not inserted: sys.stdout.wri...
def _enableTracesVerilog(self, verilogFile)
Enables traces in a Verilog file
3.087903
3.103818
0.994873
''' Returns a simulation instance of func. Uses the simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters ''' ...
def _getDut(self, func, **kwargs)
Returns a simulation instance of func. Uses the simulator specified by self._simulator. Enables traces if self._trace is True func - MyHDL function to be simulated kwargs - dict of func interface assignments: for signals and parameters
9.32834
2.521483
3.699545
for _file in self._files: with asHandle(_file) as fp: # Use FastqGeneralIterator because it provides access to # the unconverted quality string (i.e., it doesn't try to # figure out the numeric quality values, which we don't # ...
def iter(self)
Iterate over the sequences in the files in self.files_, yielding each as an instance of the desired read class.
8.427392
7.051721
1.195083
assert params['fastaFile'][-1] == 'a', ('You must specify a file in ' 'fasta-format that ends in ' '.fasta') fileCount = count = seqCount = 0 outfp = None with open(params['fastaFile']) as infp: for seq...
def splitFASTA(params)
Read the FASTA file named params['fastaFile'] and print out its sequences into files named 0.fasta, 1.fasta, etc. with params['seqsPerJob'] sequences per file.
2.961081
2.584782
1.145583
if not self._valid_name(task.name): raise ValueError(task.name) self._tasks[task.name] = task incomplete_dependencies = set() for dependency in task.dependencies: if not self._valid_name(dependency) or dependency in self._failed: # ther...
def add_task(self, task)
Add a task to the scheduler. task: The task to add.
4.046711
3.976794
1.017581
if name is None: for possibility in self._graph.roots: if possibility not in self._running: name = possibility break else: # all tasks blocked/running/completed/failed return None else: ...
def start_task(self, name=None)
Start a task. Returns the task that was started (or None if no task has been started). name: (optional, None) The task to start. If a name is given, Scheduler will attempt to start the task (and raise an exception if the task doesn't exist or isn't runnable). If ...
5.08474
5.129121
0.991347
self._running.remove(name) if success: self._completed.add(name) self._graph.remove(name, strategy=Strategy.orphan) else: self._cascade_failure(name)
def end_task(self, name, success=True)
End a running task. Raises an exception if the task isn't running. name: The name of the task to complete. success: (optional, True) Whether the task was successful.
7.439322
7.842416
0.948601
self._failed.update(self._graph.nodes) self._graph = Graph() self._running = set()
def fail_remaining(self)
Mark all unfinished tasks (including currently running ones) as failed.
10.528591
8.45918
1.244635
if name in self._graph: self._failed.update( self._graph.remove(name, strategy=Strategy.remove) ) else: self._failed.add(name)
def _cascade_failure(self, name)
Mark a task (and anything that depends on it) as failed. name: The name of the offending task
6.737678
7.563247
0.890845
# TODO: Make it so we can pass a 'db' argument to getSequence. record = getSequence(gi) if record is None: print("Looks like you're offline.") sys.exit(3) else: printed = set() if ranges: for (start, end) in ranges: for index, feature in ...
def main(gi, ranges)
Print the features of the genbank entry given by gi. If ranges is non-emtpy, only print features that include the ranges. gi: either a hit from a BLAST record, in the form 'gi|63148399|gb|DQ011818.1|' or a gi number (63148399 in this example). ranges: a possibly empty list of ranges to print inform...
3.879708
3.498533
1.108953
if startup_script is not None and startup_script_url is not None: raise ValueError('Cannot specify a startup script string and URL ' 'at the same time!') access_token = credentials.get_access_token() if metadata is None: metadata = {} meta_items = [{'key'...
def create_instance(credentials, project, zone, name, startup_script=None, startup_script_url=None, metadata=None, machine_type='f1-micro', tags=None, disk_size_gb=10, wait_until_done=False)
Create instance with startup script. TODO: docstring
1.978208
1.991868
0.993142
access_token = credentials.get_access_token() headers = { 'Authorization': 'Bearer %s' % access_token.access_token } r = requests.delete('https://www.googleapis.com/compute/v1/' 'projects/%s/zones/%s/instances/%s' % (project, zone, name), ...
def delete_instance(credentials, project, zone, name, wait_until_done=False)
Delete an instance. TODO: docstring
2.865535
2.893199
0.990438
t0 = time.time() access_token = credentials.get_access_token() headers = { 'Authorization': 'Bearer %s' % access_token.access_token } r = requests.get('https://www.googleapis.com/compute/v1/' 'projects/%s/zones/%s/instances/%s' % (project,...
def wait_for_instance_deletion(credentials, project, zone, instance_name, interval_seconds=5)
Wait until an instance is deleted. We require that initially, the specified instance exists. TODO: docstring
1.749999
1.728223
1.0126
indent = ' ' * indent def _references(sam): result = [] for i in range(sam.nreferences): result.append('%s%s (length %d)' % ( indent, sam.get_reference_name(i), sam.lengths[i])) return '\n'.join(result) if isinstance(filenameOrSamfile, six.string_ty...
def samReferencesToStr(filenameOrSamfile, indent=0)
List SAM/BAM file reference names and lengths. @param filenameOrSamfile: Either a C{str} SAM/BAM file name or an instance of C{pysam.AlignmentFile}. @param indent: An C{int} number of spaces to indent each line. @return: A C{str} describing known reference names and their lengths.
2.617474
2.91404
0.898229
hardClipCount = cigarLength = 0 for (operation, length) in cigartuples: hardClipCount += operation == CHARD_CLIP cigarLength += length if operation in _CONSUMES_QUERY else 0 sequenceLength = len(sequence) if quality is not None: assert sequenceLength == len(quality) cli...
def _hardClip(sequence, quality, cigartuples)
Hard clip (if necessary) a sequence. @param sequence: A C{str} nucleotide sequence. @param quality: A C{str} quality string, or a C{list} of C{int} quality values as returned by pysam, or C{None} if the SAM file had a '*' for the quality string (which pysam converts to C{None}). @param ciga...
2.186983
2.237421
0.977457
parser.add_argument( '%ssamfile' % ('' if samfileIsPositionalArg else '--'), required=True, help='The SAM/BAM file to filter.') parser.add_argument( '--referenceId', metavar='ID', nargs='+', action='append', help=('A reference sequenc...
def addFilteringOptions(parser, samfileIsPositionalArg=False)
Add options to an argument parser for filtering SAM/BAM. @param samfileIsPositionalArg: If C{True} the SAM/BAM file must be given as the final argument on the command line (without being preceded by --samfile). @param parser: An C{argparse.ArgumentParser} instance.
2.467891
2.460138
1.003152
referenceIds = (set(chain.from_iterable(args.referenceId)) if args.referenceId else None) return cls( args.samfile, filterRead=filterRead, referenceIds=referenceIds, storeQueryIds=storeQueryIds, dropUnmapped=ar...
def parseFilteringOptions(cls, args, filterRead=None, storeQueryIds=False)
Parse command line options (added in C{addSAMFilteringOptions}. @param args: The command line arguments, as returned by C{argparse.parse_args}. @param filterRead: A one-argument function that accepts a read and returns C{None} if the read should be omitted in filtering ...
2.689144
2.799465
0.960592
referenceIds = self.referenceIds dropUnmapped = self.dropUnmapped dropSecondary = self.dropSecondary dropSupplementary = self.dropSupplementary dropDuplicates = self.dropDuplicates keepQCFailures = self.keepQCFailures storeQueryIds = self.storeQueryIds ...
def alignments(self)
Get alignments from the SAM/BAM file, subject to filtering.
3.454516
3.373812
1.023921
result = {} with samfile(self.filename) as sam: if self.referenceIds: for referenceId in self.referenceIds: tid = sam.get_tid(referenceId) if tid == -1: raise UnknownReference( ...
def referenceLengths(self)
Get the lengths of wanted references. @raise UnknownReference: If a reference id is not present in the SAM/BAM file. @return: A C{dict} of C{str} reference id to C{int} length with a key for each reference id in C{self.referenceIds} or for all references if C{self.re...
3.251346
2.462211
1.320498
N = len(ls_di) @always_comb def _mux(): do.next = 0 for i in range(N): if i == sel: do.next = ls_di[i] return _mux
def mux(sel, ls_di, do)
Multiplexes a list of input signals to an output signal do = sl_di[sel] sel - select index ls_di - list of input signals do - output signals
2.981865
3.303811
0.902553
N = len(ls_do) @always_comb def _demux(): for i in range(N): ls_do[i].next = 0 if i == sel: ls_do[i].next = di return _demux
def demux(sel, di, ls_do)
Demultiplexes an input signal to a list of output signals ls_do[sel] = di sel - select index di - input signal ls_do - list of output signals
2.898774
3.384196
0.856562
N = len(ls_do) lsls_in = [list(x) for x in zip(*lsls_di)] return [mux(sel, lsls_in[i], ls_do[i]) for i in range(N)]
def ls_mux(sel, lsls_di, ls_do)
Multiplexes a list of input signal structures to an output structure. A structure is represented by a list of signals: [signal_1, signal_2, ..., signal_n] ls_do[0] = lsls_di[sel][0] ls_do[1] = lsls_di[sel][1] ... ls_do[n] = lsls_di[sel][n] sel - sele...
2.893209
2.822389
1.025092
N = len (ls_di) lsls_out = [list(x) for x in zip(*lsls_do)] return [demux(sel, ls_di[i], lsls_out[i])for i in range(N)]
def ls_demux(sel, ls_di, lsls_do)
Demultiplexes an input signal structure to list of output structures. A structure is represented by a list of signals: [signal_1, signal_2, ..., signal_n] lsls_do[sel][0] = ls_di[0] lsls_do[sel][1] = ls_di[1] ... lsls_do[sel][n] = ls_di[n] sel - sele...
3.670085
3.814784
0.962069
''' Selects a bit-slice from a bit-vector offset - (i) bit offset of the slice bv_di - (i) bit vector where the slice is taken from bv_do - (o) selected slice; the length of this bit-vector defines the number of bit in the slice bv_do = bv_di[len(bv_do)+offset:offs...
def bitslice_select(offset, bv_di, bv_do)
Selects a bit-slice from a bit-vector offset - (i) bit offset of the slice bv_di - (i) bit vector where the slice is taken from bv_do - (o) selected slice; the length of this bit-vector defines the number of bit in the slice bv_do = bv_di[len(bv_do)+offset:offset]
3.427296
2.192045
1.563515
''' Selects a slice of length 8*n aligned on a byte from a bit-vector offset - (i) byte offset of the slice bv_di - (i) bit vector where the slice is taken from; must len(bv_di) = 8*m bv_do - (o) selected slice; must len(bv_do) = 8*n, n<=m; len(bv_do) defines the number of bit ...
def byteslice_select(offset, bv_di, bv_do)
Selects a slice of length 8*n aligned on a byte from a bit-vector offset - (i) byte offset of the slice bv_di - (i) bit vector where the slice is taken from; must len(bv_di) = 8*m bv_do - (o) selected slice; must len(bv_do) = 8*n, n<=m; len(bv_do) defines the number of bit in the s...
3.835636
2.201141
1.742567
file_mv = cli.file_mv desc = 'Find all runs (SRR..) associated with an SRA experiment (SRX...).' parser = cli.get_argument_parser(desc=desc) parser.add_argument( '-e', '--experiment-file', type=str, required=True, metavar=file_mv, help='File with SRA experiment IDs (starting with...
def get_argument_parser()
Function to obtain the argument parser. Returns ------- A fully configured `argparse.ArgumentParser` object. Notes ----- This function is used by the `sphinx-argparse` extension for sphinx.
4.298404
4.744449
0.905986
if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() experiment_file = args.experiment_file output_file = args.output_file # log_file = args.log_file # quiet = args.quiet # verbose = args.verbose # logger = ...
def main(args=None)
Download all .sra from NCBI SRA for a given experiment ID. Parameters ---------- args: argparse.Namespace object, optional The argument values. If not specified, the values will be obtained by parsing the command line arguments using the `argparse` module. Returns ------- int ...
2.999318
2.836301
1.057475
model = model_attrib.parent.class_ if isinstance(search4, str): query_obj = query_obj.join(model).filter(model_attrib.like(search4)) elif isinstance(search4, int): query_obj = query_obj.join(model).filter(model_attrib == search4) elif isinstance(search...
def _one_to_many_query(cls, query_obj, search4, model_attrib)
extends and returns a SQLAlchemy query object to allow one-to-many queries :param query_obj: SQL Alchemy query object :param str search4: search string :param model_attrib: attribute in model
1.964035
2.065295
0.950971
q = self.session.query(models.Keyword) model_queries_config = ( (name, models.Keyword.name), (identifier, models.Keyword.identifier) ) q = self.get_model_queries(q, model_queries_config) q = self.get_many_to_many_queries(q, ((entry_name, models....
def keyword(self, name=None, identifier=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.Keyword` objects in database :param name: keyword name(s) :type name: str or tuple(str) or None :param identifier: keyword identifier(s) :type identifier: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :ty...
3.533832
3.542428
0.997573
q = self.session.query(models.Disease) model_queries_config = ( (identifier, models.Disease.identifier), (ref_id, models.Disease.ref_id), (ref_type, models.Disease.ref_type), (name, models.Disease.name), (acronym, models.Disease.acron...
def disease(self, identifier=None, ref_id=None, ref_type=None, name=None, acronym=None, description=None, entry_name=None, limit=None, as_df=False )
Method to query :class:`.models.Disease` objects in database :param identifier: disease UniProt identifier(s) :type identifier: str or tuple(str) or None :param ref_id: identifier(s) of referenced database :type ref_id: str or tuple(str) or None :param ref_type: database name...
2.005657
2.022137
0.99185
q = self.session.query(models.DiseaseComment) q = self.get_model_queries(q, ((comment, models.DiseaseComment.comment),)) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._limit_and_df(q, limit, as_df)
def disease_comment(self, comment=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.DiseaseComment` objects in database :param comment: Comment(s) to disease :type comment: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - if `i...
3.914127
3.721598
1.051733
q = self.session.query(models.OtherGeneName) model_queries_config = ( (type_, models.OtherGeneName.type_), (name, models.OtherGeneName.name), ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_name,...
def other_gene_name(self, type_=None, name=None, entry_name=None, limit=None, as_df=None)
Method to query :class:`.models.OtherGeneName` objects in database :param type_: type(s) of gene name e.g. *synonym* :type type_: str or tuple(str) or None :param name: other gene name(s) :type name: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry...
3.43284
3.387937
1.013254
q = self.session.query(models.AlternativeFullName) model_queries_config = ( (name, models.AlternativeFullName.name), ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) retur...
def alternative_full_name(self, name=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.AlternativeFullName` objects in database :param name: alternative full name(s) :type name: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - if ...
4.423707
3.898511
1.134717
q = self.session.query(models.AlternativeShortName) model_queries_config = ( (name, models.AlternativeShortName.name), ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) ret...
def alternative_short_name(self, name=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.AlternativeShortlName` objects in database :param name: alternative short name(s) :type name: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - ...
4.373343
3.917329
1.116409
q = self.session.query(models.Accession) model_queries_config = ( (accession, models.Accession.accession), ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._li...
def accession(self, accession=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.Accession` objects in database :param accession: UniProt Accession number(s) :type accession: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - ...
3.999302
3.917667
1.020838
q = self.session.query(models.Pmid) model_queries_config = ( (pmid, models.Pmid.pmid), (last, models.Pmid.last), (first, models.Pmid.first), (volume, models.Pmid.volume), (name, models.Pmid.name), (date, models.Pmid.date),...
def pmid(self, pmid=None, entry_name=None, first=None, last=None, volume=None, name=None, date=None, title=None, limit=None, as_df=False )
Method to query :class:`.models.Pmid` objects in database :param pmid: PubMed identifier(s) :type pmid: int or tuple(int) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param first: first page(s) :type first: s...
2.507923
2.500369
1.003021
q = self.session.query(models.OrganismHost) q = self.get_model_queries(q, ((taxid, models.OrganismHost.taxid),)) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._limit_and_df(q, limit, as_df)
def organism_host(self, taxid=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.OrganismHost` objects in database :param taxid: NCBI taxonomy identifier(s) :type taxid: int or tuple(int) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - if `i...
3.853583
3.705418
1.039986
q = self.session.query(models.DbReference) model_queries_config = ( (type_, models.DbReference.type_), (identifier, models.DbReference.identifier) ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_...
def db_reference(self, type_=None, identifier=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.DbReference` objects in database Check list of available databases with on :py:attr:`.dbreference_types` :param type_: type(s) (or name(s)) of database :type type_: str or tuple(str) or None :param identifier: unique identifier(s) in specific database (...
3.764359
4.195275
0.897285
q = self.session.query(models.Feature) model_queries_config = ( (type_, models.Feature.type_), (identifier, models.Feature.identifier), (description, models.Feature.description) ) q = self.get_model_queries(q, model_queries_config) q...
def feature(self, type_=None, identifier=None, description=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.Feature` objects in database Check available features types with ``pyuniprot.query().feature_types`` :param type_: type(s) of feature :type type_: str or tuple(str) or None :param identifier: feature identifier(s) :type identifier: str or tuple(...
3.366622
3.501554
0.961465
q = self.session.query(models.Function) model_queries_config = ( (text, models.Function.text), ) q = self.get_model_queries(q, model_queries_config) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._limit_and_df(q...
def function(self, text=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.Function` objects in database :param text: description(s) of function(s) :type text: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - if `isins...
4.467152
4.253503
1.050229
q = self.session.query(models.ECNumber) q = self.get_model_queries(q, ((ec_number, models.ECNumber.ec_number),)) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._limit_and_df(q, limit, as_df)
def ec_number(self, ec_number=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.ECNumber` objects in database :param ec_number: Enzyme Commission number(s) :type ec_number: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: - i...
3.845497
3.685746
1.043343
q = self.session.query(models.SubcellularLocation) q = self.get_model_queries(q, ((location, models.SubcellularLocation.location),)) q = self.get_many_to_many_queries(q, ((entry_name, models.SubcellularLocation.entries, models.Entry.name),)) return self._limit_and_df(q, limit...
def subcellular_location(self, location=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.SubcellularLocation` objects in database :param location: subcellular location(s) :type location: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: ...
3.445965
3.3954
1.014892
q = self.session.query(models.TissueSpecificity) q = self.get_model_queries(q, ((comment, models.TissueSpecificity.comment),)) q = self.get_one_to_many_queries(q, ((entry_name, models.Entry.name),)) return self._limit_and_df(q, limit, as_df)
def tissue_specificity(self, comment=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.TissueSpecificity` objects in database Provides information on the expression of a gene at the mRNA or protein level in cells or in tissues of multicellular organisms. By default, the information is derived from experiments at the mRNA level, unless specified ‘at...
3.871016
3.751547
1.031845
q = self.session.query(models.TissueInReference) model_queries_config = ( (tissue, models.TissueInReference.tissue), ) q = self.get_model_queries(q, model_queries_config) q = self.get_many_to_many_queries(q, ((entry_name, models.TissueInReference.entries, m...
def tissue_in_reference(self, tissue=None, entry_name=None, limit=None, as_df=False)
Method to query :class:`.models.TissueInReference` objects in database :param tissue: tissue(s) linked to reference :type tissue: str or tuple(str) or None :param entry_name: name(s) in :class:`.models.Entry` :type entry_name: str or tuple(str) or None :param limit: ...
3.686618
3.503107
1.052385
q = self.session.query(distinct(models.DbReference.type_)) return [x[0] for x in q.all()]
def dbreference_types(self)
Distinct database reference types (``type_``) in :class:`.models.DbReference` :return: List of strings for all available database cross reference types used in model DbReference :rtype: list[str]
5.756808
3.982272
1.445609
r = self.session.query(distinct(models.Entry.taxid)).all() return [x[0] for x in r]
def taxids(self)
Distinct NCBI taxonomy identifiers (``taxid``) in :class:`.models.Entry` :return: NCBI taxonomy identifiers :rtype: list[int]
5.544867
4.105586
1.350566
r = self.session.query(distinct(models.Entry.dataset)).all() return [x[0] for x in r]
def datasets(self)
Distinct datasets (``dataset``) in :class:`.models.Entry` Distinct datasets are SwissProt or/and TrEMBL :return: all distinct dataset types :rtype: list[str]
6.553388
3.915874
1.673544
r = self.session.query(distinct(models.Feature.type_)).all() return [x[0] for x in r]
def feature_types(self)
Distinct types (``type_``) in :class:`.models.Feature` :return: all distinct feature types :rtype: list[str]
5.360617
3.626352
1.478239
return [x[0] for x in self.session.query(models.SubcellularLocation.location).all()]
def subcellular_locations(self)
Distinct subcellular locations (``location`` in :class:`.models.SubcellularLocation`) :return: all distinct subcellular locations :rtype: list[str]
5.141717
4.858704
1.058249
return [x[0] for x in self.session.query(models.TissueInReference.tissue).all()]
def tissues_in_references(self)
Distinct tissues (``tissue`` in :class:`.models.TissueInReference`) :return: all distinct tissues in references :rtype: list[str]
5.124451
4.258515
1.203342
return [x[0] for x in self.session.query(models.Keyword.name).all()]
def keywords(self)
Distinct keywords (``name`` in :class:`.models.Keyword`) :returns: all distinct keywords :rtype: list[str]
5.566648
5.833171
0.954309
return [x[0] for x in self.session.query(models.Disease.name).all()]
def diseases(self)
Distinct diseases (``name`` in :class:`.models.Disease`) :returns: all distinct disease names :rtype: list[str]
4.682405
4.610678
1.015557
return [x for x in self.session.query(models.Version).all()]
def version(self)
Version of UniPort knowledgebase :returns: dictionary with version info :rtype: dict
10.259777
14.497171
0.707709
if not force: try: self.api.call_rc('ixPortTakeOwnership {}'.format(self.uri)) except Exception as _: raise TgnError('Failed to take ownership for port {} current owner is {}'.format(self, self.owner)) else: self.api.call_rc('...
def reserve(self, force=False)
Reserve port. :param force: True - take forcefully, False - fail if port is reserved by other user
6.731332
6.476472
1.039352
self.ix_command('write') stream_warnings = self.streamRegion.generateWarningList() warnings_list = (self.api.call('join ' + ' {' + stream_warnings + '} ' + ' LiStSeP').split('LiStSeP') if self.streamRegion.generateWarningList() else []) for warning in w...
def write(self)
Write configuration to chassis. Raise StreamWarningsError if configuration warnings found.
15.080925
10.481338
1.438836
config_file_name = config_file_name.replace('\\', '/') ext = path.splitext(config_file_name)[-1].lower() if ext == '.prt': self.api.call_rc('port import "{}" {}'.format(config_file_name, self.uri)) elif ext == '.str': self.reset() self.api.cal...
def load_config(self, config_file_name)
Load configuration file from prt or str. Configuration file type is extracted from the file suffix - prt or str. :param config_file_name: full path to the configuration file. IxTclServer must have access to the file location. either: The config file is on shared folder. ...
3.933038
3.450482
1.139852
config_file_name = config_file_name.replace('\\', '/') ext = path.splitext(config_file_name)[-1].lower() if ext == '.prt': self.api.call_rc('port export "{}" {}'.format(config_file_name, self.uri)) elif ext == '.str': # self.reset() self.api.c...
def save_config(self, config_file_name)
Save configuration file from prt or str. Configuration file type is extracted from the file suffix - prt or str. :param config_file_name: full path to the configuration file. IxTclServer must have access to the file location. either: The config file is on shared folder. ...
3.870545
3.384842
1.143493
self.session.start_transmit(blocking, False, self)
def start_transmit(self, blocking=False)
Start transmit on port. :param blocking: True - wait for traffic end, False - return after traffic start.
14.301006
17.456827
0.819221
return self.session.stop_capture(cap_file_name, cap_file_format, self)[self]
def stop_capture(self, cap_file_name=None, cap_file_format=IxeCapFileFormat.mem)
Stop capture on port. :param cap_file_name: prefix for the capture file name. Capture file will be saved as pcap file named 'prefix' + 'URI'.pcap. :param cap_file_format: exported file format :return: number of captured frames
6.658322
9.615951
0.692425
frames = [] for frame_num in frame_nums: if self.captureBuffer.getframe(frame_num) == '0': frames.append(self.captureBuffer.frame) else: frames.append(None) return frames
def get_cap_frames(self, *frame_nums)
Stop capture on ports. :param frame_nums: list of frame numbers to read. :return: list of captured frames.
3.982934
3.68644
1.080428
stat = IxeStat(self) stat.ix_set_default() stat.enableValidStats = True stat.ix_set() stat.write()
def clear_port_stats(self)
Clear only port stats (leave stream and packet group stats). Do not use - still working with Ixia to resolve.
19.001591
14.664579
1.295747
if isinstance(mode, IxePhyMode): if mode.value: self.api.call_rc('port setPhyMode {} {}'.format(mode.value, self.uri)) else: self.api.call_rc('port setPhyMode {} {}'.format(mode, self.uri))
def set_phy_mode(self, mode=IxePhyMode.ignore)
Set phy mode to copper or fiber. :param mode: requested PHY mode.
4.062733
4.423943
0.918351
self.api.call_rc('port setTransmitMode {} {}'.format(mode, self.uri))
def set_transmit_mode(self, mode)
set port transmit mode :param mode: request transmit mode :type mode: ixexplorer.ixe_port.IxeTransmitMode
26.607422
20.04258
1.327545
# It is possible to have the same width appear more than once, if # THUMBNAIL_UPSCALE is set to False and the image's width is less than the # largest value in FLEXIBLE_IMAGE_SIZES. So keep track of widths and # don't output more than one image with the same width (which would result # in an i...
def get_image_sizes(image)
Given an ImageField `image`, returns a list of images sizes in this form: [ { "url": "http://example.com/xxx.jpg", "width": 1440, "height": 960 }, [...] ]
5.50839
5.07139
1.08617
context = { "container": container, "classes": classes, "aspect_padding_bottom": aspect_ratio_percent(src), "alt": alt, "background_image": background_image, "no_css": no_css, "inner_classes": inner_classes, "aria_hidden": aria_hidden, } ...
def get_template_context(src, container="div", classes="", inner_classes="", alt="", background_image=False, no_css=False, aria_hidden=False)
Returns a template context for a flexible image template tag implementation.
4.561137
4.612919
0.988775
images = check_images(images) reference = check_reference(images, reference) def func(item): key, image = item return asarray([key, self._get(image, reference)]) transformations = images.map(func, with_keys=True).toarray() if images.shape[0] == ...
def fit(self, images, reference=None)
Estimate registration model using cross-correlation. Use cross correlation to compute displacements between images or volumes and reference. Displacements will be 2D for images and 3D for volumes. Parameters ---------- images : array-like or thunder images ...
6.141619
6.988411
0.878829
images = check_images(images) check_reference(images, reference) def func(image): t = self._get(image, reference) return t.apply(image) return images.map(func)
def fit_and_transform(self, images, reference=None)
Estimate and apply registration model using cross-correlation. Use cross correlation to compute displacements between images or volumes and reference, and apply the estimated model to the data. Displacements will be 2D for images and 3D for volumes. Parameters -------...
4.947738
8.653095
0.571788
if isinstance(path_patterns, string_types): path_patterns = [path_patterns] # Loop over available patherns, return first one that matches all for pattern in path_patterns: # If strict, all entities must be contained in the pattern if strict: defined = re.findall('\{...
def build_path(entities, path_patterns, strict=False)
Constructs a path given a set of entities and a list of potential filename patterns to use. Args: entities (dict): A dictionary mapping entity names to entity values. path_patterns (str, list): One or more filename patterns to write the file to. Entities should be represented by the...
4.261427
4.219154
1.010019
'''Deduce settings from environment variables''' settings = {} for name, value in environ.items(): if not name.startswith('DJANGO_'): continue name = name.replace('DJANGO_', '', 1) if _ignore_setting(name): continue try: settings[name] = as...
def get_settings_from_environment(environ)
Deduce settings from environment variables
2.725034
2.542275
1.071888
assert isinstance(matrix, ExpMatrix) assert isinstance(top, (int, np.integer)) if top >= matrix.p: logger.warning('Variance filter has no effect ' '("top" parameter is >= number of genes).') return matrix.copy() var = np.var(matrix.X, axis=1, ddof=1) tot...
def filter_variance(matrix, top)
Filter genes in an expression matrix by variance. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix.
3.432678
3.443202
0.996943
assert isinstance(matrix, ExpMatrix) assert isinstance(top, int) if top >= matrix.p: logger.warning('Gene expression filter with `top` parameter that is ' '>= the number of genes!') top = matrix.p a = np.argsort(np.mean(matrix.X, axis=1)) a = a[::-1] ...
def filter_mean(matrix, top)
Filter genes in an expression matrix by mean expression. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. Returns ------- ExpMatrix The filtered expression matrix.
4.301225
4.26215
1.009168
assert isinstance(matrix, ExpMatrix) assert isinstance(top, int) assert isinstance(percentile, (int, float)) if top >= matrix.p: logger.warning('Gene expression filter with `top` parameter that is ' ' >= the number of genes!') top = matrix.p a = np.argso...
def filter_percentile(matrix, top, percentile=50)
Filter genes in an expression matrix by percentile expression. Parameters ---------- matrix: ExpMatrix The expression matrix. top: int The number of genes to retain. percentile: int or float, optinonal The percentile to use Defaults to the median (50th percentile). Ret...
3.861903
3.823078
1.010156
try: c = int(chrom) except: if chrom in ['X', 'Y']: return chrom elif chrom == 'MT': return '_MT' # sort to the end else: return '__' + chrom # sort to the very end else: # make sure numbered chromosomes are sorted numerically...
def _transform_chrom(chrom)
Helper function to obtain specific sort order.
4.853749
4.581843
1.059344
chromlen = [] with gzip.open(fasta_file, 'rt', encoding='ascii') as fh: fasta = SeqIO.parse(fh, 'fasta') for i, f in enumerate(fasta): chromlen.append((f.id, len(f.seq))) _LOGGER.info('Processed chromosome "%s"...', f.id) #print(dir(f)) #if i ...
def get_chromosome_lengths(fasta_file, fancy_sort=True)
Extract chromosome lengths from genome FASTA file.
3.254662
3.288205
0.989799
def traverse(schema): if isinstance(schema, dict): if 'allOf' in schema: for x in schema['allOf']: sub_schema = x sub_schema.pop('title', None) schema = _merge_dicts(schema, sub_schema) schema.pop('a...
def resolve_schema(schema)
Transform JSON schemas "allOf". This is the default schema resolver. This function was created because some javascript JSON Schema libraries don't support "allOf". We recommend to use this function only in this specific case. This function is transforming the JSON Schema by removing "allOf" keywo...
2.468007
2.478371
0.995818
new = deepcopy(first) for k, v in second.items(): if isinstance(v, dict) and v: ret = _merge_dicts(new.get(k, dict()), v) new[k] = ret else: new[k] = second[k] return new
def _merge_dicts(first, second)
Merge the 'second' multiple-dictionary into the 'first' one.
2.008008
1.926441
1.04234
assert isinstance(cmap_file, str) cm = np.loadtxt(cmap_file, delimiter='\t', dtype=np.float64) # x = cm[:, 0] rgb = np.int64(cm[:, 1:]) # normalize to 0-1? n = cm.shape[0] colorscale = [] for i in range(n): colorscale.append( [i / float(n - 1), 'rgb(%d...
def read_colorscale(cmap_file)
Return a colorscale in the format expected by plotly. Parameters ---------- cmap_file : str Path of a plain-text file containing the colorscale. Returns ------- list The colorscale. Notes ----- A plotly colorscale is a list where each item is a pair (i...
2.679605
2.615506
1.024507
global router routings = [ ('GET', '^/$', index), ('GET', '^/api/?$', index), ('POST', '^/api/1/calculate/?$', calculate.api1_calculate), ('GET', '^/api/2/entities/?$', entities.api2_entities), ('GET', '^/api/1/field/?$', field.api1_field), ('GET', '^/api/1/f...
def make_router()
Return a WSGI application that searches requests to controllers
2.721035
2.714703
1.002332
for root, dirs, files in os.walk(directory): dir_path = os.path.relpath(root, directory) if dir_path == '.': dir_path = '' for file_ in files: if file_.lower().endswith(('.json')): schema_name = os.path.join(dir_pat...
def register_schemas_dir(self, directory)
Recursively register all json-schemas in a directory. :param directory: directory path.
2.326192
2.484761
0.936183
self.schemas[path] = os.path.abspath(directory)
def register_schema(self, directory, path)
Register a json-schema. :param directory: root directory path. :param path: schema path, relative to the root directory.
5.407086
7.505197
0.720446
if path not in self.schemas: raise JSONSchemaNotFound(path) return self.schemas[path]
def get_schema_dir(self, path)
Retrieve the directory containing the given schema. :param path: Schema path, relative to the directory where it was registered. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. :returns: The schema directory.
4.920808
3.974518
1.238089
if path not in self.schemas: raise JSONSchemaNotFound(path) return os.path.join(self.schemas[path], path)
def get_schema_path(self, path)
Compute the schema's absolute path from a schema relative path. :param path: relative path of the schema. :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If no schema was found in the specified path. :returns: The absolute path.
4.536682
3.618424
1.253773
if path not in self.schemas: raise JSONSchemaNotFound(path) with open(os.path.join(self.schemas[path], path)) as file_: schema = json.load(file_) if with_refs: schema = JsonRef.replace_refs( schema, base...
def get_schema(self, path, with_refs=False, resolved=False)
Retrieve a schema. :param path: schema's relative path. :param with_refs: replace $refs in the schema. :param resolved: resolve schema using the resolver :py:const:`invenio_jsonschemas.config.JSONSCHEMAS_RESOLVER_CLS` :raises invenio_jsonschemas.errors.JSONSchemaNotFound: If...
3.19529
2.790244
1.145165
parts = urlsplit(url) try: loader, args = self.url_map.bind(parts.netloc).match(parts.path) path = args.get('path') if loader == 'schema' and path in self.schemas: return path except HTTPException: return None
def url_to_path(self, url)
Convert schema URL to path. :param url: The schema URL. :returns: The schema path or ``None`` if the schema can't be resolved.
4.982759
5.358207
0.92993
if path not in self.schemas: return None return self.url_map.bind( self.app.config['JSONSCHEMAS_HOST'], url_scheme=self.app.config['JSONSCHEMAS_URL_SCHEME'] ).build( 'schema', values={'path': path}, force_external=True)
def path_to_url(self, path)
Build URL from a path. :param path: relative path of the schema. :returns: The schema complete URL or ``None`` if not found.
4.447968
4.131617
1.076568
cls = self.app.config['JSONSCHEMAS_LOADER_CLS'] if isinstance(cls, six.string_types): return import_string(cls) return cls
def loader_cls(self)
Loader class used in `JsonRef.replace_refs`.
3.618702
3.167421
1.142476
self.init_config(app) if not entry_point_group: entry_point_group = self.kwargs['entry_point_group'] \ if 'entry_point_group' in self.kwargs \ else 'invenio_jsonschemas.schemas' state = InvenioJSONSchemasState(app) # Load the json-s...
def init_app(self, app, entry_point_group=None, register_blueprint=True, register_config_blueprint=None)
Flask application initialization. :param app: The Flask application. :param entry_point_group: The group entry point to load extensions. (Default: ``invenio_jsonschemas.schemas``) :param register_blueprint: Register the blueprints. :param register_config_blueprint: Register ...
3.030534
2.941785
1.030169
for k in dir(config): if k.startswith('JSONSCHEMAS_'): app.config.setdefault(k, getattr(config, k)) host_setting = app.config['JSONSCHEMAS_HOST'] if not host_setting or host_setting == 'localhost': app.logger.warning('JSONSCHEMAS_HOST is set to {...
def init_config(self, app)
Initialize configuration.
3.263327
3.201826
1.019208
if xRange not in ('subject', 'reads'): raise ValueError('xRange must be either "subject" or "reads".') if equalizeXAxes: raise NotImplementedError('This feature is not yet implemented.') titles = titlesAlignments.sortTitles(sortOn) if os.access(outputDir, os.F_OK): # out...
def alignmentPanelHTML(titlesAlignments, sortOn='maxScore', outputDir=None, idList=False, equalizeXAxes=False, xRange='subject', logLinearXAxis=False, logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False, showFeatures=True, ...
Produces an HTML index file in C{outputDir} and a collection of alignment graphs and FASTA files to summarize the information in C{titlesAlignments}. @param titlesAlignments: A L{dark.titles.TitlesAlignments} instance. @param sortOn: The attribute to sort subplots on. Either "maxScore", "medianScor...
3.872733
3.679331
1.052564
maxScore = None maxHsps = 0 cols = 5 rows = int(len(titlesAlignments) / cols) + ( 0 if len(titlesAlignments) % cols == 0 else 1) f, ax = plt.subplots(rows, cols) coords = dimensionalIterator((rows, cols)) for title in titlesAlignments: titleAlignments = titlesAlignments...
def scoreGraph(titlesAlignments, find=None, showTitles=False, figureWidth=5, figureHeight=5)
NOTE: This function has probably bit rotted (but only a little). Produce a rectangular panel of graphs, each of which shows sorted scores for a title. Matches against a certain sequence title, as determined by C{find}, (see below) are highlighted. @param find: A function that can be passed a sequence ...
2.73218
2.720241
1.004389
d1 = defaultdict(list) d2 = defaultdict(list) for (seq, section_dict) in [(seq1, d1), (seq2, d2)]: for i in range(len(seq) - window): section = seq[i:i + window] section_dict[section].append(i) matches = set(d1).intersection(d2) print('%i unique matches' % len(ma...
def scatterAlign(seq1, seq2, window=7)
Visually align two sequences.
2.787504
2.765675
1.007893
MISSING_AA_VALUE = -1.1 propertyValues = propertiesForSequence(sequence, propertyNames, missingAAValue=MISSING_AA_VALUE) if showFigure: legend = [] x = np.arange(0, len(sequence)) plot = plt.plot if showLines else plt.scatter f...
def plotAAProperties(sequence, propertyNames, showLines=True, showFigure=True)
Plot amino acid property values for a sequence. @param sequence: An C{AARead} (or a subclass) instance. @param propertyNames: An iterable of C{str} property names (each of which must be a key of a key in the C{dark.aa.PROPERTY_DETAILS} C{dict}). @param showLines: If C{True}, lines will be drawn bet...
2.822814
2.791795
1.011111