_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37800 | WeatherReport.parse_xml_data | train | def parse_xml_data(self):
"""
Parses `xml_data` and loads it into object properties.
"""
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').t... | python | {
"resource": ""
} |
q37801 | WeatherReportSet.download_data | train | def download_data(self, mock_response=None):
"""
Loads XML data into the `xml_data` attribute.
"""
if mock_response is not None:
body = mock_response
else:
api_url = self.get_api_url()
body = urlopen(api_url).read()
xml_root = ElementTr... | python | {
"resource": ""
} |
q37802 | sequenceCategoryLengths | train | 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 sequen... | python | {
"resource": ""
} |
q37803 | simplifyTitle | train | 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.,
# S... | python | {
"resource": ""
} |
q37804 | DUTer._enableTracesVerilog | train | def _enableTracesVerilog(self, verilogFile):
''' 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... | python | {
"resource": ""
} |
q37805 | Scheduler.add_task | train | def add_task(self, task):
"""
Add a task to the scheduler.
task: The task to add.
"""
if not self._valid_name(task.name):
raise ValueError(task.name)
self._tasks[task.name] = task
incomplete_dependencies = set()
for dependency in task.depen... | python | {
"resource": ""
} |
q37806 | Scheduler.end_task | train | 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.
"""
self._running.remove(name)
if success:
... | python | {
"resource": ""
} |
q37807 | main | train | 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 em... | python | {
"resource": ""
} |
q37808 | create_instance | train | 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.
... | python | {
"resource": ""
} |
q37809 | SAMFilter.referenceLengths | train | 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... | python | {
"resource": ""
} |
q37810 | main | train | 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.
R... | python | {
"resource": ""
} |
q37811 | QueryManager.version | train | def version(self):
"""Version of UniPort knowledgebase
:returns: dictionary with version info
:rtype: dict
"""
return [x for x in self.session.query(models.Version).all()] | python | {
"resource": ""
} |
q37812 | IxePort.write | train | def write(self):
""" Write configuration to chassis.
Raise StreamWarningsError if configuration warnings found.
"""
self.ix_command('write')
stream_warnings = self.streamRegion.generateWarningList()
warnings_list = (self.api.call('join ' + ' {' + stream_warnings + '} ' ... | python | {
"resource": ""
} |
q37813 | IxePort.load_config | train | 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:
... | python | {
"resource": ""
} |
q37814 | IxePort.save_config | train | 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:
... | python | {
"resource": ""
} |
q37815 | IxePort.start_transmit | train | def start_transmit(self, blocking=False):
""" Start transmit on port.
:param blocking: True - wait for traffic end, False - return after traffic start.
"""
self.session.start_transmit(blocking, False, self) | python | {
"resource": ""
} |
q37816 | IxePort.stop_capture | train | 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
... | python | {
"resource": ""
} |
q37817 | IxePort.set_transmit_mode | train | def set_transmit_mode(self, mode):
""" set port transmit mode
:param mode: request transmit mode
:type mode: ixexplorer.ixe_port.IxeTransmitMode
"""
self.api.call_rc('port setTransmitMode {} {}'.format(mode, self.uri)) | python | {
"resource": ""
} |
q37818 | get_template_context | train | 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."""
context = {
"container": container,
"classes": classes,
"a... | python | {
"resource": ""
} |
q37819 | CrossCorr.fit | train | 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
---------... | python | {
"resource": ""
} |
q37820 | CrossCorr.fit_and_transform | train | 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
... | python | {
"resource": ""
} |
q37821 | get_settings_from_environment | train | def get_settings_from_environment(environ):
'''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
... | python | {
"resource": ""
} |
q37822 | filter_variance | train | 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.
"""
as... | python | {
"resource": ""
} |
q37823 | filter_mean | train | 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.
"""
... | python | {
"resource": ""
} |
q37824 | filter_percentile | train | 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 ... | python | {
"resource": ""
} |
q37825 | _transform_chrom | train | def _transform_chrom(chrom):
"""Helper function to obtain specific sort order."""
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 v... | python | {
"resource": ""
} |
q37826 | get_chromosome_lengths | train | def get_chromosome_lengths(fasta_file, fancy_sort=True):
"""Extract chromosome lengths from genome FASTA file."""
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.se... | python | {
"resource": ""
} |
q37827 | resolve_schema | train | 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 JS... | python | {
"resource": ""
} |
q37828 | _merge_dicts | train | def _merge_dicts(first, second):
"""Merge the 'second' multiple-dictionary into the 'first' one."""
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... | python | {
"resource": ""
} |
q37829 | read_colorscale | train | 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 ... | python | {
"resource": ""
} |
q37830 | make_router | train | def make_router():
"""Return a WSGI application that searches requests to controllers """
global router
routings = [
('GET', '^/$', index),
('GET', '^/api/?$', index),
('POST', '^/api/1/calculate/?$', calculate.api1_calculate),
('GET', '^/api/2/entities/?$', entities.api2_ent... | python | {
"resource": ""
} |
q37831 | InvenioJSONSchemasState.register_schemas_dir | train | 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 == '.':
... | python | {
"resource": ""
} |
q37832 | InvenioJSONSchemasState.register_schema | train | 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) | python | {
"resource": ""
} |
q37833 | InvenioJSONSchemasState.get_schema_dir | train | 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.
... | python | {
"resource": ""
} |
q37834 | InvenioJSONSchemasState.get_schema_path | train | 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.
... | python | {
"resource": ""
} |
q37835 | InvenioJSONSchemasState.get_schema | train | 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_RESOLVE... | python | {
"resource": ""
} |
q37836 | InvenioJSONSchemasState.url_to_path | train | 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)
... | python | {
"resource": ""
} |
q37837 | InvenioJSONSchemasState.path_to_url | train | 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['JS... | python | {
"resource": ""
} |
q37838 | InvenioJSONSchemasState.loader_cls | train | 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 | python | {
"resource": ""
} |
q37839 | scatterAlign | train | 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].ap... | python | {
"resource": ""
} |
q37840 | plotAAProperties | train | 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{d... | python | {
"resource": ""
} |
q37841 | plotAAClusters | train | 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 ... | python | {
"resource": ""
} |
q37842 | task_loop | train | 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
... | python | {
"resource": ""
} |
q37843 | findOrDie | train | 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:
retu... | python | {
"resource": ""
} |
q37844 | ftp_download | train | 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... | python | {
"resource": ""
} |
q37845 | get_cdna_url | train | 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 underscor... | python | {
"resource": ""
} |
q37846 | GeneOntology.write_pickle | train | 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.
Ret... | python | {
"resource": ""
} |
q37847 | GeneOntology.read_pickle | train | 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`
... | python | {
"resource": ""
} |
q37848 | GeneOntology._flatten_descendants | train | 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
-------... | python | {
"resource": ""
} |
q37849 | InstanceConfig.wait_for_instance_deletion | train | 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 | python | {
"resource": ""
} |
q37850 | get_cytoband_names | train | 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")
] | python | {
"resource": ""
} |
q37851 | get_cytoband_map | train | 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",... | python | {
"resource": ""
} |
q37852 | get_cytoband_maps | train | 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()
re... | python | {
"resource": ""
} |
q37853 | ExpProfile.filter_genes | train | 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 expre... | python | {
"resource": ""
} |
q37854 | ExpProfile.read_tsv | train | 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, op... | python | {
"resource": ""
} |
q37855 | run_fastqc | train | 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_d... | python | {
"resource": ""
} |
q37856 | sra_download_paired_end | train | 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-e... | python | {
"resource": ""
} |
q37857 | _runshell | train | 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 | python | {
"resource": ""
} |
q37858 | Bridge.addif | train | 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)) | python | {
"resource": ""
} |
q37859 | Bridge.delif | train | 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)) | python | {
"resource": ""
} |
q37860 | Bridge.setageing | train | def setageing(self, time):
""" Set bridge ageing time. """
_runshell([brctlexe, 'setageing', self.name, str(time)],
"Could not set ageing time in %s." % self.name) | python | {
"resource": ""
} |
q37861 | Bridge.setbridgeprio | train | def setbridgeprio(self, prio):
""" Set bridge priority value. """
_runshell([brctlexe, 'setbridgeprio', self.name, str(prio)],
"Could not set bridge priority in %s." % self.name) | python | {
"resource": ""
} |
q37862 | Bridge.setfd | train | 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) | python | {
"resource": ""
} |
q37863 | Bridge.sethello | train | 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) | python | {
"resource": ""
} |
q37864 | Bridge.setmaxage | train | 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) | python | {
"resource": ""
} |
q37865 | Bridge.setpathcost | train | 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)) | python | {
"resource": ""
} |
q37866 | Bridge.setportprio | train | 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)) | python | {
"resource": ""
} |
q37867 | Bridge._show | train | 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:] | python | {
"resource": ""
} |
q37868 | BridgeController.addbr | train | 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) | python | {
"resource": ""
} |
q37869 | BridgeController.delbr | train | 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 bri... | python | {
"resource": ""
} |
q37870 | BridgeController.showall | train | 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... | python | {
"resource": ""
} |
q37871 | BridgeController.getbr | train | 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.") | python | {
"resource": ""
} |
q37872 | Field.clean | train | 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__ fo... | python | {
"resource": ""
} |
q37873 | EmbeddedReference.clean_new | train | 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) | python | {
"resource": ""
} |
q37874 | EmbeddedReference.clean_existing | train | 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:
... | python | {
"resource": ""
} |
q37875 | Schema.get_fields | train | 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... | python | {
"resource": ""
} |
q37876 | Schema.obj_to_dict | train | 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)
... | python | {
"resource": ""
} |
q37877 | RegistrationModel.transform | train | 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 ... | python | {
"resource": ""
} |
q37878 | load_module_in_background | train | 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
... | python | {
"resource": ""
} |
q37879 | TokenProvider.get_token | train | def get_token(self):
"""Performs Neurio API token authentication using provided key and secret.
Note:
This method is generally not called by hand; rather it is usually
called as-needed by a Neurio Client object.
Returns:
string: the access token
"""
if self.__token is not None:
... | python | {
"resource": ""
} |
q37880 | Client.__append_url_params | train | def __append_url_params(self, url, params):
"""Utility method formatting url request parameters."""
url_parts = list(urlparse(url))
query = dict(parse_qsl(url_parts[4]))
query.update(params)
url_parts[4] = urlencode(query)
return urlunparse(url_parts) | python | {
"resource": ""
} |
q37881 | Client.get_appliance | train | def get_appliance(self, appliance_id):
"""Get the information for a specified appliance
Args:
appliance_id (string): identifiying string of appliance
Returns:
list: dictionary object containing information about the specified appliance
"""
url = "https://api.neur.io/v1/appliances/%s"%(... | python | {
"resource": ""
} |
q37882 | Client.get_appliances | train | def get_appliances(self, location_id):
"""Get the appliances added for a specified location.
Args:
location_id (string): identifiying string of appliance
Returns:
list: dictionary objects containing appliances data
"""
url = "https://api.neur.io/v1/appliances"
headers = self.__gen... | python | {
"resource": ""
} |
q37883 | Client.get_appliance_event_after_time | train | def get_appliance_event_after_time(self, location_id, since, per_page=None, page=None, min_power=None):
"""Get appliance events by location Id after defined time.
Args:
location_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
since (string):... | python | {
"resource": ""
} |
q37884 | Client.get_appliance_stats_by_location | train | def get_appliance_stats_by_location(self, location_id, start, end, granularity=None, per_page=None, page=None,
min_power=None):
"""Get appliance usage data for a given location within a given time range.
Stats are generated by fetching appliance events that match the suppli... | python | {
"resource": ""
} |
q37885 | Client.get_samples_live | train | def get_samples_live(self, sensor_id, last=None):
"""Get recent samples, one sample per second for up to the last 2 minutes.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
last (string): starting range, as ISO8601 timestamp
Returns:
l... | python | {
"resource": ""
} |
q37886 | Client.get_samples_live_last | train | def get_samples_live_last(self, sensor_id):
"""Get the last sample recorded by the sensor.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
``0x0013A20040B65FAD``
Returns:
list: dictionary objects containing sample data
"""
url = "https://api.neur.io/v1/sam... | python | {
"resource": ""
} |
q37887 | Client.get_samples | train | def get_samples(self, sensor_id, start, granularity, end=None,
frequency=None, per_page=None, page=None,
full=False):
"""Get a sensor's samples for a specified time interval.
Args:
sensor_id (string): hexadecimal id of the sensor to query, e.g.
... | python | {
"resource": ""
} |
q37888 | Client.get_user_information | train | def get_user_information(self):
"""Gets the current user information, including sensor ID
Args:
None
Returns:
dictionary object containing information about the current user
"""
url = "https://api.neur.io/v1/users/current"
headers = self.__gen_headers()
headers["Content-Type"]... | python | {
"resource": ""
} |
q37889 | api2_formula | train | def api2_formula(req):
"""
A simple `GET`-, URL-based API to OpenFisca, making the assumption of computing formulas for a single person.
Combination
-----------
You can compute several formulas at once by combining the paths and joining them with `+`.
Example:
```
/salaire_super_brut+salaire_net_a_payer?salaire_... | python | {
"resource": ""
} |
q37890 | arithmetic_mean4 | train | def arithmetic_mean4(rst, clk, rx_rdy, rx_vld, rx_dat, tx_rdy, tx_vld, tx_dat):
''' Calculates the arithmetic mean of every 4 consecutive input numbers
Input handshake & data
rx_rdy - (o) Ready
rx_vld - (i) Valid
rx_dat - (i) Data
Output handshake & data
... | python | {
"resource": ""
} |
q37891 | pipeline_control_stop_tx | train | def pipeline_control_stop_tx():
''' Instantiates the arithmetic_mean4 pipeline, feeds it with data and drains its output '''
clk = sim.Clock(val=0, period=10, units="ns")
rst = sim.ResetSync(clk=clk, val=0, active=1)
rx_rdy, rx_vld, tx_rdy, tx_vld = [Signal(bool(0)) for _ in range(4)]
rx_dat = Sig... | python | {
"resource": ""
} |
q37892 | MongoEmbedded.clean | train | def clean(self, value):
"""Clean the provided dict of values and then return an
EmbeddedDocument instantiated with them.
"""
value = super(MongoEmbedded, self).clean(value)
return self.document_class(**value) | python | {
"resource": ""
} |
q37893 | MongoReference.fetch_object | train | def fetch_object(self, doc_id):
"""Fetch the document by its PK."""
try:
return self.object_class.objects.get(pk=doc_id)
except self.object_class.DoesNotExist:
raise ReferenceNotFoundError | python | {
"resource": ""
} |
q37894 | get_argument_parser | train | def get_argument_parser():
"""Create the argument parser for the script.
Parameters
----------
Returns
-------
`argparse.ArgumentParser`
The arguemnt parser.
"""
desc = 'Generate a sample sheet based on a GEO series matrix.'
parser = cli.get_argument_parser(desc=desc)
... | python | {
"resource": ""
} |
q37895 | read_series_matrix | train | def read_series_matrix(path, encoding):
"""Read the series matrix."""
assert isinstance(path, str)
accessions = None
titles = None
celfile_urls = None
with misc.smart_open_read(path, mode='rb', try_gzip=True) as fh:
reader = csv.reader(fh, dialect='excel-tab', encoding=encoding)
... | python | {
"resource": ""
} |
q37896 | write_sample_sheet | train | def write_sample_sheet(path, accessions, names, celfile_urls, sel=None):
"""Write the sample sheet."""
with open(path, 'wb') as ofh:
writer = csv.writer(ofh, dialect='excel-tab',
lineterminator=os.linesep,
quoting=csv.QUOTE_NONE)
# write he... | python | {
"resource": ""
} |
q37897 | create_blueprint | train | def create_blueprint(state):
"""Create blueprint serving JSON schemas.
:param state: :class:`invenio_jsonschemas.ext.InvenioJSONSchemasState`
instance used to retrieve the schemas.
"""
blueprint = Blueprint(
'invenio_jsonschemas',
__name__,
)
@blueprint.route('/<path:sc... | python | {
"resource": ""
} |
q37898 | printBlastRecord | train | def printBlastRecord(record):
"""
Print a BLAST record.
@param record: A BioPython C{Bio.Blast.Record.Blast} instance.
"""
for key in sorted(record.__dict__.keys()):
if key not in ['alignments', 'descriptions', 'reference']:
print('%s: %r' % (key, record.__dict__[key]))
prin... | python | {
"resource": ""
} |
q37899 | get_goa_gene_sets | train | def get_goa_gene_sets(go_annotations):
"""Generate a list of gene sets from a collection of GO annotations.
Each gene set corresponds to all genes annotated with a certain GO term.
"""
go_term_genes = OrderedDict()
term_ids = {}
for ann in go_annotations:
term_ids[ann.go_term.id] = ann.... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.