code
stringlengths
1
18.2k
def register_schemas_dir(self, directory): """Recursively register all json-schemas in a directory. :param directory: directory path. """ 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')): s...
def register_schema(self, directory, path): """Register a json-schema. :param directory: root directory path. :param path: schema path, relative to the root directory. """ self.schemas[path] = os.path.abspath(directory)
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. """ if path not in self...
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. """ if path not in self.schemas: raise JSONSchem...
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.JSO...
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. """ 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.sch...
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. """ 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'] )....
def loader_cls(self): """Loader class used in `JsonRef.replace_refs`.""" cls = self.app.config['JSONSCHEMAS_LOADER_CLS'] if isinstance(cls, six.string_types): return import_string(cls) return cls
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: Regi...
def init_config(self, app): """Initialize configuration.""" 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 {0}'.format( ho...
def alignmentGraph(titlesAlignments, title, addQueryLines=True, showFeatures=True, logLinearXAxis=False, logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE, rankScores=False, colorQueryBases=False, createFigure=True, showFigure=True, readsAx=None, imageFile=None, quiet=False, idList=False, xRange='subject', showOrfs=True): """ Ali...
@param logBase: The base of the logarithm to use if logLinearXAxis is C{True}. @param: rankScores: If C{True}, change the e-values and bit scores for the reads for each title to be their rank (worst to best). @param colorQueryBases: if C{True}, color each base of a query string. If C{True}, then addQueryLines is meanin...
If C{True}, don't print progress / timing output. @param idList: a dictionary. The keys is a color and the values is a list of read identifiers that should be colored in the respective color. @param xRange: set to either 'subject' or 'reads' to indicate the range of the X axis. @param showOrfs: If C{True}, open reading...
featureAx = plt.subplot(gs[0, 0]) readsAx = readsAx or plt.subplot(gs[1, 0]) else: if showOrfs: gs = gridspec.GridSpec(3, 1, height_ratios=[1, 1, 12]) orfAx = plt.subplot(gs[0, 0]) orfReversedAx = plt.subplot(gs[1, 0]) readsAx = readsAx or plt.subplot(gs[2, 0]) else: readsAx = readsAx or plt.subplot(111) # Make a deep ...
pass else: adjuster(titleAlignments) if rankScores: reverse = titlesAlignments.scoreClass is not HigherIsBetterScore for rank, hsp in enumerate(sorted(titleAlignments.hsps(), reverse=reverse), start=1): hsp.score.score = rank if logLinearXAxis: readIntervals = ReadIntervals(titleAlignments.subjectLength) # Examine all ...
# We'll display a graph for the full subject range. Adjust X axis # min/max to make sure we cover at least zero to the sequence length. maxX = max(titleAlignments.subjectLength, maxX) minX = min(0, minX) # Swap min & max Y values, if needed, as it's possible we are dealing # with LSPs but that the score adjuster made n...
last gap: intervalType, (start, stop) = gaps[-1] if intervalType == ReadIntervals.EMPTY: adjustedStop = adjustOffset(stop) if adjustedStop > maxX: maxX = adjustedStop # We're all set up to start plotting the graph. # Add light grey vertical rectangles to show the logarithmic gaps. Add # these first so that reads will b...
color='#f4f4f4') if colorQueryBases: # Color each query by its bases. xScale = 3 yScale = 2 baseImage = BaseImage( maxX - minX, maxY - minY + (1 if rankScores else 0), xScale, yScale) for alignment in titleAlignments: for hsp in alignment.hsps: y = hsp.score.score - minY # If the product of the subject and read frame v...
(if any) before the matched # part of the subject. 2) the matched part (which can # include gaps in the query and/or subject). 3) the right # part (if any) after the matched part. For each part, # calculate the ranges in which we have to make the # comparison between subject and query. # NOTE: never use hsp['origHsp']....
subtracted to get the right # length. origQuery = hsp.readMatchedSequence.upper() rightRange = (hsp.readEndInSubject - hsp.subjectEnd - origQuery.count('-')) # 1. Left part. xOffset = readStartInSubject - minX queryOffset = 0 for queryIndex in range(leftRange): color = QUERY_COLORS.get(query[queryOffset + queryIndex], ...
== origQuery[matchIndex]: # The query matched the subject at this location. # Matching bases are all colored in the same # 'match' color. color = QUERY_COLORS['match'] else: if origQuery[matchIndex] == '-': # A gap in the query. All query gaps get the # same 'gap' color. color = QUERY_COLORS['gap'] else: # Query doesn'...
(below) draw the matched part # on top of part of them. if addQueryLines: for hsp in titleAlignments.hsps(): y = hsp.score.score line = Line2D([hsp.readStartInSubject, hsp.readEndInSubject], [y, y], color='#aaaaaa') readsAx.add_line(line) # Add the horizontal BLAST alignment lines. # If an idList is given set things up...
showFeatures: if subjectIsNucleotides: featureAdder = NucleotideFeatureAdder() else: featureAdder = ProteinFeatureAdder() features = featureAdder.add(featureAx, title, minX, maxX, adjustOffset) # If there are features and there weren't too many of them, add # vertical feature lines to the reads and ORF axes. if feature...
# Titles, axis, etc. if createFigure: readCount = titleAlignments.readCount() hspCount = titleAlignments.hspCount() figure.suptitle( '%s\nLength %d %s, %d read%s, %d HSP%s.' % ( fill(titleAlignments.subjectTitle, 80), titleAlignments.subjectLength, 'nt' if subjectIsNucleotides else 'aa', readCount, '' if readCount == 1...
def alignmentPanel(titlesAlignments, sortOn='maxScore', idList=False, equalizeXAxes=False, xRange='subject', logLinearXAxis=False, rankScores=False, showFeatures=True, logBase=DEFAULT_LOG_LINEAR_X_AXIS_BASE): """ Produces a rectangular panel of graphs that each contain an alignment graph against a given sequence. @para...
The logarithm base to use if logLinearXAxis is C{True}. @param: rankScores: If C{True}, change the scores for the reads for each title to be their rank (worst to best). @param showFeatures: If C{True}, look online for features of the subject sequences. @raise ValueError: If C{outputDir} exists but is not a directory or...
in enumerate(titles): titleAlignments = titlesAlignments[title] row, col = next(coords) report('%d: %s %s' % (i, title, NCBISequenceLinkURL(title, ''))) # Add a small plot to the alignment panel. graphInfo = alignmentGraph( titlesAlignments, title, addQueryLines=True, showFeatures=showFeatures, rankScores=rankScores, l...
ranked score' else: plotTitle += '\nmax %.2f, median %.2f' % ( titleAlignments.bestHsp().score.score, titleAlignments.medianScore()) ax[row][col].set_title(plotTitle, fontsize=10) maxX = max(graphInfo['maxX'] for graphInfo in allGraphInfo.values()) minX = min(graphInfo['minX'] for graphInfo in allGraphInfo.values()) ma...
can see where the # sequence ends (as all panel graphs have the same width and we # otherwise couldn't tell). sequenceLen = titleAlignments.subjectLength if logLinearXAxis: sequenceLen = allGraphInfo[title]['adjustOffset'](sequenceLen) a.axvline(x=sequenceLen, color='#cccccc') # Hide the final panel graphs (if any) tha...
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, showOrfs=True): """ Produces an HTML index file in C{outputDir} and a collection of alignmen...
axis. @param logLinearXAxis: If C{True}, convert read offsets so that empty regions in the plots we're preparing will only be as wide as their logged actual values. @param logBase: The logarithm base to use if logLinearXAxis is C{True}. @param: rankScores: If C{True}, change the scores for the reads for each title to b...
not yet implemented.') titles = titlesAlignments.sortTitles(sortOn) if os.access(outputDir, os.F_OK): # outputDir exists. Check it's a directory. if not S_ISDIR(os.stat(outputDir).st_mode): raise ValueError("%r is not a directory." % outputDir) else: if outputDir is None: raise ValueError("The outputDir needs to be spe...
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}, (se...
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[title] row, col = next(coords) hspCount = titleAlignments.hspCount() if hspCo...
= next(coords) a = ax[row][col] a.axis([0, maxHsps, 0, maxScore]) # a.set_yscale('log') a.set_yticks([]) a.set_xticks([]) # Hide the final panel graphs (if any) that have no content. We do this # because the panel is a rectangular grid and some of the plots at the # end of the last row may be unused. for row, col in co...
def scatterAlign(seq1, seq2, window=7): """ Visually align two sequences. """ 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 uni...
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} ...
the corresponding property value according to sequence position. """ 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 for index, propertyName i...
def plotAAClusters(sequence, propertyNames, showLines=True, showFigure=True): """ Plot amino acid property cluster numbers 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_CL...
of the corresponding property value according to sequence position. """ MISSING_AA_VALUE = 0 propertyClusters = clustersForSequence(sequence, propertyNames, missingAAValue=MISSING_AA_VALUE) if showFigure: minCluster = 1 maxCluster = -1 legend = [] x = np.arange(0, len(sequence)) plot = plt.plot if showLines else plt.sc...
def byteorder(bv_di, bv_do, REVERSE=True): """ Reverses the byte order of an input bit-vector bv_di - (i) input bit-vector bv_do - (o) output bit-vector """ BITS = len(bv_di) assert (BITS % 8)==0, "byteorder: expects len(bv_in)=8*x, but len(bv_in)={}".format(BITS) if REVERSE: BYTES = BITS//8 y = ConcatSignal(*[bv_di(8*...
def task_loop(tasks, execute, wait=None, store=TaskStore()): """ The inner task loop for a task runner. execute: A function that runs a task. It should take a task as its sole argument, and may optionally return a TaskResult. wait: (optional, None) A function to run whenever there aren't any runnable tasks (but there a...
Scheduler(tasks, completed=completed, failed=failed) as scheduler: while not scheduler.is_finished(): task = scheduler.start_task() while task is not None: # Collect any dependent results args, kwargs = collect(task) func = partial(task.function, *args, **kwargs) if task.handler: func = partial(task.handler, func) resu...
def findOrDie(s): """ Look up an amino acid. @param s: A C{str} amino acid specifier. This may be a full name, a 3-letter abbreviation or a 1-letter abbreviation. Case is ignored. @return: An C{AminoAcid} instance, if one can be found. Else exit. """ aa = find(s) if aa: return aa else: print('Unknown amino acid or codo...
def http_download(url, download_file, overwrite=False, raise_http_exception=True): """Download a file over HTTP(S). See: http://stackoverflow.com/a/13137873/5651021 Parameters ---------- url : str The URL. download_file : str The path of the local file to write to. overwrite : bool, optional Whether to overwrite an exi...
if r.status_code == 200: with open(download_file, 'wb') as fh: r.raw.decode_content = True shutil.copyfileobj(r.raw, fh) _logger.info('Downloaded file "%s".', download_file) else: _logger.error('Failed to download url "%s": HTTP status %d/%s', url, r.status_code, r.reason)
def ftp_download(url, download_file, if_exists='error', user_name='anonymous', password='', blocksize=4194304): """Downloads a file from an FTP server. Parameters ---------- url : str The URL of the file to download. download_file : str The path of the local file to download to. if_exists : str, optional Desired behavi...
isinstance(download_file, (str, _oldstr)) assert isinstance(if_exists, (str, _oldstr)) assert isinstance(user_name, (str, _oldstr)) assert isinstance(password, (str, _oldstr)) u = urlparse.urlparse(url) assert u.scheme == 'ftp' if if_exists not in ['error', 'skip', 'overwrite']: raise ValueError('"if_exists" must be "e...
def get_cdna_url(species, release=None, ftp=None): """Returns the URL for a cDNA file hosted on the Ensembl FTP server. Parameters ---------- species: str The scientific name of the species. It should be all lower-case, and the genus and species parts should be separated by an underscore (e.g., "homo_sapiens"). release...
close_connection = True # determine latest release, if necessary if release is None: release = util.get_latest_release(ftp=ftp) # check if species exists fasta_dir = '/pub/release-%d/fasta' % release ftp.cwd(fasta_dir) if not species in ftp.nlst(): logger.error('Species "%s" not found on Ensembl FTP server.', species) ...
def write_pickle(self, path, compress=False): """Serialize the current `GOParser` object and store it in a pickle file. Parameters ---------- path: str Path of the output file. compress: bool, optional Whether to compress the file using gzip. Returns ------- None Notes ----- Compression with gzip is significantly slowe...
def read_pickle(fn): """Load a GOParser object from a pickle file. The function automatically detects whether the file is compressed with gzip. Parameters ---------- fn: str Path of the pickle file. Returns ------- `GOParser` The GOParser object stored in the pickle file. """ with misc.open_plain_or_gzip(fn, 'rb') as f...
def get_term_by_name(self, name): """Get the GO term with the given GO term name. If the given name is not associated with any GO term, the function will search for it among synonyms. Parameters ---------- name: str The name of the GO term. Returns ------- `GOTerm` The GO term with the given name. Raises ------ ValueEr...
def read_obo(cls, path, flatten=True, part_of_cc_only=False): """ Parse an OBO file and store GO term information. Parameters ---------- path: str Path of the OBO file. flatten: bool, optional If set to False, do not generate a list of all ancestors and descendants for each GO term. part_of_cc_only: bool, optional Lega...
= None is_a = set() part_of = set() l = next(fh) while l != '\n': if l.startswith('alt_id:'): alt_id[l[8:-1]] = id_ elif l.startswith('def: '): idx = l[6:].index('"') def_ = l[6:(idx+6)] elif l.startswith('is_a:'): is_a.add(l[6:16]) elif l.startswith('synonym:'): idx = l[10:].index('"') if l[(10+idx+2):].startswith("EX...
def _flatten_descendants(self, include_parts=True): """Determines and stores all descendants of each GO term. Parameters ---------- include_parts: bool, optional Whether to include ``part_of`` relations in determining descendants. Returns ------- None """ def get_all_descendants(term): descendants = set() for id_ in te...
def create_instance(self, credentials, name, **kwargs): """Create an instance based on the configuration data. TODO: docstring""" op_name = create_instance( credentials, self.project, self.zone, name, machine_type=self.machine_type, disk_size_gb=self.disk_size_gb, **kwargs) return op_name
def delete_instance(self, credentials, name, **kwargs): """Delete an instance based on the configuration data. TODO: docstring""" op_name = delete_instance( credentials, self.project, self.zone, name, **kwargs) return op_name
def wait_for_instance_deletion(self, credentials, name, **kwargs): """Wait for deletion of instance based on the configuration data. TODO: docstring""" op_name = wait_for_instance_deletion( credentials, self.project, self.zone, name, **kwargs) return op_name
def get_cytoband_names(): """Returns the names of available cytoband data files >> get_cytoband_names() ['ucsc-hg38', 'ucsc-hg19'] """ return [ n.replace(".json.gz", "") for n in pkg_resources.resource_listdir(__name__, _data_dir) if n.endswith(".json.gz") ]
def get_cytoband_map(name): """Fetch one cytoband map by name >>> map = get_cytoband_map("ucsc-hg38") >>> map["1"]["p32.2"] [55600000, 58500000, 'gpos50'] """ fn = pkg_resources.resource_filename( __name__, _data_path_fmt.format(name=name)) return json.load(gzip.open(fn, mode="rt", encoding="utf-8"))
def get_cytoband_maps(names=[]): """Load all cytoband maps >>> maps = get_cytoband_maps() >>> maps["ucsc-hg38"]["1"]["p32.2"] [55600000, 58500000, 'gpos50'] >>> maps["ucsc-hg19"]["1"]["p32.2"] [56100000, 59000000, 'gpos50'] """ if names == []: names = get_cytoband_names() return {name: get_cytoband_map(name) for name i...
def get_relative_file_path(absolute_file_path): ''' Example: absolute_file_path = "/home/xxx/Dev/openfisca/openfisca-france/openfisca_france/param/param.xml" result = "openfisca_france/param/param.xml" ''' global country_package_dir_path assert country_package_dir_path is not None relative_file_path = absolute_file_pat...
def load_environment(global_conf, app_conf): """Configure the application environment.""" conf.update(strings.deep_decode(global_conf)) conf.update(strings.deep_decode(app_conf)) conf.update(conv.check(conv.struct( { 'app_conf': conv.set_value(app_conf), 'app_dir': conv.set_value(app_dir), 'country_package': conv.pipe(...
if extensions is not None: for extension in extensions: tax_benefit_system.load_extension(extension) class Scenario(tax_benefit_system.Scenario): instance_and_error_couple_cache = {} if conf['debug'] else weakref.WeakValueDictionary() # class attribute @classmethod def make_json_to_cached_or_new_instance(cls, ctx, repa...
reformed_tbs.full_key model.reforms[key] = reform model.reformed_tbs[full_key] = reformed_tbs log.debug(u'Cache default decomposition.') if tax_benefit_system.decomposition_file_path is not None: # Ignore the returned value, because we just want to pre-compute the cache. model.get_cached_or_new_decomposition_json(tax_b...
parameters if not conf['debug']: # Do this after tax_benefit_system.get_legislation(). log.debug(u'Compute and cache compact legislation for each first day of month since at least 2 legal years.') today = periods.instant(datetime.date.today()) first_day_of_year = today.offset('first-of', 'year') instant = first_day_of_...
def filter_genes(self, gene_names : Iterable[str]): """Filter the expression matrix against a set of genes. Parameters ---------- gene_names: list of str The genome to filter the genes against. Returns ------- ExpMatrix The filtered expression matrix. """ filt = self.loc[self.index & gene_names] return filt
def read_tsv(cls, filepath_or_buffer: str, gene_table: ExpGeneTable = None, encoding='UTF-8'): """Read expression profile from a tab-delimited text file. Parameters ---------- path: str The path of the text file. gene_table: `ExpGeneTable` object, optional The set of valid genes. If given, the genes in the text file wi...
def write_tsv(self, path, encoding='UTF-8'): """Write expression matrix to a tab-delimited text file. Parameters ---------- path: str The path of the output file. encoding: str, optional The file encoding. ("UTF-8") Returns ------- None """ assert isinstance(path, (str, _oldstr)) assert isinstance(encoding, (str, _olds...
def setup_storage(self): """Save existing FileField storages and patch them with test instance(s). If storage_per_field is False (default) this function will create a single instance here and assign it to self.storage to be used for all filefields. If storage_per_field is True, an independent storage instance will be u...
def run_fastqc(credentials, instance_config, instance_name, script_dir, input_file, output_dir, self_destruct=True, **kwargs): """Run FASTQC. TODO: docstring""" template = _TEMPLATE_ENV.get_template('fastqc.sh') startup_script = template.render( script_dir=script_dir, input_file=input_file, output_dir=output_dir, self_...
def sra_download_paired_end(credentials, instance_config, instance_name, script_dir, sra_run_acc, output_dir, **kwargs): """Download paired-end reads from SRA and convert to gzip'ed FASTQ files. TODO: docstring""" template = _TEMPLATE_ENV.get_template('sra_download_paired-end.sh') startup_script = template.render( scri...
def trim_fastq(credentials, instance_config, instance_name, script_dir, input_file, output_file, trim_crop, trim_headcrop=0, self_destruct=True, **kwargs): """Trims a FASTQ file. TODO: docstring""" template = _TEMPLATE_ENV.get_template('trim_fastq.sh') startup_script = template.render( script_dir=script_dir, input_file...
def _runshell(cmd, exception): """ Run a shell command. if fails, raise a proper exception. """ p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.wait() != 0: raise BridgeException(exception) return p
def addif(self, iname): """ Add an interface to the bridge """ _runshell([brctlexe, 'addif', self.name, iname], "Could not add interface %s to %s." % (iname, self.name))
def delif(self, iname): """ Delete an interface from the bridge. """ _runshell([brctlexe, 'delif', self.name, iname], "Could not delete interface %s from %s." % (iname, self.name))
def hairpin(self, port, val=True): """ Turn harpin on/off on a port. """ if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'hairpin', self.name, port, state], "Could not set hairpin in port %s in %s." % (port, self.name))
def stp(self, val=True): """ Turn STP protocol on/off. """ if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'stp', self.name, state], "Could not set stp on %s." % self.name)
def setageing(self, time): """ Set bridge ageing time. """ _runshell([brctlexe, 'setageing', self.name, str(time)], "Could not set ageing time in %s." % self.name)
def setbridgeprio(self, prio): """ Set bridge priority value. """ _runshell([brctlexe, 'setbridgeprio', self.name, str(prio)], "Could not set bridge priority in %s." % self.name)
def setfd(self, time): """ Set bridge forward delay time value. """ _runshell([brctlexe, 'setfd', self.name, str(time)], "Could not set forward delay in %s." % self.name)
def sethello(self, time): """ Set bridge hello time value. """ _runshell([brctlexe, 'sethello', self.name, str(time)], "Could not set hello time in %s." % self.name)
def setmaxage(self, time): """ Set bridge max message age time. """ _runshell([brctlexe, 'setmaxage', self.name, str(time)], "Could not set max message age in %s." % self.name)
def setpathcost(self, port, cost): """ Set port path cost value for STP protocol. """ _runshell([brctlexe, 'setpathcost', self.name, port, str(cost)], "Could not set path cost in port %s in %s." % (port, self.name))
def setportprio(self, port, prio): """ Set port priority value. """ _runshell([brctlexe, 'setportprio', self.name, port, str(prio)], "Could not set priority in port %s in %s." % (port, self.name))
def _show(self): """ Return a list of unsorted bridge details. """ p = _runshell([brctlexe, 'show', self.name], "Could not show %s." % self.name) return p.stdout.read().split()[7:]
def addbr(self, name): """ Create a bridge and set the device up. """ _runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % name) return Bridge(name)
def delbr(self, name): """ Set the device down and delete the bridge. """ self.getbr(name) # Check if exists _runshell([ipexe, 'link', 'set', 'dev', name, 'down'], "Could not set link down for %s." % name) _runshell([brctlexe, 'delbr', name], "Could not delete bridge %s." % name)
def showall(self): """ Return a list of all available bridges. """ p = _runshell([brctlexe, 'show'], "Could not show bridges.") wlist = map(str.split, p.stdout.read().splitlines()[1:]) brwlist = filter(lambda x: len(x) != 1, wlist) brlist = map(lambda x: x[0], brwlist) return map(Bridge, brlist)
def getbr(self, name): """ Return a bridge object.""" for br in self.showall(): if br.name == name: return br raise BridgeException("Bridge does not exist.")
def clean(self, value): """Take a dirty value and clean it.""" if ( self.base_type is not None and value is not None and not isinstance(value, self.base_type) ): if isinstance(self.base_type, tuple): allowed_types = [typ.__name__ for typ in self.base_type] allowed_types_text = ' or '.join(allowed_types) else: allowed_t...
def clean_new(self, value): """Return a new object instantiated with cleaned data.""" value = self.schema_class(value).full_clean() return self.object_class(**value)
def clean_existing(self, value): """Clean the data and return an existing document with its fields updated based on the cleaned values. """ existing_pk = value[self.pk_field] try: obj = self.fetch_existing(existing_pk) except ReferenceNotFoundError: raise ValidationError('Object does not exist.') orig_data = self.get_o...
def get_fields(cls): """ Returns a dictionary of fields and field instances for this schema. """ fields = {} for field_name in dir(cls): if isinstance(getattr(cls, field_name), Field): field = getattr(cls, field_name) field_name = field.field_name or field_name fields[field_name] = field return fields
def obj_to_dict(cls, obj): """ Takes a model object and converts it into a dictionary suitable for passing to the constructor's data attribute. """ data = {} for field_name in cls.get_fields(): try: value = getattr(obj, field_name) except AttributeError: # If the field doesn't exist on the object, fail gracefully # and...
def toarray(self): """ Return transformations as an array with shape (n,x1,x2,...) where n is the number of images, and remaining dimensions depend on the particular transformations """ return asarray([value.toarray() for (key, value) in sorted(self.transformations.items())])
def transform(self, images): """ Apply the transformation to an Images object. Will apply the underlying dictionary of transformations to the images or volumes of the Images object. The dictionary acts as a lookup table specifying which transformation should be applied to which record of the Images object based on the ...
def load_module_in_background(name, package=None, debug='DEBUG', env=None, replacements=None): """Entry point for loading modules in background thread. Parameters ---------- name : str Module name to load in background thread. package : str or None, optional Package name, has the same meaning as in importlib.import_mod...
in sys.modules or a proxy module that will block until delay attribute access until the module is fully loaded. """ modname = resolve_name(name, package) if modname in sys.modules: return sys.modules[modname] if env is None: try: import builtins env = getattr(builtins, '__xonsh_env__', os.environ) except: return os.env...