INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Create ( if necessary ) and apply the mask to the given matrix mat. | def _apply_mask(self,p,mat):
"""Create (if necessary) and apply the mask to the given matrix mat."""
mask = p.mask
ms=p.mask_shape
if ms is not None:
mask = ms(x=p.x+p.size*(ms.x*np.cos(p.orientation)-ms.y*np.sin(p.orientation)),
y=p.y+p.size*(ms.x*np.si... |
Change the dimensions of the matrix into which the pattern will be drawn. Users of this class should call this method rather than changing the bounds xdensity and ydensity parameters directly. Subclasses can override this method to update any internal data structures that may depend on the matrix dimensions. | def set_matrix_dimensions(self, bounds, xdensity, ydensity):
"""
Change the dimensions of the matrix into which the pattern
will be drawn. Users of this class should call this method
rather than changing the bounds, xdensity, and ydensity
parameters directly. Subclasses can ove... |
Save the state of the output functions to be restored with state_pop. | def state_push(self):
"Save the state of the output functions, to be restored with state_pop."
for of in self.output_fns:
if hasattr(of,'state_push'):
of.state_push()
super(PatternGenerator, self).state_push() |
Restore the state of the output functions saved by state_push. | def state_pop(self):
"Restore the state of the output functions saved by state_push."
for of in self.output_fns:
if hasattr(of,'state_pop'):
of.state_pop()
super(PatternGenerator, self).state_pop() |
duration: The temporal duration to animate in the units defined on the global time function. | def anim(self, duration, offset=0, timestep=1,
label=None, unit=None,
time_fn=param.Dynamic.time_fn):
"""
duration: The temporal duration to animate in the units
defined on the global time function.
offset: The temporal offset from which the animation is
... |
Returns a PIL image for this pattern overriding parameters if provided. | def pil(self, **params_to_override):
"""Returns a PIL image for this pattern, overriding parameters if provided."""
from PIL.Image import fromarray
nchans = self.num_channels()
if nchans in [0, 1]:
mode, arr = None, self(**params_to_override)
arr = (255.0 / arr.m... |
Push the state of all generators | def state_push(self):
"""
Push the state of all generators
"""
super(Composite,self).state_push()
for gen in self.generators:
gen.state_push() |
Pop the state of all generators | def state_pop(self):
"""
Pop the state of all generators
"""
super(Composite,self).state_pop()
for gen in self.generators:
gen.state_pop() |
Constructs combined pattern out of the individual ones. | def function(self,p):
"""Constructs combined pattern out of the individual ones."""
generators = self._advance_pattern_generators(p)
assert hasattr(p.operator,'reduce'),repr(p.operator)+" does not support 'reduce'."
# CEBALERT: mask gets applied by all PGs including the Composite itsel... |
Postgresql Create Table statement formatter. | def compile_create_table(qualified_name: str, column_statement: str,
primary_key_statement: str) -> str:
"""Postgresql Create Table statement formatter."""
statement = """
CREATE TABLE {table} ({columns} {primary_keys});
""".format(table=qualified_name,
... |
Postgresql Create Temporary Table statement formatter. | def compile_create_temporary_table(table_name: str,
column_statement: str,
primary_key_statement: str) -> str:
"""Postgresql Create Temporary Table statement formatter."""
statement = """
CREATE TEMPORARY TABLE {table} ({colu... |
Create column definition statement. | def compile_column(name: str, data_type: str, nullable: bool) -> str:
"""Create column definition statement."""
null_str = 'NULL' if nullable else 'NOT NULL'
return '{name} {data_type} {null},'.format(name=name,
data_type=data_type,
... |
Declare materalized view. | def create(self, no_data=False):
"""Declare materalized view."""
if self.query:
ddl_statement = self.compile_create_as()
else:
ddl_statement = self.compile_create()
if no_data:
ddl_statement += '\nWITH NO DATA'
return ddl_statement, self.que... |
For a given variant return its set of predicted effects. Optionally filter to transcripts where this variant results in a non - synonymous change to the protein sequence. | def predicted_effects_for_variant(
variant,
transcript_id_whitelist=None,
only_coding_changes=True):
"""
For a given variant, return its set of predicted effects. Optionally
filter to transcripts where this variant results in a non-synonymous
change to the protein sequence.
... |
For a given variant find all the transcripts which overlap the variant and for which it has a predictable effect on the amino acid sequence of the protein. | def reference_transcripts_for_variant(
variant,
transcript_id_whitelist=None,
only_coding_changes=True):
"""
For a given variant, find all the transcripts which overlap the
variant and for which it has a predictable effect on the amino acid
sequence of the protein.
"""
pr... |
Returns a pileup column at the specified position. Unclear if a function like this is hiding somewhere in pysam API. | def pileup_reads_at_position(samfile, chromosome, base0_position):
"""
Returns a pileup column at the specified position. Unclear if a function
like this is hiding somewhere in pysam API.
"""
# TODO: I want to pass truncate=True, stepper="all"
# but for some reason I get this error:
# ... |
Generator that yields a sequence of ReadAtLocus records for reads which contain the positions before and after a variant. The actual work to figure out if what s between those positions matches a variant happens later in the variant_reads module. | def locus_read_generator(
samfile,
chromosome,
base1_position_before_variant,
base1_position_after_variant,
use_duplicate_reads=USE_DUPLICATE_READS,
use_secondary_alignments=USE_SECONDARY_ALIGNMENTS,
min_mapping_quality=MIN_READ_MAPPING_QUALITY):
"""
Gener... |
Traverse a BAM file to find all the reads overlapping a specified locus. | def locus_reads_dataframe(*args, **kwargs):
"""
Traverse a BAM file to find all the reads overlapping a specified locus.
Parameters are the same as those for read_locus_generator.
"""
df_builder = DataFrameBuilder(
LocusRead,
variant_columns=False,
converters={
"... |
Parameters ---------- pileup_element: pysam. PileupRead | def from_pysam_pileup_element(
cls,
pileup_element,
base0_position_before_variant,
base0_position_after_variant,
use_secondary_alignments,
use_duplicate_reads,
min_mapping_quality,
use_soft_clipped_bases=False):
"""
... |
Generate copy from csv statement. | def copy_from_csv_sql(qualified_name: str, delimiter=',', encoding='utf8',
null_str='', header=True, escape_str='\\', quote_char='"',
force_not_null=None, force_null=None):
"""Generate copy from csv statement."""
options = []
options.append("DELIMITER '%s'" % del... |
Sort protein sequences in decreasing order of priority | def sort_protein_sequences(protein_sequences):
"""
Sort protein sequences in decreasing order of priority
"""
return list(
sorted(
protein_sequences,
key=ProteinSequence.ascending_sort_key,
reverse=True)) |
Translates each coding variant in a collection to one or more Translation objects which are then aggregated into equivalent ProteinSequence objects. | def reads_generator_to_protein_sequences_generator(
variant_and_overlapping_reads_generator,
transcript_id_whitelist=None,
protein_sequence_length=PROTEIN_SEQUENCE_LENGTH,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
mi... |
Given a generator which yields ( Variant [ ProteinSequence ] ) elements returns a pandas. DataFrame | def protein_sequences_generator_to_dataframe(variant_and_protein_sequences_generator):
"""
Given a generator which yields (Variant, [ProteinSequence]) elements,
returns a pandas.DataFrame
"""
return dataframe_from_generator(
element_class=ProteinSequence,
variant_and_elements_generat... |
Summarize a collection of Translation objects into three values: 1 ) List of unique reads supporting underlying variant sequences 2 ) Set of unique transcript names for establishing reading frames of the translations. 3 ) Set of unique gene names for all transcripts used by translations. | def _summarize_translations(cls, translations):
"""
Summarize a collection of Translation objects into three values:
1) List of unique reads supporting underlying variant sequences
2) Set of unique transcript names for establishing reading frames of the
translation... |
Create a ProteinSequence object from a TranslationKey along with all the extra fields a ProteinSequence requires. | def from_translation_key(
cls,
translation_key,
translations,
overlapping_reads,
ref_reads,
alt_reads,
alt_reads_supporting_protein_sequence,
transcripts_overlapping_variant,
transcripts_supporting_protein_sequen... |
Sort protein sequences lexicographically by three criteria: - number of unique supporting reads - minimum mismatch versus a supporting reference transcript before variant - minimum mismatch versus a supporting reference transcript after variant - number of supporting reference transcripts | def ascending_sort_key(self):
"""
Sort protein sequences lexicographically by three criteria:
- number of unique supporting reads
- minimum mismatch versus a supporting reference transcript before variant
- minimum mismatch versus a supporting reference transcript aft... |
Table referencing a delete from using primary key join. | def make_delete_table(table: Table, delete_prefix='delete_from__') -> Table:
"""Table referencing a delete from using primary key join."""
name = delete_prefix + table.name
primary_key = table.primary_key
key_names = set(primary_key.column_names)
columns = [column for column in table.columns if col... |
Record table column ( s ) and primary key columns by specified order. | def order_table_columns(table: Table, column_names: list) -> Table:
"""Record table column(s) and primary key columns by specified order."""
unordered_columns = table.column_names
index_order = (unordered_columns.index(name) for name in column_names)
ordered_columns = [table.columns[i] for i in index_o... |
Trims common prefixes from the ref and alt sequences | def trim_variant_fields(location, ref, alt):
"""
Trims common prefixes from the ref and alt sequences
Parameters
----------
location : int
Position (starting from 1) on some chromosome
ref : str
Reference nucleotides
alt : str
Alternate (mutant) nucleotide
Ret... |
Inteval of interbase offsets of the affected reference positions for a particular variant s primary fields ( pos ref alt ). | def base0_interval_for_variant_fields(base1_location, ref, alt):
"""
Inteval of interbase offsets of the affected reference positions for a
particular variant's primary fields (pos, ref, alt).
Parameters
----------
base1_location : int
First reference nucleotide of variant or, for inser... |
Inteval of interbase offsets of the affected reference positions for a particular variant. | def base0_interval_for_variant(variant):
"""
Inteval of interbase offsets of the affected reference positions for a
particular variant.
Parameters
----------
variant : varcode.Variant
Returns triplet of (base1_location, ref, alt)
"""
base1_location, ref, alt = trim_variant(variant)... |
Convert from a variant s position in global genomic coordinates on the forward strand to an interval of interbase offsets on a particular transcript s mRNA. | def interbase_range_affected_by_variant_on_transcript(variant, transcript):
"""
Convert from a variant's position in global genomic coordinates on the
forward strand to an interval of interbase offsets on a particular
transcript's mRNA.
Parameters
----------
variant : varcode.Variant
t... |
Insert a collection of namedtuple records. | def insert(conn, qualified_name: str, column_names, records):
"""Insert a collection of namedtuple records."""
query = create_insert_statement(qualified_name, column_names)
with conn:
with conn.cursor(cursor_factory=NamedTupleCursor) as cursor:
for record in records:
cu... |
Insert many records by chunking data into insert statements. | def insert_many(conn, tablename, column_names, records, chunksize=2500):
"""Insert many records by chunking data into insert statements.
Notes
-----
records should be Iterable collection of namedtuples or tuples.
"""
groups = chunks(records, chunksize)
column_str = ','.join(column_names)
... |
Upsert records. | def upsert_records(conn, records, upsert_statement):
"""Upsert records."""
with conn:
with conn.cursor() as cursor:
for record in records:
cursor.execute(upsert_statement, record) |
SQL statement for a joined delete from. Generate SQL statement for deleting the intersection of rows between both tables from table referenced by tablename. | def delete_joined_table_sql(qualified_name, removing_qualified_name, primary_key):
"""SQL statement for a joined delete from.
Generate SQL statement for deleting the intersection of rows between
both tables from table referenced by tablename.
"""
condition_template = 't.{}=d.{}'
where_clause = ... |
Copy file - like object to database table. | def copy_from_csv(conn, file, qualified_name: str, delimiter=',', encoding='utf8',
null_str='', header=True, escape_str='\\', quote_char='"',
force_not_null=None, force_null=None):
"""Copy file-like object to database table.
Notes
-----
Implementation defaults to pos... |
Retrieve all user tables. | def get_user_tables(conn):
"""Retrieve all user tables."""
query_string = "select schemaname, relname from pg_stat_user_tables;"
with conn.cursor() as cursor:
cursor.execute(query_string)
tables = cursor.fetchall()
return tables |
Returns primary key columns for a specific table. | def get_primary_keys(conn, table: str, schema='public'):
"""Returns primary key columns for a specific table."""
query = """\
SELECT
c.constraint_name AS pkey_constraint_name,
c.column_name AS column_name
FROM
information_schema.key_column_usage AS c
JOIN information_schema.table_constraints AS t
... |
Returns column data following db. Column parameter specification. | def get_column_metadata(conn, table: str, schema='public'):
"""Returns column data following db.Column parameter specification."""
query = """\
SELECT
attname as name,
format_type(atttypid, atttypmod) AS data_type,
NOT attnotnull AS nullable
FROM pg_catalog.pg_attribute
WHERE attrelid=%s::regclass
AND a... |
Reflect basic table attributes. | def reflect_table(conn, table_name, schema='public'):
"""Reflect basic table attributes."""
column_meta = list(get_column_metadata(conn, table_name, schema=schema))
primary_key_columns = list(get_primary_keys(conn, table_name, schema=schema))
columns = [Column(**column_data) for column_data in column_... |
Reset database. | def reset(db_name):
"""Reset database."""
conn = psycopg2.connect(database='postgres')
db = Database(db_name)
conn.autocommit = True
with conn.cursor() as cursor:
cursor.execute(db.drop_statement())
cursor.execute(db.create_statement())
conn.close() |
Install Postgres extension if available. | def install_extensions(extensions, **connection_parameters):
"""Install Postgres extension if available.
Notes
-----
- superuser is generally required for installing extensions.
- Currently does not support specific schema.
"""
from postpy.connections import connect
conn = connect(**c... |
Sends a status update to the framework scheduler. | def update(self, status):
"""Sends a status update to the framework scheduler.
Retrying as necessary until an acknowledgement has been received or the
executor is terminated (in which case, a TASK_LOST status update will be
sent).
See Scheduler.statusUpdate for more information ... |
Sends a message to the framework scheduler. | def message(self, data):
"""Sends a message to the framework scheduler.
These messages are best effort; do not expect a framework message to be
retransmitted in any reliable fashion.
"""
logging.info('Driver sends framework message {}'.format(data))
return self.driver.se... |
Returns an iterable of tuples containing ( index controller_name ) pairs. | def get_controller_list(self):
"""
Returns an iterable of tuples containing (index, controller_name) pairs.
Controller indexes start at 0.
You may easily transform this to a {name: index} mapping by using:
>>> controllers = {name: index for index, name in raildriver.get_contro... |
Returns current/ min/ max value of controller at given index or name. | def get_controller_value(self, index_or_name, value_type):
"""
Returns current/min/max value of controller at given index or name.
It is much more efficient to query using an integer index rather than string name.
Name is fine for seldom updates but it's not advised to be used every sec... |
Get current time | def get_current_time(self):
"""
Get current time
:return: datetime.time
"""
hms = [int(self.get_current_controller_value(i)) for i in range(406, 409)]
return datetime.time(*hms) |
Returns the Provider Product and Engine name. | def get_loco_name(self):
"""
Returns the Provider, Product and Engine name.
:return list
"""
ret_str = self.dll.GetLocoName().decode()
if not ret_str:
return
return ret_str.split('.:.') |
Sets controller value | def set_controller_value(self, index_or_name, value):
"""
Sets controller value
:param index_or_name integer index or string name
:param value float
"""
if not isinstance(index_or_name, int):
index = self.get_controller_index(index_or_name)
else:
... |
Flask application initialization. | def init_app(self, app):
"""Flask application initialization.
:param app: The Flask application.
"""
self.init_config(app)
app.extensions['invenio-indexer'] = self
hooks = app.config.get('INDEXER_BEFORE_INDEX_HOOKS', [])
for hook in hooks:
if isinsta... |
.. todo:: REPO. close docstring | def close(self):
""" .. todo:: REPO.close docstring
"""
# Imports
import h5py as h5
from ..error import RepoError
# Close the repo if it's bound, and wipe link; else complain
if self._repo != None:
self._repo.close()
self._repo = None
... |
.. todo:: REPO. load docstring | def load(self, fname):
""" .. todo:: REPO.load docstring
"""
# Imports
import h5py as h5
from ..error import RepoError
# If repo not None, complain
if not self._repo == None:
raise RepoError(RepoError.STATUS,
"Repository already o... |
.. todo:: is_open docstring | def is_open(self):
""" .. todo:: is_open docstring
"""
# Imports
import h5py as h5
# Return whether repo is bound; depends on the 'None' assignment in
# 'close'
retval = isinstance(self._repo, h5.File)
return retval |
.. todo:: store_data docstring | def store_data(self, data, datatype, mode, disp, clobber=False):
""" .. todo:: store_data docstring
"""
# Imports
import h5py as h5
from ..error import RepoError as RErr
from ..const import EnumDispDirection as _E_DD
from ..const import EnumAnharmRepoData
... |
.. todo:: docstring for get_data | def get_data(self, datatype, mode, disp):
""" .. todo:: docstring for get_data
"""
# Imports
import os
from ..const import EnumDispDirection as _E_DD
from ..const import EnumAnharmRepoData
from ..error import RepoError as RErr
# Must be valid mode
... |
.. todo:: has_data docstring | def has_data(self, datatype, mode, disp):
""" .. todo:: has_data docstring
"""
# Imports
from ..error import RepoError
# Just try to get the data. Simply pass up all exceptions except for
# those if the group or data doesn't exist. DO re-raise a non-bound
# re... |
.. todo:: store_param docstring | def store_param(self, value, param, clobber=False):
""" .. todo:: store_param docstring
"""
# Imports
from ..const import EnumAnharmRepoParam
from ..error import RepoError as RErr
# Must be a valid parameter name
if not param in EnumAnharmRepoParam:
... |
.. todo:: docstring for get_param | def get_param(self, param):
""" .. todo:: docstring for get_param
"""
# Imports
import os
from ..const import EnumAnharmRepoParam
from ..error import RepoError as RErr
# Must be a valid parameter name
if not param in EnumAnharmRepoParam:
rais... |
.. todo:: has_param docstring | def has_param(self, param):
""" .. todo:: has_param docstring
"""
# Imports
from ..error import RepoError
# Try to get the param; pass along all errors, except 'data' error
# from RepoError
retval = True
try:
self.get_param(param)
ex... |
.. todo:: docstring for is_dirty | def is_dirty(self):
""" .. todo:: docstring for is_dirty
"""
# Imports
from ..error import RepoError as RErr
# Get the return value from the dataset, complaining if repo not
# bound. Using 'require_dataset' since any repo w/o a defined
# 'dirty' value is just ... |
.. todo:: set_clean docstring | def set_dirty(self, dirty):
""" .. todo:: set_clean docstring
"""
# Complain if 'dirty' isn't boolean
if not isinstance(dirty, bool):
raise ValueError("'dirty' must be Boolean")
## end if
# Try to retrieve the dataset; complain if repo not bound.
try... |
.. todo:: docstring for get_xyz | def get_XYZ(self, mode, disp):
""" .. todo:: docstring for get_xyz
"""
# Imports
from ..xyz import OpanXYZ as XYZ
from ..const import EnumAnharmRepoParam, EnumAnharmRepoData
# Generate XYZ and return
out_XYZ = XYZ(atom_syms=self.get_param(EnumAnharmRepoParam.ato... |
Stops the scheduler driver. | def stop(self, failover=False):
"""Stops the scheduler driver.
If the 'failover' flag is set to False then it is expected that this
framework will never reconnect to Mesos and all of its executors and
tasks can be terminated. Otherwise, all executors and tasks will
remain runni... |
Requests resources from Mesos. | def request(self, requests):
"""Requests resources from Mesos.
(see mesos.proto for a description of Request and how, for example, to
request resources from specific slaves.)
Any resources available are offered to the framework via
Scheduler.resourceOffers callback, asynchronou... |
Launches the given set of tasks. | def launch(self, offer_id, tasks, filters=Filters()):
"""Launches the given set of tasks.
Any resources remaining (i.e., not used by the tasks or their executors)
will be considered declined.
The specified filters are applied on all unused resources (see
mesos.proto for a descri... |
Kills the specified task. | def kill(self, task_id):
"""Kills the specified task.
Note that attempting to kill a task is currently not reliable.
If, for example, a scheduler fails over while it was attempting to kill
a task it will need to retry in the future.
Likewise, if unregistered / disconnected, the ... |
Allows the framework to query the status for non - terminal tasks. | def reconcile(self, statuses):
"""Allows the framework to query the status for non-terminal tasks.
This causes the master to send back the latest task status for each task
in 'statuses', if possible. Tasks that are no longer known will result
in a TASK_LOST update. If statuses is empty,... |
Declines an offer in its entirety and applies the specified filters on the resources ( see mesos. proto for a description of Filters ). | def decline(self, offer_id, filters=Filters()):
"""Declines an offer in its entirety and applies the specified
filters on the resources (see mesos.proto for a description of
Filters).
Note that this can be done at any time, it is not necessary to do this
within the Schedul... |
Accepts the given offers and performs a sequence of operations on those accepted offers. | def accept(self, offer_ids, operations, filters=Filters()):
"""Accepts the given offers and performs a sequence of operations
on those accepted offers.
See Offer.Operation in mesos.proto for the set of available operations.
Available resources are aggregated when multiple offers are ... |
Acknowledges the status update. | def acknowledge(self, status):
"""Acknowledges the status update.
This should only be called once the status update is processed durably
by the scheduler.
Not that explicit acknowledgements must be requested via the constructor
argument, otherwise a call to this method will cau... |
Sends a message from the framework to one of its executors. | def message(self, executor_id, slave_id, message):
"""Sends a message from the framework to one of its executors.
These messages are best effort; do not expect a framework message to be
retransmitted in any reliable fashion.
"""
logging.info('Sends message `{}` to executor `{}` ... |
Handles GtkBuilder signal connect events | def _connect_func(builder, obj, signal_name, handler_name,
connect_object, flags, cls):
'''Handles GtkBuilder signal connect events'''
if connect_object is None:
extra = ()
else:
extra = (connect_object,)
# The handler name refers to an attribute on the template insta... |
Registers the template for the widget and hooks init_template | def _register_template(cls, template_bytes):
'''Registers the template for the widget and hooks init_template'''
# This implementation won't work if there are nested templates, but
# we can't do that anyways due to PyGObject limitations so it's ok
if not hasattr(cls, 'set_template'):
raise Typ... |
This would be better as an override for Gtk. Widget | def _init_template(self, cls, base_init_template):
'''This would be better as an override for Gtk.Widget'''
# TODO: could disallow using a metaclass.. but this is good enough
# .. if you disagree, feel free to fix it and issue a PR :)
if self.__class__ is not cls:
raise TypeError("Inheritance f... |
babel translation token extract function for haml files | def extract_haml(fileobj, keywords, comment_tags, options):
""" babel translation token extract function for haml files """
import haml
from mako import lexer, parsetree
from mako.ext.babelplugin import extract_nodes
encoding = options.get('input_encoding', options.get('encoding', None))
temp... |
Return a list ( of length patterns_per_label ) of PatternGenerator instances. Should use pattern_type and pattern_parameters to create each pattern. | def _create_patterns(self, properties=None):
"""
Return a list (of length patterns_per_label) of
PatternGenerator instances. Should use pattern_type and
pattern_parameters to create each pattern.
properties is a dictionary, e.g. {'pattern_label':
pattern_label}, which c... |
Extends an ArgumentParser instance with the following commandline arguments: -- bam -- min - reads -- min - mapping - quality -- use - duplicate - reads -- drop - secondary - alignments | def add_rna_args(
parser,
min_mapping_quality_default=MIN_READ_MAPPING_QUALITY):
"""
Extends an ArgumentParser instance with the following commandline arguments:
--bam
--min-reads
--min-mapping-quality
--use-duplicate-reads
--drop-secondary-alignments
... |
Parameters ---------- add_sequence_length_arg: bool If True then add the -- cdna - sequence - length argument. This may be omitted if the cDNA sequence length is inferred from a protein length. | def make_variant_sequences_arg_parser(add_sequence_length_arg=False, **kwargs):
"""
Parameters
----------
add_sequence_length_arg : bool
If True then add the `--cdna-sequence-length` argument. This may be
omitted if the cDNA sequence length is inferred from a protein length.
**kwarg... |
A custom replacement for iter () dispatching a few custom picklable iterators for known types. | def iter_(obj):
"""A custom replacement for iter(), dispatching a few custom picklable
iterators for known types.
"""
if six.PY2:
file_types = file, # noqa
if six.PY3:
file_types = io.IOBase,
dict_items = {}.items().__class__
dict_values = {}.values().__class__
... |
Given a sequence of AlleleRead objects which are expected to all have the same allele return that allele. | def get_single_allele_from_reads(allele_reads):
"""
Given a sequence of AlleleRead objects, which are expected to all have
the same allele, return that allele.
"""
allele_reads = list(allele_reads)
if len(allele_reads) == 0:
raise ValueError("Expected non-empty list of AlleleRead object... |
Given a list of AlleleRead objects extracts all unique ( prefix allele suffix ) sequences and associate each with a list of reads that contained that sequence. | def group_unique_sequences(
allele_reads,
max_prefix_size=None,
max_suffix_size=None):
"""
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with a list
of reads that contained that sequence.
"""
groups = default... |
Given a list of AlleleRead objects extracts all unique ( prefix allele suffix ) sequences and associate each with the number of reads that contain that sequence. | def count_unique_sequences(
allele_reads,
max_prefix_size=None,
max_suffix_size=None):
"""
Given a list of AlleleRead objects, extracts all unique
(prefix, allele, suffix) sequences and associate each with the number
of reads that contain that sequence.
"""
groups = group... |
Overload if special behaviour is required when a series ends. | def extract_specific_interval(self, interval_start, interval_end):
"""
Overload if special behaviour is required when a series ends.
"""
interval_start = int(interval_start)
interval_end = int(interval_end)
if interval_start >= interval_end:
raise ValueError... |
Perform a real Discrete Fourier Transform ( DFT ; implemented using a Fast Fourier Transform algorithm FFT ) of the current sample from the signal multiplied by the smoothing window. | def _get_row_amplitudes(self):
"""
Perform a real Discrete Fourier Transform (DFT; implemented
using a Fast Fourier Transform algorithm, FFT) of the current
sample from the signal multiplied by the smoothing window.
See numpy.rfft for information about the Fourier transform.
... |
Return an iterator that yields every node which is a child of this one. | def iter_all_children(self):
'''Return an iterator that yields every node which is a child of this one.
This includes inline children, and control structure `else` clauses.
'''
if self.inline_child:
yield self.inline_child
for x in self.children:
... |
Transfer functions may need additional information before the supplied numpy array can be modified in place. For instance transfer functions may have state which needs to be allocated in memory with a certain size. In other cases the transfer function may need to know about the coordinate system associated with the inp... | def initialize(self, **kwargs):
"""
Transfer functions may need additional information before the
supplied numpy array can be modified in place. For instance,
transfer functions may have state which needs to be allocated
in memory with a certain size. In other cases, the transfe... |
Temporarily disable plasticity of internal state. | def override_plasticity_state(self, new_plasticity_state):
"""
Temporarily disable plasticity of internal state.
This function should be implemented by all subclasses so that
after a call, the output should always be the same for any
given input pattern, and no call should have ... |
Setup integration | def setup(console=False, port=None):
"""Setup integration
Register plug-ins and integrate into the host
Arguments:
console (bool): DEPRECATED
port (int, optional): DEPRECATED
"""
if self._has_been_setup:
teardown()
register_plugins()
register_host()
self._ha... |
Register supported hosts | def register_host():
"""Register supported hosts"""
pyblish.api.register_host("hython")
pyblish.api.register_host("hpython")
pyblish.api.register_host("houdini") |
Maintain selection during context | def maintained_selection():
"""Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... node.setSelected(on=False, clear_all_selected=True)
>>> # Selection restored
"""
previous_selection = hou.selectedNodes()
t... |
Execute several statements in single DB transaction. | def execute_transaction(conn, statements: Iterable):
"""Execute several statements in single DB transaction."""
with conn:
with conn.cursor() as cursor:
for statement in statements:
cursor.execute(statement)
conn.commit() |
Execute several statements each as a single DB transaction. | def execute_transactions(conn, statements: Iterable):
"""Execute several statements each as a single DB transaction."""
with conn.cursor() as cursor:
for statement in statements:
try:
cursor.execute(statement)
conn.commit()
except psycopg2.Program... |
Open a connection commit a transaction and close it. | def execute_closing_transaction(statements: Iterable):
"""Open a connection, commit a transaction, and close it."""
with closing(connect()) as conn:
with conn.cursor() as cursor:
for statement in statements:
cursor.execute(statement) |
Return a select statement s results as a namedtuple. | def select(conn, query: str, params=None, name=None, itersize=5000):
"""Return a select statement's results as a namedtuple.
Parameters
----------
conn : database connection
query : select query string
params : query parameters.
name : server side cursor name. defaults to client side.
i... |
Return a select statement s results as dictionary. | def select_dict(conn, query: str, params=None, name=None, itersize=5000):
"""Return a select statement's results as dictionary.
Parameters
----------
conn : database connection
query : select query string
params : query parameters.
name : server side cursor name. defaults to client side.
... |
Run select query for each parameter set in single transaction. | def select_each(conn, query: str, parameter_groups, name=None):
"""Run select query for each parameter set in single transaction."""
with conn:
with conn.cursor(name=name) as cursor:
for parameters in parameter_groups:
cursor.execute(query, parameters)
yield ... |
Lightweight query to retrieve column list of select query. | def query_columns(conn, query, name=None):
"""Lightweight query to retrieve column list of select query.
Notes
-----
Strongly urged to specify a cursor name for performance.
"""
with conn.cursor(name) as cursor:
cursor.itersize = 1
cursor.execute(query)
cursor.fetchmany... |
Assuming that the transcript has a coding sequence take a ReferenceSequenceKey ( region of the transcript around the variant ) and return a ReferenceCodingSequenceKey ( or None ). | def from_variant_and_transcript_and_sequence_key(
cls, variant, transcript, sequence_key):
"""
Assuming that the transcript has a coding sequence, take a
ReferenceSequenceKey (region of the transcript around the variant) and
return a ReferenceCodingSequenceKey (or None).
... |
Extracts the reference sequence around a variant locus on a particular transcript and determines the reading frame at the start of that sequence context. | def from_variant_and_transcript(
cls,
variant,
transcript,
context_size):
"""
Extracts the reference sequence around a variant locus on a particular
transcript and determines the reading frame at the start of that
sequence context.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.