code
stringlengths
1
18.2k
self._proteinGrouper.pathogenNames[ pathogenName][sampleName]['uniqueReadCount'] = nReads self._readsFilenames[(pathogenIndex, sampleIndex)] = saveFilename return saveFilename
def lookup(self, pathogenName, sampleName): """ Look up a pathogen name, sample name combination and get its FASTA/FASTQ file name and unique read count. This method should be used instead of C{add} in situations where you want an exception to be raised if a pathogen/sample combination has not already been passed to C{...
def writeSampleIndex(self, fp): """ Write a file of sample indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) in self._samples.items()) ), file=fp)
def writePathogenIndex(self, fp): """ Write a file of pathogen indices and names, sorted by index. @param fp: A file-like object, opened for writing. """ print('\n'.join( '%d %s' % (index, name) for (index, name) in sorted((index, name) for (name, index) in self._pathogens.items()) ), file=fp)
def _title(self): """ Create a title summarizing the pathogens and samples. @return: A C{str} title. """ return ( 'Overall, proteins from %d pathogen%s were found in %d sample%s.' % (len(self.pathogenNames), '' if len(self.pathogenNames) == 1 else 's', len(self.sampleNames), '' if len(self.sampleNames) == 1 else 's'))
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. """ if self._sampleName: sampleNa...
line of information for a given # pathogen/sample/protein combination. if proteinName in proteins: raise ValueError( 'Protein %r already seen for pathogen %r sample %r.' % (proteinName, pathogenName, sampleName)) readsFilename = join(outDir, '%d.%s' % (index, self._format)) proteins[proteinName] = { 'bestScore': float(...
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}. """ for pathogenName, samples in self.pathogenNames.items(): for sampleName in sa...
def toStr(self): """ Produce a string representation of the pathogen summary. @return: A C{str} suitable for printing. """ # 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 #...
proteinCount == 1 else 's', totalReads, '' if totalReads == 1 else 's')) for proteinName in sorted(proteins): append( ' %(coverage).2f\t%(medianScore).2f\t' '%(bestScore).2f\t%(readCount)4d\t%(hspCount)4d\t' '%(index)3d\t%(proteinName)s' % proteins[proteinName]) append('') return '\n'.join(result)
def toHTML(self, pathogenPanelFilename=None, minProteinFraction=0.0, pathogenType='viral', sampleIndexFilename=None, pathogenIndexFilename=None): """ Produce an HTML string representation of the pathogen summary. @param pathogenPanelFilename: If not C{None}, a C{str} filename to write a pathogen panel PNG image to. @pa...
and then the pathogen name. @return: An HTML C{str} suitable for printing. """ if pathogenType not in ('bacterial', 'viral'): raise ValueError( "Unrecognized pathogenType argument: %r. Value must be either " "'bacterial' or 'viral'." % pathogenType) highlightSymbol = '★' self._computeUniqueReadCounts() if pathoge...
charset="UTF-8">', '</head>', '<body>', '<style>', '''\ body { margin-left: 2%; margin-right: 2%; } hr { display: block; margin-top: 0.5em; margin-bottom: 0.5em; margin-left: auto; margin-right: auto; border-style: inset; border-width: 1px; } p.pathogen { margin-top: 10px; margin-bottom: 3px; } p.sample { margin-top: 1...
below, there are the following ' 'fields:', '<ol>', '<li>Coverage fraction.</li>', '<li>Median bit score.</li>', '<li>Best bit score.</li>', '<li>Read count.</li>', '<li>HSP count (a read can match a protein more than once).</li>', '<li>Protein length (in AAs).</li>', '<li>Index (just ignore this).</li>', ] if self._sa...
%d pathogens is ' 'displayed. These are the only pathogens for which ' 'at least one sample matches at least %.2f%% of ' 'the pathogen proteins.' % (nPathogenNames, percent)) else: append('Pathogen protein fraction filtering has been applied, ' 'but all pathogens have at least %.2f%% of their ' 'proteins matched by at ...
pathogenName in pathogenNames: append('<a href="#pathogen-%s">%s</a>' % (pathogenName, pathogenName)) append('&middot;') # Get rid of final middle dot and add a period. result.pop() result[-1] += '.' append('</span></p>') # Write a linked table of contents by sample. append('<p><span class="index-name">Sample index:</s...
'' if pathogenProteinCount == 1 else 's')) if pathogenProteinCount else ''), sampleCount, '' if sampleCount == 1 else 's')) for sampleName in sorted(samples): readsFileName = self.pathogenSampleFiles.lookup( pathogenName, sampleName) proteins = samples[sampleName]['proteins'] proteinCount = len(proteins) uniqueReadCoun...
% ', '.join( map(str, sorted(proteinMatch['readLengths'])))) append( '</span> ' '<span class="protein-name">' '%(proteinName)s' '</span> ' '(<a href="%(bluePlotFilename)s">blue plot</a>, ' '<a href="%(readsFilename)s">reads</a>' % proteinMatch) if proteinMatch['proteinURL']: # Append this directly to the last string in...
pathogenName][sampleName]['uniqueReadCount'] proteinCount = len(proteins) pathogenProteinCount = self._pathogenProteinCount[pathogenName] highlight = '' if pathogenProteinCount: proteinCountStr = '%d/%d protein%s' % ( proteinCount, pathogenProteinCount, '' if pathogenProteinCount == 1 else 's') if (proteinCount / patho...
the last string in result, to # avoid introducing whitespace when we join result # using '\n'. result[-1] += (', <a href="%s">NCBI</a>' % proteinMatch['proteinURL']) result[-1] += ')' append('</li>') append('</ul>') append('</body>') append('</html>') return '\n'.join(result)
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. """ readCounts = [] for i...
len(sampleNames) x = np.arange(nSamples) yMin = np.zeros(nSamples) ax.set_xticks([]) ax.set_xlim((-0.5, nSamples - 0.5)) ax.vlines(x, yMin, readCounts, color=color) if highlighted: title = '%s\nIn red: %s' % ( pathogenName, fill(', '.join(highlighted), 50)) else: # Add a newline to keep the first line of each title at ...
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. """ import matplotlib matplotlib.use('PDF') import matplotlib.pyplot as plt self._c...
of the last row may be unused. for row, col in coords: ax[row][col].axis('off') figure.suptitle( ('Per-sample read count for %d pathogen%s and %d sample%s.\n\n' 'Sample name%s: %s') % ( len(pathogenNames), '' if len(pathogenNames) == 1 else 's', len(sampleNames), '' if len(sampleNames) == 1 else 's', '' if len(sampleNa...
def get_args(request_args, allowed_int_args=[], allowed_str_args=[]): """Check allowed argument names and return is as dictionary""" 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_...
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: string required: false description: reference identifier default: 10430...
args = get_args( request_args=request.args, allowed_str_args=allowed_str_args ) return jsonify(query.disease(**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: entry_name in: query type: string req...
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 type: string required: false description: Un...
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 type: string required: false description: Alternative sh...
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: query type: string required: false description: UniProt ent...
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: string required: false description: UniProt entry name default: A4_H...
of publication default: '%amyloidosis%' - name: limit in: query type: integer required: false description: limit of results numbers default: 10 """ args = get_args( request_args=request.args, allowed_str_args=['first', 'last', 'volume', 'name', 'date', 'title', 'entry_name'], allowed_int_args=['pmid', 'limit'] ) return...
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: string required: false description: UniProt entry name def...
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 required: false description: reference identifier default: Y...
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 type: string required: false description: Feature identifier default...
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 type: string required: false description: UniProt entry...
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: query type: string required: false description: Disease id...
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_name in: query type: string required: false descri...
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 in: query type: string required: false descr...
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: query type: string required: false description: ...
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: string required: false description: UniProt entry name...
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_name in: query type: string required: false d...
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. """ upperCase = self._upperCase for _file in self._fil...
= self._readClass(record.description, str(record.seq), str(structureRecord.seq)) yield read
def npartial(func, *args, **kwargs): """ Returns a partial node visitor function """ def wrapped(self, node): func(self, *args, **kwargs) return wrapped
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) """ 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 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' >>...
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_se...
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. T...
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) % 3, 3): try: aa = dna_to_aa1_lut[seq[i:i + 3]] except KeyError: raise ValueError("Codon {} at position {}..{} is undefined in codon table".forma...
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 :rais...
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 """ return SLASH.join([self._api_base_url, url.lstrip(SLASH)])
def merge_dictionaries(current, new, only_defaults=False, template_special_case=False): ''' 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...
list(current_value) + [element] LOGGER.debug("Added %r to %r.", element, key) changes += 1 elif isinstance(current_value, Promise) or isinstance(value, Promise): # If we don't know what to do with it, replace it. if current_value is not value: current[key] = value LOGGER.debug("Set %r to %r.", key, current[key]) change...
def configure_settings(settings, environment_settings=True): ''' 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.appen...
def configure_urls(apps, index_view=None, prefixes=None): ''' 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=Fals...
def check_images(data): """ Check and reformat input images if needed """ 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))) retur...
def check_reference(images, reference): """ Ensure the reference matches image dimensions """ 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 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. """ assert isinstance(data, dict) ...
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. """ assert start <= end self._in...
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 the interval. I.e., the ...
by an empty one (if there # is another interval pending). lastFull = nextFull() yield (self.FULL, lastFull) if intervals: yield (self.EMPTY, (lastFull[1], intervals[0][0])) # Yield the final empty section, if any. if lastFull[1] < self._targetLength: yield (self.EMPTY, (lastFull[1], self._targetLength)) else: yield (se...
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. """ 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 ...
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. """ coverageCounts = Counter() for sta...
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. """ reduction = 0 for (thisOffset, thisReduction) in self._adjustments: if offset >= thisOffset: reduction += t...
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. """ reduction = self._reductionForOffset( min(hsp.readStartInSubject, hsp.subjectStart)) hsp.readEndInSubject = hsp.readEndInSubject - reduction hsp.readStartInSubject = ...
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. """ if i >= self.n: raise ValueError('Index %d out of bounds ' % i + 'for database with %d gene sets....
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 """ gene_sets = [] n = 0 with open(path, 'rb') as fh: reader = csv.reader(fh, dialect='e...
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 """ 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.va...
def read_msigdb_xml(cls, path, entrez2gene, species=None): # pragma: no cover """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 T...
[0] species_excl = [0] unknown_entrezid = [0] src = 'MSigDB' def handle_item(pth, item): # 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_ = data['SYSTEMATIC_NAME'] name...
if species_excl[0] > 0: kept = total_gs[0] - species_excl[0] perc = 100 * (kept / float(total_gs[0])) logger.info('%d of all %d gene sets (%.1f %%) belonged to the ' 'specified species.', kept, total_gs[0], perc) if unknown_entrezid[0] > 0: unkn = unknown_entrezid[0] # known = total_genes[0] - unknown_entrezid[0] perc ...
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. """ excludedQualifiers = set(( 'codon_start', 'db_xref', 'protein_id', 'region_name', 'ribosomal_slippage', 'rpt_type', 'translation', 'transl_...
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 BLA...
= FeatureList(title, self.DATABASE, self.WANTED_TYPES, sequenceFetcher=sequenceFetcher) if features.offline: fig.text(minX + (maxX - minX) / 3.0, 0, 'You (or Genbank) appear to be offline.', fontsize=self.FONTSIZE) fig.axis([minX, maxX, -1, 1]) return None # If no interesting features were found, display a message sayi...
/ 3.0, 0, # 'Too many features to plot.', fontsize=self.FONTSIZE) fig.text(0.5, 0.5, 'Too many features to plot', horizontalalignment='center', verticalalignment='center', fontsize=self.FONTSIZE, transform=fig.transAxes) fig.axis([minX, maxX, -1, 1]) return features
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 ...
loc='lower center', bbox_to_anchor=(0.5, 1.4), fancybox=True, shadow=True, ncol=2)
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 ...
[''])[0] if product.lower().find('polyprotein') > -1: y = frame + 0.2 else: y = frame fig.plot([start, end], [y, y], color=feature.color, linewidth=2) labels.append(feature.legendLabel()) # Note that minX and maxX do not need to be adjusted by the offset # adjuster. They are the already-adjusted min/max values as # com...
def recent_articles(limit=10, exclude=None): """Returns list of latest article""" 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 _flatten(n): """Recursively flatten a mixed sequence of sub-sequences and items""" if isinstance(n, collections.Sequence): for x in n: for y in _flatten(x): yield y else: yield n
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 :...
characters to buffer. :param bool echo: If ``True``, echoes received characters to stdout. :param bool close_stream: If ``True``, and the wrapper is used as a context manager, closes the stream at the end of the context manager. """ if hasattr(stream, 'read'): proxy = PollingStreamAdapter(stream) elif hasattr(stream, '...
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 *...
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 match was...
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 match was f...
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:`RegexMatch` if match...
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 smallest inde...
def poll(self, timeout): """ :param float timeout: Timeout in seconds. """ 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: raise ExpectTimeout(...
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. """ now = time.time() end_time = now + float(timeout) prev_timeout = self.stream.gettimeout() self.stream.settimeout(self._poll_perio...
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, rais...
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, rai...
return match
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. """ self._graph = Graph() # First add all nodes for key in self.loader.disk_fixtures.keys(): self.graph.add_node(key) # Then set dependencies fo...
def get_app_nodes(self, app_label): """ Get all nodes for given app :param str app_label: app label :rtype: list """ return [node for node in self.graph.nodes if node[0] == app_label]
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. """ app_nodes = self.get_app_nodes(app_label=app_label) nodes = [ node for node in app_no...
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. """ if progress_c...
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: """ if nodes: plan = self.graph.resolve_nodes(nodes) else: plan = self.graph.resolve_node() return plan