INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Save animation into a movie file.
[NOTE] If 'writer' is not specified, default writer defined in this module
will be used to generate the movie file.
[TODO] Implement docstring inheritance. | def save(self, *args, **kwargs):
"""Save animation into a movie file.
[NOTE] If 'writer' is not specified, default writer defined in this module
will be used to generate the movie file.
[TODO] Implement docstring inheritance.
"""
writer = None
if 'write... |
## Arguments:
- 'args' and 'kwargs' will be passed to 'self.save()' | def show(self, temp_file_name = 'ani.mp4', **kwargs):
"""
## Arguments:
- 'args' and 'kwargs' will be passed to 'self.save()'
"""
## [NOTE] Make this method as a method of base class.
## [NOTE] This should be modified to prevent erasing other existing file with ... |
Initialize a database that store metadata
Check if "root" dir exists, otherwise create the directory and
build the database. If a database already exists, do nothing. | def init(ctx, reset, root, phenomizer):
"""Initialize a database that store metadata
Check if "root" dir exists, otherwise create the directory and
build the database. If a database already exists, do nothing.
"""
configs = {}
if root is None:
root = ctx.obj.get('root') or os.p... |
Return a bytestring representation of the value. | def encode(value, encoding='utf-8', encoding_errors='strict'):
"""
Return a bytestring representation of the value.
"""
if isinstance(value, bytes):
return value
if not isinstance(value, basestring):
value = str(value)
if isinstance(value, unicode):
value = value.encode(e... |
Create nshares of the secret. threshold specifies the number of shares
needed for reconstructing the secret value. A 0-16 bytes identifier must
be provided. Optionally the secret is hashed with the algorithm specified
by hash_id, a class attribute of Hash.
This function must return a list of formatted s... | def share_secret(threshold, nshares, secret, identifier, hash_id=Hash.SHA256):
"""
Create nshares of the secret. threshold specifies the number of shares
needed for reconstructing the secret value. A 0-16 bytes identifier must
be provided. Optionally the secret is hashed with the algorithm specified
... |
Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow) | def _add_gmaf(self, variant_obj, gemini_variant):
"""Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow)
"""
max_af = gemini_variant['max_aaf_all']
if max_af:
max_af = float(max_af)... |
Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow) | def _add_exac(self, variant_obj, gemini_variant):
"""Add the gmaf frequency
Args:
variant_obj (puzzle.models.Variant)
gemini_variant (GeminiQueryRow)
"""
exac = gemini_variant['aaf_exac_all']
if exac:
exac = float(exac)
... |
Get the gene symbols that a interval overlaps | def get_gene_symbols(chrom, start, stop):
"""Get the gene symbols that a interval overlaps"""
gene_symbols = query_gene_symbol(chrom, start, stop)
logger.debug("Found gene symbols: {0}".format(', '.join(gene_symbols)))
return gene_symbols |
Return the genes info based on the transcripts found
Args:
ensembl_ids (Optional[list]): list of Ensembl gene ids
hgnc_symbols (Optional[list]): list of HGNC gene symbols
Returns:
iterable: an iterable with `Gene` objects | def get_gene_info(ensembl_ids=None, hgnc_symbols=None):
"""Return the genes info based on the transcripts found
Args:
ensembl_ids (Optional[list]): list of Ensembl gene ids
hgnc_symbols (Optional[list]): list of HGNC gene symbols
Returns:
iterable: an iterable with `Gene` objects
... |
Get the most severe consequence
Go through all transcripts and get the most severe consequence
Args:
transcripts (list): A list of transcripts to evaluate
Returns:
most_severe_consequence (str): The most severe consequence | def get_most_severe_consequence(transcripts):
"""Get the most severe consequence
Go through all transcripts and get the most severe consequence
Args:
transcripts (list): A list of transcripts to evaluate
Returns:
most_severe_consequence (str): The most severe conse... |
Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband | def get_cytoband_coord(chrom, pos):
"""Get the cytoband coordinate for a position
Args:
chrom(str): A chromosome
pos(int): The position
Returns:
cytoband
"""
chrom = chrom.strip('chr')
pos = int(pos)
result = None
logger.debug("Finding Cytoba... |
Do a simple parse of the dotfile mapping, using semicolons to
separate source file name from the target file paths. | def parse_mapping(self, map_path, source=None, dotfiles=None):
"""Do a simple parse of the dotfile mapping, using semicolons to
separate source file name from the target file paths."""
include_re = r"""^\s*#include\s+(".+"|'.+')"""
include_re = re.compile(include_re, re.I)
mappin... |
Run a shell command with the given arguments. | def sh(self, *command, **kwargs):
"""Run a shell command with the given arguments."""
self.log.debug('shell: %s', ' '.join(command))
return subprocess.check_call(' '.join(command),
stdout=sys.stdout,
stderr=sys.stderr,
... |
Run an ssh command using the configured user/server values. | def ssh(self, *command):
"""Run an ssh command using the configured user/server values."""
if self.args.user:
ssh_spec = '{0}@{1}'.format(self.args.user, self.args.server)
else:
ssh_spec = self.args.server
return self.sh('ssh', ssh_spec, *command) |
Copy a local file to the given remote path. | def scp(self, local_file, remote_path=''):
"""Copy a local file to the given remote path."""
if self.args.user:
upload_spec = '{0}@{1}:{2}'.format(self.args.user,
self.args.server,
remote_path)
... |
Start the dotfile deployment process. | def run(self):
"""Start the dotfile deployment process."""
script = path.realpath(__file__)
self.log.debug('Running from %s with arguments: %s', script, self.args)
if self.args.source:
self.source = self.args.source
else:
# hardcoding as the parent-parent... |
Read in the dotfile mapping as a dictionary. | def load_dotfiles(self):
"""Read in the dotfile mapping as a dictionary."""
if self.args.map and path.exists(self.args.map):
dotfiles_path = self.args.map
else:
dotfiles_path = self.source
self.log.debug('Loading dotfile mapping from %s', dotfiles_path)
... |
Clone a repository containing the dotfiles source. | def clone_repo(self):
"""Clone a repository containing the dotfiles source."""
tempdir_path = tempfile.mkdtemp()
if self.args.git:
self.log.debug('Cloning git source repository from %s to %s',
self.source, tempdir_path)
self.sh('git clone', sel... |
Cleanup the temporary directory containing the dotfiles repo. | def cleanup_repo(self):
"""Cleanup the temporary directory containing the dotfiles repo."""
if self.source and path.isdir(self.source):
self.log.debug('Cleaning up source repo from %s', self.source)
shutil.rmtree(self.source) |
Deploy dotfiles using the appropriate method. | def deploy_dotfiles(self, dotfiles):
"""Deploy dotfiles using the appropriate method."""
if self.args.server:
return self.deploy_remote(dotfiles)
else:
return self.deploy_local(dotfiles) |
Deploy dotfiles to a remote server. | def deploy_remote(self, dotfiles):
"""Deploy dotfiles to a remote server."""
tempfile_path = None
tempdir_path = None
try:
tempdir_path = tempfile.mkdtemp()
self.log.debug('Deploying to temp dir %s', tempdir_path)
self.deploy_local(dotfiles, target_ro... |
Deploy dotfiles to a local path. | def deploy_local(self, dotfiles, target_root=None):
"""Deploy dotfiles to a local path."""
if target_root is None:
target_root = self.args.path
for source_path, target_path in dotfiles.items():
source_path = path.join(self.source, source_path)
target_path = p... |
Remove duplicates from a list preserving the order.
We might be tempted to use the list(set(l)) idiom, but it doesn't preserve
the order, which hinders testability and does not work for lists with
unhashable elements. | def dedupe_list(l):
"""Remove duplicates from a list preserving the order.
We might be tempted to use the list(set(l)) idiom, but it doesn't preserve
the order, which hinders testability and does not work for lists with
unhashable elements.
"""
result = []
for el in l:
if el not in... |
Plotting of amino diagrams - circles with residue name and id, colored according to the
residue type. If the protein has more than one chain, chain identity is also included in
the plot. The plot is saved as svg file with residue id and chain id as filename for more
certain identification. | def plot_amino_diagrams(self):
"""
Plotting of amino diagrams - circles with residue name and id, colored according to the
residue type. If the protein has more than one chain, chain identity is also included in
the plot. The plot is saved as svg file with residue id and chain id as file... |
Plotting domain diagrams - a ring around the residue name and id and chain id. The colors are
determined by the chain id and are extracted from matplotlib colormap "terrain" (ver. "09.2016")
The plot is saved as svg file with residue id and chain id as filename for more certain
identification. | def plot_domain_diagrams(self):
"""
Plotting domain diagrams - a ring around the residue name and id and chain id. The colors are
determined by the chain id and are extracted from matplotlib colormap "terrain" (ver. "09.2016")
The plot is saved as svg file with residue id and chain id as... |
Ploting clock diagrams - one or more rings around residue name and id (and chain id).
The rings show the fraction of simulation time this residue has spent in the vicinity of the
ligand - characterised by distance. | def plot_clock_diagrams(self, colormap="summer"):
"""
Ploting clock diagrams - one or more rings around residue name and id (and chain id).
The rings show the fraction of simulation time this residue has spent in the vicinity of the
ligand - characterised by distance.
"""
... |
Create a cases and populate it with individuals
Args:
variant_source (str): Path to vcf files
case_lines (Iterable): Ped like lines
case_type (str): Format of case lines
Returns:
case_objs (list(puzzle.models.Case)) | def get_cases(variant_source, case_lines=None, case_type='ped',
variant_type='snv', variant_mode='vcf'):
"""Create a cases and populate it with individuals
Args:
variant_source (str): Path to vcf files
case_lines (Iterable): Ped like lines
... |
Get the individuals from a vcf file, gemini database, and/or a ped file.
Args:
variant_source (str): Path to a variant source
case_lines(Iterable): Ped like lines
case_type(str): Format of ped lines
Returns:
individuals (generator... | def get_individuals(variant_source, case_lines=None, case_type='ped', variant_mode='vcf'):
"""Get the individuals from a vcf file, gemini database, and/or a ped file.
Args:
variant_source (str): Path to a variant source
case_lines(Iterable): Ped like lines
... |
Process UDP messages | def handle_message(self, message):
"""Process UDP messages"""
if self._yamaha:
if 'power' in message:
_LOGGER.debug("Power: %s", message.get('power'))
self._yamaha.power = (
STATE_ON if message.get('power') == "on" else STATE_OFF)
... |
Updates the zone status. | def update_status(self, new_status=None):
"""Updates the zone status."""
_LOGGER.debug("update_status: Zone %s", self.zone_id)
if self.status and new_status is None:
_LOGGER.debug("Zone: healthy.")
else:
old_status = self.status or {}
if new_status:
... |
Get status from device | def get_status(self):
"""Get status from device"""
req_url = ENDPOINTS["getStatus"].format(self.ip_address, self.zone_id)
return request(req_url) |
Send Power command. | def set_power(self, power):
"""Send Power command."""
req_url = ENDPOINTS["setPower"].format(self.ip_address, self.zone_id)
params = {"power": "on" if power else "standby"}
return request(req_url, params=params) |
Send mute command. | def set_mute(self, mute):
"""Send mute command."""
req_url = ENDPOINTS["setMute"].format(self.ip_address, self.zone_id)
params = {"enable": "true" if mute else "false"}
return request(req_url, params=params) |
Send Volume command. | def set_volume(self, volume):
"""Send Volume command."""
req_url = ENDPOINTS["setVolume"].format(self.ip_address, self.zone_id)
params = {"volume": int(volume)}
return request(req_url, params=params) |
Send Input command. | def set_input(self, input_id):
"""Send Input command."""
req_url = ENDPOINTS["setInput"].format(self.ip_address, self.zone_id)
params = {"input": input_id}
return request(req_url, params=params) |
Check if there are any compounds and add them to the variant
The compounds that are added should be sorted on rank score | def _add_compounds(self, variant_obj, info_dict):
"""Check if there are any compounds and add them to the variant
The compounds that are added should be sorted on rank score
"""
compound_list = []
compound_entry = info_dict.get('Compounds')
if compound_entry:... |
Add the cadd score to the variant
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary | def _add_cadd_score(self, variant_obj, info_dict):
"""Add the cadd score to the variant
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
cadd_score = info_dict.get('CADD')
if cadd_score:
log... |
Add the genetic models found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary | def _add_genetic_models(self, variant_obj, info_dict):
"""Add the genetic models found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
genetic_models_entry = info_dict.get('GeneticModels')
if genetic_mode... |
Add the rank score if found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary | def _add_rank_score(self, variant_obj, info_dict):
"""Add the rank score if found
Args:
variant_obj (puzzle.models.Variant)
info_dict (dict): A info dictionary
"""
rank_score_entry = info_dict.get('RankScore')
if rank_score_entry:
... |
r"""
Parse the contents of the file-like object ``fp`` as an XML properties file
and return a `dict` of the key-value pairs.
Beyond basic XML well-formedness, `load_xml` only checks that the root
element is named "``properties``" and that all of its ``<entry>`` children
have ``key`` attributes. No... | def load_xml(fp, object_pairs_hook=dict):
r"""
Parse the contents of the file-like object ``fp`` as an XML properties file
and return a `dict` of the key-value pairs.
Beyond basic XML well-formedness, `load_xml` only checks that the root
element is named "``properties``" and that all of its ``<entr... |
r"""
Parse the contents of the string ``s`` as an XML properties document and
return a `dict` of the key-value pairs.
Beyond basic XML well-formedness, `loads_xml` only checks that the root
element is named "``properties``" and that all of its ``<entry>`` children
have ``key`` attributes. No furth... | def loads_xml(s, object_pairs_hook=dict):
r"""
Parse the contents of the string ``s`` as an XML properties document and
return a `dict` of the key-value pairs.
Beyond basic XML well-formedness, `loads_xml` only checks that the root
element is named "``properties``" and that all of its ``<entry>`` c... |
Write a series ``props`` of key-value pairs to a binary filehandle ``fp``
in the format of an XML properties file. The file will include both an XML
declaration and a doctype declaration.
:param props: A mapping or iterable of ``(key, value)`` pairs to write to
``fp``. All keys and values in ``pr... | def dump_xml(props, fp, comment=None, encoding='UTF-8', sort_keys=False):
"""
Write a series ``props`` of key-value pairs to a binary filehandle ``fp``
in the format of an XML properties file. The file will include both an XML
declaration and a doctype declaration.
:param props: A mapping or itera... |
Configure connection to a SQL database.
Args:
db_uri (str): path/URI to the database to connect to
debug (Optional[bool]): whether to output logging information | def connect(self, db_uri, debug=False):
"""Configure connection to a SQL database.
Args:
db_uri (str): path/URI to the database to connect to
debug (Optional[bool]): whether to output logging information
"""
kwargs = {'echo': debug, 'convert_unicode': True}
... |
Convert a series ``props`` of key-value pairs to a text string containing
an XML properties document. The document will include a doctype
declaration but not an XML declaration.
:param props: A mapping or iterable of ``(key, value)`` pairs to serialize.
All keys and values in ``props`` must be tex... | def dumps_xml(props, comment=None, sort_keys=False):
"""
Convert a series ``props`` of key-value pairs to a text string containing
an XML properties document. The document will include a doctype
declaration but not an XML declaration.
:param props: A mapping or iterable of ``(key, value)`` pairs t... |
Tear down a database (tables and columns).
Returns:
Store: self | def tear_down(self):
"""Tear down a database (tables and columns).
Returns:
Store: self
"""
# drop/delete the tables
logger.info('resetting database...')
BASE.metadata.drop_all(self.engine)
return self |
Initialize a new database with the default tables and columns.
Returns:
Store: self | def set_up(self, reset=False):
"""Initialize a new database with the default tables and columns.
Returns:
Store: self
"""
if reset:
self.tear_down()
logger.info("Creating database")
# create the tables
BASE.metadata.create_all(self.engine)... |
Select and initialize the correct plugin for the case. | def select_plugin(self, case_obj):
"""Select and initialize the correct plugin for the case."""
if case_obj.variant_mode == 'vcf':
logger.debug("Using vcf plugin")
plugin = VcfPlugin(case_obj.variant_type)
elif case_obj.variant_mode == 'gemini':
logger.debug("... |
Show the landing page. | def index():
"""Show the landing page."""
gene_lists = app.db.gene_lists() if app.config['STORE_ENABLED'] else []
queries = app.db.gemini_queries() if app.config['STORE_ENABLED'] else []
case_groups = {}
for case in app.db.cases():
key = (case.variant_source, case.variant_type, case.variant... |
Show the overview for a case. | def case(case_id):
"""Show the overview for a case."""
case_obj = app.db.case(case_id)
return render_template('case.html', case=case_obj, case_id=case_id) |
Add phenotype(s) to the case model. | def phenotypes():
"""Add phenotype(s) to the case model."""
ind_id = request.form['ind_id']
phenotype_id = request.form['phenotype_id']
if not phenotype_id:
return abort(500, 'no phenotype_id submitted')
ind_obj = app.db.individual(ind_id)
try:
added_terms = app.db.add_phenotyp... |
Delete phenotype from an individual. | def delete_phenotype(phenotype_id):
"""Delete phenotype from an individual."""
ind_id = request.form['ind_id']
ind_obj = app.db.individual(ind_id)
try:
app.db.remove_phenotype(ind_obj, phenotype_id)
except RuntimeError as error:
return abort(500, error.message)
return redirect(re... |
Display or add a gene list. | def gene_list(list_id=None):
"""Display or add a gene list."""
all_case_ids = [case.case_id for case in app.db.cases()]
if list_id:
genelist_obj = app.db.gene_list(list_id)
case_ids = [case.case_id for case in app.db.cases()
if case not in genelist_obj.cases]
if g... |
Delete a whole gene list with links to cases or a link. | def delete_genelist(list_id, case_id=None):
"""Delete a whole gene list with links to cases or a link."""
if case_id:
# unlink a case from a gene list
case_obj = app.db.case(case_id)
app.db.remove_genelist(list_id, case_obj=case_obj)
return redirect(request.referrer)
else:
... |
Upload a new resource for an individual. | def resources():
"""Upload a new resource for an individual."""
ind_id = request.form['ind_id']
upload_dir = os.path.abspath(app.config['UPLOAD_DIR'])
req_file = request.files['file']
filename = secure_filename(req_file.filename)
file_path = os.path.join(upload_dir, filename)
name = request... |
Show a resource. | def resource(resource_id):
"""Show a resource."""
resource_obj = app.db.resource(resource_id)
if 'raw' in request.args:
return send_from_directory(os.path.dirname(resource_obj.path),
os.path.basename(resource_obj.path))
return render_template('resource.html',... |
Delete a resource. | def delete_resource(resource_id):
"""Delete a resource."""
resource_obj = app.db.resource(resource_id)
try:
os.remove(resource_obj.path)
except OSError as err:
app.logger.debug(err.message)
app.db.delete_resource(resource_id)
return redirect(request.referrer) |
Upload a new comment. | def comments(case_id):
"""Upload a new comment."""
text = request.form['text']
variant_id = request.form.get('variant_id')
username = request.form.get('username')
case_obj = app.db.case(case_id)
app.db.add_comment(case_obj, text, variant_id=variant_id, username=username)
return redirect(requ... |
Show details for a specific individual. | def individual(ind_id):
"""Show details for a specific individual."""
individual_obj = app.db.individual(ind_id)
return render_template('individual.html', individual=individual_obj) |
Update the case synopsis. | def synopsis(case_id):
"""Update the case synopsis."""
text = request.form['text']
case_obj = app.db.case(case_id)
app.db.update_synopsis(case_obj, text)
return redirect(request.referrer) |
Make a new case out of a list of individuals. | def add_case():
"""Make a new case out of a list of individuals."""
ind_ids = request.form.getlist('ind_id')
case_id = request.form['case_id']
source = request.form['source']
variant_type = request.form['type']
if len(ind_ids) == 0:
return abort(400, "must add at least one member of cas... |
Dummy print sub.
:param tables: print events of tables. | def print_sub(tables):
"""Dummy print sub.
:param tables: print events of tables.
"""
logger = logging.getLogger("meepo.sub.print_sub")
logger.info("print_sub tables: %s" % ", ".join(tables))
if not isinstance(tables, (list, set)):
raise ValueError("tables should be list or set")
... |
Decode Erlang terms within binary data into Python types | def binary_to_term(data):
"""
Decode Erlang terms within binary data into Python types
"""
if not isinstance(data, bytes):
raise ParseException('not bytes input')
size = len(data)
if size <= 1:
raise ParseException('null input')
if b_ord(data[0]) != _TAG_VERSION:
rais... |
Encode Python types into Erlang terms in binary data | def term_to_binary(term, compressed=False):
"""
Encode Python types into Erlang terms in binary data
"""
data_uncompressed = _term_to_binary(term)
if compressed is False:
return b_chr(_TAG_VERSION) + data_uncompressed
else:
if compressed is True:
compressed = 6
... |
provide file:consult/1 functionality with python types | def consult(string_in):
"""
provide file:consult/1 functionality with python types
"""
# pylint: disable=eval-used
# pylint: disable=too-many-branches
# pylint: disable=too-many-statements
# manually parse textual erlang data to avoid external dependencies
list_out = []
tuple_binary... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
if isinstance(self.value, int):
return b_chr(_TAG_ATOM_CACHE_REF) + b_chr(self.value)
elif isinstance(self.value, TypeUnicode):
value_encoded = self.value.encode('utf-8')
length = len(valu... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
if isinstance(self.value, bytes):
length = len(self.value)
if length > 4294967295:
raise OutputException('uint32 overflow')
elif self.bits != 8:
return (
... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
if isinstance(self.value, list):
length = len(self.value)
if length == 0:
return b_chr(_TAG_NIL_EXT)
elif length > 4294967295:
raise OutputException('uint32 overflo... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PID_EXT) +
self.node.binary() + self.id + self.serial + self.creation
)
elif creat... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
creation_size = len(self.creation)
if creation_size == 1:
return (
b_chr(_TAG_PORT_EXT) +
self.node.binary() + self.id + self.creation
)
elif creation_size == 4... |
return encoded representation | def binary(self):
"""
return encoded representation
"""
length = len(self.id) / 4
if length == 0:
return (
b_chr(_TAG_REFERENCE_EXT) +
self.node.binary() + self.id + self.creation
)
elif length <= 65535:
... |
Serialize a queryset. | def serialize(self, queryset, **options):
"""
Serialize a queryset.
"""
self.options = options
self.stream = options.pop("stream", six.StringIO())
self.selected_fields = options.pop("fields", None)
self.use_natural_foreign_keys = options.pop('use_natural_foreign_... |
Link a resource to an individual. | def add_resource(self, name, file_path, ind_obj):
"""Link a resource to an individual."""
new_resource = Resource(name=name, individual=ind_obj, path=file_path)
self.session.add(new_resource)
self.save()
return new_resource |
Link a resource to an individual. | def delete_resource(self, resource_id):
"""Link a resource to an individual."""
resource_obj = self.resource(resource_id)
logger.debug("Deleting resource {0}".format(resource_obj.name))
self.session.delete(resource_obj)
self.save() |
Parsers a file or string and returns a list of AudioClipSpec
Arguments:
specsFileOrString (str): specifications' file or string
Examples:
>>> SpecsParser.parse('23.4 34.1\n40.2 79.65 Hello World!')
[<AudioClipSpec start:23.40, end:34.10, text:''>,
... | def parse(cls, specsFileOrString):
"""Parsers a file or string and returns a list of AudioClipSpec
Arguments:
specsFileOrString (str): specifications' file or string
Examples:
>>> SpecsParser.parse('23.4 34.1\n40.2 79.65 Hello World!')
[<Audi... |
Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None | def _parseLine(cls, line):
"""Parsers a single line of text and returns an AudioClipSpec
Line format:
<number> <number> [<text>]
Returns: list(AudioClipSpec) or None
"""
r = cls._PROG.match(line)
if not r:
raise ValueError("Error: parsing '%s'. ... |
Returns the tunnel mode's name, for printing purpose. | def mode_name(self):
""" Returns the tunnel mode's name, for printing purpose. """
for name, id in self.MODES.iteritems():
if id == self.mode:
return name |
Create the tunnel.
If the tunnel is already opened, the function will
raised an AlreadyOpened exception. | def open(self):
""" Create the tunnel.
If the tunnel is already opened, the function will
raised an AlreadyOpened exception.
"""
if self.fd is not None:
raise self.AlreadyOpened()
logger.debug("Opening %s..." % (TUN_KO_PATH, ))
self.fd = os.o... |
Close the tunnel.
If the tunnel is already closed or never opened,
do nothing. | def close(self):
""" Close the tunnel.
If the tunnel is already closed or never opened,
do nothing.
"""
if self.fd is None:
return
logger.debug("Closing tunnel '%s'..." % (self.name or "", ))
# Close tun.ko file
os.close(... |
Receive a buffer. The default size is 1500, the
classical MTU. | def recv(self, size = None):
""" Receive a buffer. The default size is 1500, the
classical MTU.
"""
size = size if size is not None else 1500
return os.read(self.fd, size) |
Sets the MAC address of the device to 'mac'.
parameter 'mac' should be a binary representation
of the MAC address
Note: Will fail for TUN devices | def set_mac(self, mac):
""" Sets the MAC address of the device to 'mac'.
parameter 'mac' should be a binary representation
of the MAC address
Note: Will fail for TUN devices
"""
mac = map(ord, mac)
ifreq = struct.pack('16sH6B8', self.name, socket.AF_UN... |
Sets the IP address (ifr_addr) of the device
parameter 'ip' should be string representation of IP address
This does the same as ifconfig. | def set_ipv4(self, ip):
""" Sets the IP address (ifr_addr) of the device
parameter 'ip' should be string representation of IP address
This does the same as ifconfig.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bin_ip = socket.inet_aton(ip)
... |
MLBAM dataset download | def download(self):
"""
MLBAM dataset download
"""
p = Pool()
p.map(self._download, self.days) |
download MLBAM Game Day
:param timestamp: day | def _download(self, timestamp):
"""
download MLBAM Game Day
:param timestamp: day
"""
games, atbats, pitches = [], [], []
rosters, coaches, umpires = [], [], []
boxscores, actions = [], []
timestamp_params = {
'year': str(timestamp.year),
... |
Game Number
:param gid_path: game logs directory path
:return: game number(int) | def _get_game_number(cls, gid_path):
"""
Game Number
:param gid_path: game logs directory path
:return: game number(int)
"""
game_number = str(gid_path[len(gid_path)-2:len(gid_path)-1])
if game_number.isdigit():
return int(game_number)
else:
... |
Write CSV
:param datasets: Datasets
:param filename: File Name | def _write_csv(self, datasets, filename):
"""
Write CSV
:param datasets: Datasets
:param filename: File Name
"""
with open('/'.join([self.output, filename]), mode='w', encoding=self.encoding) as write_file:
writer = csv.writer(write_file, delimiter=',')
... |
validate datetime value
:param value: datetime value
:return: None or validators.Invalid or MlbAmException | def _validate_datetime(cls, value):
"""
validate datetime value
:param value: datetime value
:return: None or validators.Invalid or MlbAmException
"""
datetime_check = validators.Int()
datetime_check.to_python(value)
if len(value) != 8:
raise M... |
validate from-to
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:return: None or MlbAmException | def _validate_datetime_from_to(cls, start, end):
"""
validate from-to
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:return: None or MlbAmException
"""
if not start <= end:
raise MlbAmBadParameter("not Start Day({start}) <= End Day({e... |
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD) | def _days(cls, start, end):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
"""
days = []
# datetime
start_day, end_day = dt.strptime(start, cls.DATE_FORMAT), dt.strptime(end, cls.DATE_FORMAT)
delta = end_day... |
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory | def scrape(cls, start, end, output):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param output: Output directory
"""
# Logger setting
logging.basicConfig(
level=logging.INFO,
format="time:... |
First the atom names of protein charge centers are found as these can be different in different forcefields.
Then a Euclidian distance is measured between charged ligand atoms and respective inverted charge centres on
protein. If the distance s lower than threshold (5.5 angstrom) the interaction is reco... | def find_salt_bridges(self):
"""First the atom names of protein charge centers are found as these can be different in different forcefields.
Then a Euclidian distance is measured between charged ligand atoms and respective inverted charge centres on
protein. If the distance s lower than threshol... |
Make numpy array from timeseries data. | def make_table(self):
"""Make numpy array from timeseries data."""
num_records = int(np.sum([1 for frame in self.timeseries]))
dtype = [("frame",float),("time",float),("ligand atom id",int),
("ligand atom name","|U4"),("distance",float),
("resid",int),("resname","... |
Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array. | def count_by_type(self):
"""Count how many times each individual salt bridge occured throughout the simulation.
Returns numpy array."""
saltbridges = defaultdict(int)
for contact in self.timeseries:
#count by residue name not by proteinring
pkey = (contact.liganda... |
Count how many salt bridges occured in each frame.
Returns numpy array. | def count_by_time(self):
"""Count how many salt bridges occured in each frame.
Returns numpy array."""
out = np.empty((len(self.timesteps),), dtype=[('time', float), ('count', int)])
for cursor,timestep in enumerate(self.timesteps):
out[cursor] = (timestep,len([x for x in sel... |
Calculates the frequency of salt bridges throughout simulations. If the frequency exceeds the
analysis cutoff, this interaction will be taken for further consideration.
Takes:
* analysis_cutoff * - fraction of simulation time a feature has to be present for to be plotted
Output:
... | def get_saltbridge_frequency(self,analysis_cutoff):
"""Calculates the frequency of salt bridges throughout simulations. If the frequency exceeds the
analysis cutoff, this interaction will be taken for further consideration.
Takes:
* analysis_cutoff * - fraction of simulation time a f... |
Keep longest field among `head` and `update`. | def keep_longest(head, update, down_path):
"""Keep longest field among `head` and `update`.
"""
if update is None:
return 'f'
if head is None:
return 's'
return 'f' if len(head) >= len(update) else 's' |
Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant | def comments(self, case_id=None, variant_id=None, username=None):
"""Return comments for a case or variant.
Args:
case_id (str): id for a related case
variant_id (Optional[str]): id for a related variant
"""
logger.debug("Looking for comments")
comment_ob... |
Add a comment to a variant or a case | def add_comment(self, case_obj, text, variant_id=None, username=None):
"""Add a comment to a variant or a case"""
comment = Comment(
text=text,
username=username or 'Anonymous',
case=case_obj,
# md5 sum of chrom, pos, ref, alt
variant_id=varia... |
Delete a comment | def delete_comment(self, comment_id):
"""Delete a comment"""
comment_obj = self.query(Comment).get(comment_id)
if comment_obj:
logger.debug("Deleting comment {0}".format(comment_obj.id))
self.session.delete(comment_obj)
self.save()
return comment_obj |
Add the consequences found for a variant
Args:
variant_obj (puzzle.models.Variant)
raw_variant_line (str): A raw vcf variant line | def _add_consequences(self, variant_obj, raw_variant_line):
"""Add the consequences found for a variant
Args:
variant_obj (puzzle.models.Variant)
raw_variant_line (str): A raw vcf variant line
"""
consequences = []
for consequence in SO_TERMS:... |
Add the most severe consequence
Args:
variant_obj (puzzle.models.Variant) | def _add_most_severe_consequence(self, variant_obj):
"""Add the most severe consequence
Args:
variant_obj (puzzle.models.Variant)
"""
most_severe_consequence = None
most_severe_score = None
for consequence in variant_obj.consequences:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.