output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def dot(self, vec):
"""Dot product with another vector"""
if not isinstance(vec, self.__class__):
raise TypeError('Dot product operand must be a vector')
return np.dot(self, vec) | Implement a Python 3 function for
dotting product with another vector | As a python code expert, you are capable of creating scripts from specifications. |
Cross product with another vector | Can you tell what is the following Python 3 function doing
def cross(self, vec):
if not isinstance(vec, self.__class__):
raise TypeError('Cross product operand must be a vector')
return self.__class__(np.cross(self, vec)) | As a python code expert, you are capable of creating scripts from specifications. |
Calculate the angle between two Vectors
| Here you have a function in Python 3, explain what it does
def angle(self, vec, unit='rad'):
if not isinstance(vec, self.__class__):
raise TypeError('Angle operand must be of class {}'
.format(self.__class__.__name__))
if unit not in ['deg', 'rad']:
ra... | As a python code expert, you are capable of creating scripts from specifications. |
def phi(self):
"""Polar angle / inclination of this vector in radians
Based on sperical coordinate space
returns angle between this vector and the positive z-azis
range: (0 <= phi <= pi)
"""
return np.arctan2(np.sqrt(self.x**2 + self.y**2), self.z) | Can you implement a function in Python 3 that
returns the polar angle of this vector in radians | As a python code expert, you are capable of creating scripts from specifications. |
Cross product with another vector | Make a summary of the following Python 3 code
def cross(self, vec):
if not isinstance(vec, self.__class__):
raise TypeError('Cross product operand must be a vector')
return Vector3(0, 0, np.asscalar(np.cross(self, vec))) | You are a Python code analyst, evaluating scripts for potential improvements. |
Array of vector lengths | Given the following Python 3 function, write the documentation
def length(self):
return np.sqrt(np.sum(self**2, axis=1)).view(np.ndarray) | As a Python code composer, you craft elegant and concise scripts. |
def dot(self, vec):
"""Dot product with another vector"""
if not isinstance(vec, self.__class__):
raise TypeError('Dot product operand must be a VectorArray')
if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV:
raise ValueError('Dot product operands must have the same ... | Can you implement a function in Python 3 that
dots product with another vector. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cross(self, vec):
"""Cross product with another Vector3Array"""
if not isinstance(vec, Vector3Array):
raise TypeError('Cross product operand must be a Vector3Array')
if self.nV != 1 and vec.nV != 1 and self.nV != vec.nV:
raise ValueError('Cross product operands must h... | Write a Python 3 function that can
cross product with another Vector3Array. | As a python code expert, you are capable of creating scripts from specifications. |
Evaluates the RS variable in the RSI algorithm
| How would you explain what the following Python 3 function does
def eval_rs(gains, losses):
# Number of days that the data was collected through
count = len(gains) + len(losses)
avg_gains = stats.avg(gains, count=count) if gains else 1
avg_losses = stats.avg(losses,count=count) if losse... | You are a Python code architect, reviewing and designing scalable and efficient code |
Evaluates RSI from JSON | Make a summary of the following Python 3 code
def eval_from_json(json):
changes = poloniex.get_gains_losses(poloniex.parse_changes(json))
return RSI.eval_algorithm(changes['gains'], changes['losses']) | As a Python code composer, you craft elegant and concise scripts. |
def sigusr1_handler(self, unused_signum, unused_frame):
"""
Handle SIGUSR1 signal. Call function which is defined in the
**settings.SIGUSR1_HANDLER**.
"""
if self._sigusr1_handler_func is not None:
self._sigusr1_handler_func(self.context) | How would you implement a function in Python 3 that
handles SIGUSR1 signal. Call function which is defined in the CONFIG_SYS_SIGUSR1_HANDLER. | As a Python code analyst, you investigate and solve complex coding mysteries |
Handle SIGUSR2 signal. Call function which is defined in the CONFIG_SYS_SIGUSR2_HANDLER. | Can you tell what is the following Python 3 function doing
def sigusr2_handler(self, unused_signum, unused_frame):
if self._sigusr1_handler_func is not None:
self._sigusr2_handler_func(self.context) | You are a Python code generator, capable of creating scripts from specifications. |
def action(args):
"""
Show information about reference packages.
"""
log.info('loading reference package')
pkg = refpkg.Refpkg(args.refpkg, create=False)
with open(pkg.file_abspath('seq_info'), 'rU') as seq_info:
seqinfo = list(csv.DictReader(seq_info))
snames = [row['seqname']... | Write a Python 3 function for
showing information about reference packages. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def json_to_url(json, symbol):
""" Converts a JSON to a URL by the Poloniex API
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
symbol: String of currency pair, like a ticker symbol.
Returns:
String URL to Poloniex API repre... | Write a Python 3 script for
converting a JSON to a URL by the Poloniex API representing the given JSON. | As a Python code composer, you craft elegant and concise scripts. |
def chart_json(start, end, period, symbol):
""" Requests chart data from Poloniex API
Args:
start: Int epoch date to START getting market stats from.
Note that this epoch is FURTHER from the current date.
end: Int epoch date to STOP getting market stats from.
Note th... | How would you code a function in Python 3 to
request and returns the JSON data from Poloniex API for a given market pair. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parses the JSON data into a list of floats of price changes between entries in the JSON. | Can you generate the documentation for the following Python 3 function
def parse_changes(json):
changes = []
dates = len(json)
for date in range(1, dates):
last_close = json[date - 1]['close']
now_close = json[date]['close']
changes.append(now_close - last_close)
logger.debug('M... | As a python code expert, you are capable of creating scripts from specifications. |
def get_gains_losses(changes):
""" Categorizes changes into gains and losses
Args:
changes: List of floats of price changes between entries in JSON.
Returns:
Dict of changes with keys 'gains' and 'losses'.
All values are positive.
"""
res = {'gains': [], 'losses': []}
f... | Implement a Python 3 function for
categorizing changes into gains and losses. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_attribute(json, attr):
""" Gets the values of an attribute from JSON
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
attr: String of attribute in JSON file to collect.
Returns:
List of values of specified attribute fr... | Create a Python 3 function to
get the values of an attribute from JSON data | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_json_shift(year, month, day, unit, count, period, symbol):
""" Gets JSON from shifted date by the Poloniex API
Args:
year: Int between 1 and 9999.
month: Int between 1 and 12.
day: Int between 1 and 31.
unit: String of time period unit for count argument.
How... | Implement a function in Python 3 to
get JSON from shifted date by Poloniex API. | You are a Python code generator, capable of creating scripts from specifications. |
Yields all the ranks for all the results for a given tax_id. | Given the following Python 3 function, write the documentation
def filter_ranks(results):
for _, group in itertools.groupby(results, operator.itemgetter(0)):
yield next(group) | You are a Python code generator, capable of creating scripts from specifications. |
Evaluates the SO algorithm for the current closing price. | Make a summary of the following Python 3 code
def eval_algorithm(closing, low, high):
if high - low == 0: # High and low are the same, zero division error
return 100 * (closing - low)
else:
return 100 * (closing - low) / (high - low) | As a python code expert, you are capable of creating scripts from specifications. |
Evaluates the SO from a JSON dict. | Given the following Python 3 function, write the documentation
def eval_from_json(json):
close = json[-1]['close'] # Latest closing price
low = min(poloniex.get_attribute(json, 'low')) # Lowest low
high = max(poloniex.get_attribute(json, 'high')) # Highest high
return SO.eval_algor... | You are a Python code generator, capable of creating scripts from specifications. |
def avg(vals, count=None):
""" Returns the average value
Args:
vals: List of numbers to calculate average from.
count: Int of total count that vals was part of.
Returns:
Float average value throughout a count.
"""
sum = 0
for v in vals:
sum += v
if count is... | Write a Python 3 script to
return the average value of a list of numbers. | You are a Python code analyst, evaluating scripts for potential improvements. |
def db_connect(engine, schema=None, clobber=False):
"""Create a connection object to a database. Attempt to establish a
schema. If there are existing tables, delete them if clobber is
True and return otherwise. Returns a sqlalchemy engine object.
"""
if schema is None:
base = declarative_b... | Can you implement a function in Python 3 that
creates a connection object to a database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Yields a generator of rows ready to insert into table nodes. | Given the following Python 3 function, write the documentation
def read_nodes(rows, source_id=1):
ncbi_keys = ['tax_id', 'parent_id', 'rank', 'embl_code', 'division_id']
extra_keys = ['source_id', 'is_valid']
is_valid = True
ncbi_cols = len(ncbi_keys)
rank = ncbi_keys.index('rank')
parent_id ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return an iterator of rows ready to insert into table
names. | Can you generate a brief explanation for the following Python 3 code
def read_names(rows, source_id=1):
ncbi_keys = ['tax_id', 'tax_name', 'unique_name', 'name_class']
extra_keys = ['source_id', 'is_primary', 'is_classified']
# is_classified applies to species only; we will set this value
# later
... | As a Python code composer, you craft elegant and concise scripts. |
Download data from NCBI required to generate local taxonomy
database. | Can you generate a brief explanation for the following Python 3 code
def fetch_data(dest_dir='.', clobber=False, url=DATA_URL):
dest_dir = os.path.abspath(dest_dir)
try:
os.mkdir(dest_dir)
except OSError:
pass
fout = os.path.join(dest_dir, os.path.split(url)[-1])
if os.access(fout... | You are a Python code generator, capable of creating scripts from specifications. |
def read_archive(archive, fname):
"""Return an iterator of unique rows from a zip archive.
* archive - path to the zip archive.
* fname - name of the compressed file within the archive.
"""
# Note that deduplication here is equivalent to an upsert/ignore,
# but avoids requirement for a databa... | Implement a function in Python 3 to
return an iterator of unique rows from a zip file. | As a Python code analyst, you investigate and solve complex coding mysteries |
Prepend schema name to name when a schema is specified
| Make a summary of the following Python 3 code
def prepend_schema(self, name):
return '.'.join([self.schema, name]) if self.schema else name | You are a Python code generator, capable of creating scripts from specifications. |
def load_table(self, table, rows, colnames=None, limit=None):
"""Load 'rows' into table 'table'. If 'colnames' is not provided, the
first element of 'rows' must provide column names.
"""
conn = self.engine.raw_connection()
cur = conn.cursor()
colnames = colnames or nex... | How would you code a function in Python 3 to
load rows into table table. | You are a Python code generator, capable of creating scripts from specifications. |
def load_archive(self, archive):
"""Load data from the zip archive of the NCBI taxonomy.
"""
# source
self.load_table(
'source',
rows=[('ncbi', DATA_URL)],
colnames=['name', 'description'],
)
conn = self.engine.raw_connection()
... | Create a Python 3 function for
loading data from the zip archive of the NCBI taxonomy. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a date object to a Delorean instance in UTC | Can you generate a brief explanation for the following Python 3 code
def date_to_delorean(year, month, day):
return Delorean(datetime=dt(year, month, day), timezone='UTC') | You are a Python code generator, capable of creating scripts from specifications. |
Converts a date to epoch in UTC | Explain what the following Python 3 code does
def date_to_epoch(year, month, day):
return int(date_to_delorean(year, month, day).epoch) | As a Python code analyst, you investigate and solve complex coding mysteries |
Gets the resulting epoch after a time shift of a Delorean object. | Explain what the following Python 3 code does
def shift_epoch(delorean, direction, unit, count):
return int(delorean._shift_date(direction, unit, count).epoch) | You are a Python code generator, capable of creating scripts from specifications. |
Generates count epochs in UTC from a shifted Delorean instance. | Explain what the following Python 3 code does
def generate_epochs(delorean, direction, unit, count):
for shift in range(count):
yield int(delorean._shift_date(direction, unit, shift).epoch) | You are a Python code analyst, evaluating scripts for potential improvements. |
Gets epoch from a start date and epoch from a shifted date | Can you generate the documentation for the following Python 3 function
def get_end_start_epochs(year, month, day, direction, unit, count):
if year or month or day: # Date is specified
if not year:
year = 2017
if not month:
month = 1
if not day:
day = 1
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a child to this node. | Can you tell what is the following Python 3 function doing
def add_child(self, child):
assert child != self
child.parent = self
child.ranks = self.ranks
child.index = self.index
assert child.tax_id not in self.index
self.index[child.tax_id] = child
self.children.a... | You are a Python code generator, capable of creating scripts from specifications. |
def remove_child(self, child):
"""
Remove a child from this node.
"""
assert child in self.children
self.children.remove(child)
self.index.pop(child.tax_id)
if child.parent is self:
child.parent = None
if child.index is self.index:
... | Write a Python 3 function that can
remove a child from this node. | As a Python code composer, you craft elegant and concise scripts. |
def drop(self):
"""
Remove this node from the taxonomy, maintaining child subtrees by
adding them to the node's parent, and moving sequences at this node
to the parent.
Not valid for root node.
"""
if self.is_root:
raise ValueError("Cannot drop root n... | Can you implement a function in Python 3 that
drops this node from the taxonomy. | As a python code expert, you are capable of creating scripts from specifications. |
Remove nodes with sequences or children below this node. | Can you generate a brief explanation for the following Python 3 code
def prune_unrepresented(self):
for node in self.depth_first_iter(self_first=False):
if (not node.children and
not node.sequence_ids and
node is not self):
node.parent.remove_c... | As a python code expert, you are capable of creating scripts from specifications. |
Find the node above this node at the given rank. | Can you generate a brief explanation for the following Python 3 code
def at_rank(self, rank):
s = self
while s:
if s.rank == rank:
return s
s = s.parent
raise ValueError("No node at rank {0} for {1}".format(
rank, self.tax_id)) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def depth_first_iter(self, self_first=True):
"""
Iterate over nodes below this node, optionally yielding children before
self.
"""
if self_first:
yield self
for child in list(self.children):
for i in child.depth_first_iter(self_first):
... | Create a Python 3 function for
iterating over nodes below this node optionally yielding children before this node. | You are a Python code architect, reviewing and designing scalable and efficient code |
def path(self, tax_ids):
"""Get the node at the end of the path described by tax_ids."""
assert tax_ids[0] == self.tax_id
if len(tax_ids) == 1:
return self
n = tax_ids[1]
try:
child = next(i for i in self.children if i.tax_id == n)
except StopIter... | How would you implement a function in Python 3 that
gets the node at the end of the path described by tax_ids. | You are a Python code architect, reviewing and designing scalable and efficient code |
def lineage(self):
"""
Return all nodes between this node and the root, including this one.
"""
if not self.parent:
return [self]
else:
L = self.parent.lineage()
L.append(self)
return L | Write a Python 3 script for
returning all nodes between this node and the root including this one. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def write_taxtable(self, out_fp, **kwargs):
"""
Write a taxtable for this node and all descendants,
including the lineage leading to this node.
"""
ranks_represented = frozenset(i.rank for i in self) | \
frozenset(i.rank for i in self.lineage())
ranks = [i for... | Write a Python 3 script to
write a taxtable for this node and all descendants including the lineage leading to this node. | You are a Python code architect, reviewing and designing scalable and efficient code |
def populate_from_seqinfo(self, seqinfo):
"""Populate sequence_ids below this node from a seqinfo file object."""
for row in csv.DictReader(seqinfo):
node = self.index.get(row['tax_id'])
if node:
node.sequence_ids.add(row['seqname']) | Create a Python 3 function to
populate sequence_ids below this node from a seqinfo file object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Collapse all sequence_ids in the subtree below this node to this node. | Here you have a function in Python 3, explain what it does
def collapse(self, remove=False):
descendants = iter(self)
# Skip this node
assert next(descendants) is self
for descendant in descendants:
self.sequence_ids.update(descendant.sequence_ids)
descendant.sequ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write a simple seq_info file suitable for use in taxtastic. | Make a summary of the following Python 3 code
def write_seqinfo(self, out_fp, include_name=True):
header = ['seqname', 'tax_id']
if include_name:
header.append('tax_name')
w = csv.DictWriter(out_fp, header, quoting=csv.QUOTE_NONNUMERIC,
lineterminator='\n... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate a node from an open handle to a taxtable | Can you tell what is the following Python 3 function doing
def from_taxtable(cls, taxtable_fp):
r = csv.reader(taxtable_fp)
headers = next(r)
rows = (collections.OrderedDict(list(zip(headers, i))) for i in r)
row = next(rows)
root = cls(rank=row['rank'], tax_id=row[
... | As a Python code composer, you craft elegant and concise scripts. |
Generate a TaxNode from a taxonomy database. | Can you generate the documentation for the following Python 3 function
def from_taxdb(cls, con, root=None):
cursor = con.cursor()
if root is None:
cursor.execute(
"SELECT tax_id, rank FROM nodes WHERE tax_id = parent_id")
else:
cursor.execute(
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse_host(host):
"""
Parse *host* in format ``"[hostname:]port"`` and return :class:`tuple`
``(address, port)``.
>>> parse_host('localhost:4444')
('localhost', 4444)
>>> parse_host(':4444')
('', 4444)
>>> parse_host('4444')
('', 4444)
>>> parse_h... | How would you code a function in Python 3 to
parse a host string and return a tuple containing the address and port. | As a Python code analyst, you investigate and solve complex coding mysteries |
Recursively fetch children of tax_ids in parent_ids until the rank of rank of rank of rank | Can you generate the documentation for the following Python 3 function
def get_children(engine, parent_ids, rank='species', schema=None):
if not parent_ids:
return []
nodes = schema + '.nodes' if schema else 'nodes'
names = schema + '.names' if schema else 'names'
cmd = ('select tax_id, tax_n... | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a list of items from the current configuration. | Can you generate the documentation for the following Python 3 function
def get_config_items(self):
return (
('settings', self.settings),
('context_class', self.context_class),
('interfaces', self.interfaces),
('logging', self.logging),
('name', self.na... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the class object that represents the current context. | Explain what the following Python 3 code does
def context_class(self):
if 'context_class' not in self._cached_values:
context_cls_name = getattr(self.settings, 'CONTEXT_CLASS', '')
if context_cls_name:
context_class = import_object(context_cls_name)
else:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def interfaces(self):
"""
Interfaces as a :class:`list`of the
:class:`shelter.core.config.Config.Interface` instances.
"""
if 'interfaces' not in self._cached_values:
self._cached_values['interfaces'] = []
for name, interface in six.iteritems(self.settings... | Create a Python 3 function for
returning a list of all interfaces in the current session. | You are a Python code generator, capable of creating scripts from specifications. |
Updates a Refpkg with new files. | Here you have a function in Python 3, explain what it does
def action(args):
log.info('loading reference package')
pairs = [p.split('=', 1) for p in args.changes]
if args.metadata:
rp = refpkg.Refpkg(args.refpkg, create=False)
rp.start_transaction()
for key, value in pairs:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Imports object from module and returns object from it. | Given the following Python 3 function, write the documentation
def import_object(name):
parts = name.split('.')
if len(parts) < 2:
raise ValueError("Invalid name '%s'" % name)
module_name = ".".join(parts[:-1])
obj_name = parts[-1]
module = importlib.import_module(module_name)
return get... | As a Python code composer, you craft elegant and concise scripts. |
Create the argument parser for the base argument parser. | Can you generate the documentation for the following Python 3 function
def parse_arguments(argv):
parser = argparse.ArgumentParser(description=DESCRIPTION)
base_parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-V', '--version', action='version',
version='taxit v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Execute a list of statements in a session and perform a rollback on
error. | Here you have a function in Python 3, explain what it does
def execute(self, statements, exc=IntegrityError, rasie_as=ValueError):
Session = sessionmaker(bind=self.engine)
session = Session()
try:
for statement in statements:
session.execute(statement)
excep... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _node(self, tax_id):
"""
Returns parent_id, rank
FIXME: expand return rank to include custom 'below' ranks built when
get_lineage is caled
"""
s = select([self.nodes.c.parent_id, self.nodes.c.rank],
self.nodes.c.tax_id == tax_id)
res... | Create a Python 3 function to
return the node id and rank of a tax_id | As a Python code translator, you convert algorithms and pseudocode into Python. |
def primary_from_id(self, tax_id):
"""
Returns primary taxonomic name associated with tax_id
"""
s = select([self.names.c.tax_name],
and_(self.names.c.tax_id == tax_id,
self.names.c.is_primary))
res = s.execute()
output = res.fet... | Create a Python 3 function for
returning the primary taxonomic name associated with tax_id | You are a Python code architect, reviewing and designing scalable and efficient code |
def primary_from_name(self, tax_name):
"""
Return tax_id and primary tax_name corresponding to tax_name.
"""
names = self.names
s1 = select([names.c.tax_id, names.c.is_primary],
names.c.tax_name == tax_name)
log.debug(str(s1))
res = s1.execu... | Can you create a Python 3 function that
returns tax_id and primary tax_name corresponding to tax_name. | You are a Python code generator, capable of creating scripts from specifications. |
def _get_merged(self, tax_id):
"""Returns tax_id into which `tax_id` has been merged or `tax_id` of
not obsolete.
"""
cmd = """
SELECT COALESCE(
(SELECT new_tax_id FROM {merged}
WHERE old_tax_id = {x}), {x})
""".format(x=self.placeholder, merged=self.me... | Implement a Python 3 function for
returning tax_id into which tax_id has been merged or tax_id of not obsolete. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of tuples describing the lineage of a specific tax_id. | Given the following Python 3 function, write the documentation
def _get_lineage(self, tax_id, merge_obsolete=True):
# Be sure we aren't working with an obsolete tax_id
if merge_obsolete:
tax_id = self._get_merged(tax_id)
# Note: joining with ranks seems like a no-op, but for some
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a list of tuples describing the lineage of tax_id and tax_name of tax_id. | Can you generate the documentation for the following Python 3 function
def _get_lineage_table(self, tax_ids, merge_obsolete=True):
try:
with self.engine.connect() as con:
# insert tax_ids into a temporary table
temptab = self.prepend_schema(random_name(12))
... | You are a Python code generator, capable of creating scripts from specifications. |
def add_source(self, source_name, description=None):
"""Adds a row to table "source" if "name" does not
exist. Returns (source_id, True) if a new row is created,
(source_id, False) otherwise.
"""
# TODO: shoud be able to do this inside a transaction
if not source_name:... | Create a Python 3 function for
adding a row to table source if name does not exist. Returns a tuple of source_id and True if a new row is created. | You are a Python code generator, capable of creating scripts from specifications. |
def get_source(self, source_id=None, source_name=None):
"""Returns a dict with keys ['id', 'name', 'description'] or None if
no match. The ``id`` field is guaranteed to be an int that
exists in table source. Requires exactly one of ``source_id``
or ``source_name``. A new source correspon... | Write a Python 3 function that can
return a dict with keys id name description | As a python code expert, you are capable of creating scripts from specifications. |
Confirm that the rank of a node is consistent with the parent and children ranks. | Explain what the following Python 3 code does
def verify_rank_integrity(self, tax_id, rank, parent_id, children):
def _lower(n1, n2):
return self.ranks.index(n1) < self.ranks.index(n2)
if rank not in self.ranks:
raise TaxonIntegrityError('rank "{}" is undefined'.format(rank))
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Add a node to the taxonomy. | Here you have a function in Python 3, explain what it does
def add_node(self, tax_id, parent_id, rank, names, source_name, children=None,
is_valid=True, execute=True, **ignored):
"""Add a node to the taxonomy.
``source_name`` is added to table "source" if necessary.
"""
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_name(self, tax_id, tax_name, source_name=None, source_id=None,
name_class='synonym', is_primary=False, is_classified=None,
execute=True, **ignored):
"""Add a record to the names table corresponding to
``tax_id``. Arguments are as follows:
- tax_id (str... | Create a Python 3 function to
add a record to the names table corresponding to the tax_id. | As a python code expert, you are capable of creating scripts from specifications. |
def add_names(self, tax_id, names, execute=True):
"""Associate one or more names with ``tax_id``.
``names`` is a list of one or more dicts, with keys
corresponding to the signature of ``self.add_name()``
(excluding ``execute``).
"""
primary_names = [n['tax_name'] for n... | Write a Python 3 function for
associating one or more names with tax_id. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return None or a tax_id of a sibling of tax_id. | Can you generate the documentation for the following Python 3 function
def sibling_of(self, tax_id):
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
s = select([self.nodes.c.tax_id],
and_(self.nodes.c.parent_id == parent_id,
... | You are a Python code generator, capable of creating scripts from specifications. |
def tax_ids(self):
'''
Return all tax_ids in node table
'''
fetch = select([self.nodes.c.tax_id]).execute().fetchall()
ids = [t[0] for t in fetch]
return ids | Create a Python 3 function for
returning all tax_ids in node table | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return None or a tax id of a child of tax_id. | Can you generate the documentation for the following Python 3 function
def child_of(self, tax_id):
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
s = select([self.nodes.c.tax_id],
and_(self.nodes.c.parent_id == tax_id,
o... | You are a Python code generator, capable of creating scripts from specifications. |
Return a list of species tax_ids under tax_id such that the node under tax_id is above the species and that the node under tax_id has two children. | How would you explain what the following Python 3 function does
def nary_subtree(self, tax_id, n=2):
if tax_id is None:
return None
parent_id, rank = self._node(tax_id)
if rank == 'species':
return [tax_id]
else:
children = self.children_of(tax_id, 2)
... | As a Python code composer, you craft elegant and concise scripts. |
def validate_db(sqlalchemy_bind, is_enabled=ENABLE_DB):
""" Checks if a DB is authorized and responding before executing the function """
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
def is_db_responsive():
try:
sqlalchemy_bind.s... | Implement a function in Python 3 to
check if a DB is authorized and responding before executing the function | You are a Python code analyst, evaluating scripts for potential improvements. |
Render the template with the given mapping. | Can you tell what is the following Python 3 function doing
def substitute(template, mapping=None):
if mapping is None:
mapping = {}
templ = Template(template)
return templ.substitute(mapping) | You are a Python code generator, capable of creating scripts from specifications. |
def dirtree(path):
"""
Find recursively and return all files and directories from
the path *path*.
"""
results = []
for name in glob.glob(os.path.join(path, '*')):
results.append(name)
if os.path.isdir(name):
results.extend(dirtree(name))
return results | Can you implement a function in Python 3 that
finds recursively and return all files and directories from the path * path*. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create Tornado s application for all interfaces which are defined
in the configuration. | How would you explain what the following Python 3 function does
def get_tornado_apps(context, debug=False):
if context.config.app_settings_handler:
app_settings_handler = import_object(
context.config.app_settings_handler)
settings = app_settings_handler(context)
else:
settin... | As a python code expert, you are capable of creating scripts from specifications. |
def get_new_nodes(fname):
"""
Return an iterator of dicts given a .csv-format file.
"""
with open(fname, 'rU') as infile:
infile = (line for line in infile if not line.startswith('#'))
reader = list(csv.DictReader(infile))
rows = (d for d in reader if d['tax_id'])
# for now... | Can you implement a function in Python 3 that
returns an iterator of dicts given a. csv - format file. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns iterator of whitespace - stripped lines in file fname omitting
Taxonomy blank lines beginning with '#' character. | Can you tell what is the following Python 3 function doing
def getlines(fname):
with open(fname, 'rU') as f:
for line in f:
if line.strip() and not line.startswith('#'):
yield line.split('#', 1)[0].strip() | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse the RAxML summary output. | Explain what the following Python 3 code does
def parse_raxml(handle):
s = ''.join(handle.readlines())
result = {}
try_set_fields(result, r'(?P<program>RAxML version [0-9.]+)', s)
try_set_fields(result, r'(?P<datatype>DNA|RNA|AA)', s)
result['empirical_frequencies'] = (
result['datatype'] !=... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_stockholm(fobj):
"""Return a list of names from an Stockholm-format sequence alignment
file. ``fobj`` is an open file or another object representing a
sequence of lines.
"""
names = OrderedDict()
found_eof = False
for line in fobj:
line = line.strip()
if line == ... | Implement a function in Python 3 to
parse an alignment a file. | As a Python code composer, you craft elegant and concise scripts. |
def has_rppr(rppr_name='rppr'):
"""
Check for rppr binary in path
"""
with open(os.devnull) as dn:
try:
subprocess.check_call([rppr_name], stdout=dn, stderr=dn)
except OSError as e:
if e.errno == os.errno.ENOENT:
return False
else:
... | Implement a function in Python 3 to
check if rppr binary exists in path | You are a Python code architect, reviewing and designing scalable and efficient code |
Add a standard set of database arguments for argparse parser | Make a summary of the following Python 3 code
def add_database_args(parser):
'''
Add a standard set of database arguments for argparse
'''
parser.add_argument(
'url',
nargs='?',
default='sqlite:///ncbi_taxonomy.db',
type=sqlite_default(),
help=('Database string UR... | As a Python code composer, you craft elegant and concise scripts. |
def sqlite_default():
'''
Prepend default scheme if none is specified. This helps provides backwards
compatibility with old versions of taxtastic where sqlite was the automatic
default database.
'''
def parse_url(url):
# TODO: need separate option for a config file
if url.endswit... | Write a Python 3 script to
return a function that parses a sqlite database and returns the url of the database. | You are a Python code architect, reviewing and designing scalable and efficient code |
def action(args):
"""Strips non-current files and rollback information from a refpkg.
*args* should be an argparse object with fields refpkg (giving the
path to the refpkg to operate on).
"""
log.info('loading reference package')
refpkg.Refpkg(args.refpkg, create=False).strip() | Can you implement a function in Python 3 that
strips non - current files and rollback information from a refpkg. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return alphabetical ordered list of the. conf files placed in the path. | Given the following Python 3 function, write the documentation
def get_conf_d_files(path):
if not os.path.isdir(path):
raise ValueError("'%s' is not a directory" % path)
files_mask = os.path.join(path, "*.conf")
return [f for f in sorted(glob.glob(files_mask)) if os.path.isfile(f)] | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_conf_files(filename):
"""
Return :class:`list` of the all configuration files. *filename* is a
path of the main configuration file.
::
>>> get_conf_files('exampleapp.conf')
['exampleapp.conf', 'exampleapp.conf.d/10-database.conf']
"""
if not os.path.isfile(filename):
... | Create a Python 3 function to
return a list of all configuration files. | You are a Python code analyst, evaluating scripts for potential improvements. |
Read main configuration file and all files from * conf. d * subdirectory
and return parsed configuration as a ConfigParser instance. | Can you generate the documentation for the following Python 3 function
def get_configparser(filename=''):
filename = filename or os.environ.get('SHELTER_CONFIG_FILENAME', '')
if not filename:
raise ImproperlyConfiguredError(_(
"Configuration file is not defined. You must either "
... | You are a Python code generator, capable of creating scripts from specifications. |
Return the name of the application. | Can you generate a brief explanation for the following Python 3 code
def name(self):
try:
return self.config_parser.get('application', 'name')
except CONFIGPARSER_EXC:
return super(IniConfig, self).name | As a Python code composer, you craft elegant and concise scripts. |
Return a list of all interfaces in the config file. | Can you generate the documentation for the following Python 3 function
def interfaces(self):
if 'interfaces' not in self._cached_values:
self._cached_values['interfaces'] = []
for name, interface in six.iteritems(self.settings.INTERFACES):
interface_name = 'interface_%s' ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def tz_file(name):
"""
Open a timezone file from the zoneinfo subdir for reading.
:param name: The name of the timezone.
:type name: str
:rtype: file
"""
try:
filepath = tz_path(name)
return open(filepath, 'rb')
except TimezoneNotFound:
# http://bugs.launchpad.... | Can you implement a function in Python 3 that
opens a file from the zoneinfo subdir for reading. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the path to a timezone file. | How would you explain what the following Python 3 function does
def tz_path(name):
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.pardir or os.path.sep in part:
raise ValueError('Bad path seg... | As a Python code composer, you craft elegant and concise scripts. |
def get_timezones():
"""
Get the supported timezones.
The list will be cached unless you set the "fresh" attribute to True.
:param fresh: Whether to get a fresh list or not
:type fresh: bool
:rtype: tuple
"""
base_dir = _DIRECTORY
zones = ()
for root, dirs, files in os.walk(b... | Can you write a function in Python 3 where it
gets the supported timezones. | You are a Python code architect, reviewing and designing scalable and efficient code |
def award_points(target, key, reason="", source=None):
"""
Awards target the point value for key. If key is an integer then it's a
one off assignment and should be interpreted as the actual point value.
"""
point_value, points = get_points(key)
if not ALLOW_NEGATIVE_TOTALS:
total = poi... | Can you implement a function in Python 3 that
awards target the point value for key. | You are a Python code analyst, evaluating scripts for potential improvements. |
Determines how many points the given target has received. | Explain what the following Python 3 code does
def points_awarded(target=None, source=None, since=None):
lookup_params = {}
if target is not None:
if isinstance(target, get_user_model()):
lookup_params["target_user"] = target
else:
lookup_params.update({
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Validate if a date string is a date on yyyy - mm - dd format and it is less than or equal to a year. | Can you generate a brief explanation for the following Python 3 code
def __validate_dates(start_date, end_date):
try:
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
except ValueError:
raise ValueError("Incorrect... | You are a Python code architect, reviewing and designing scalable and efficient code |
Request Yahoo Finance information from YQL. | Can you tell what is the following Python 3 function doing
def __yahoo_request(query):
query = quote(query)
url = 'https://query.yahooapis.com/v1/public/yql?q=' + query + \
'&format=json&env=store://datatables.org/alltableswithkeys'
response = urlopen(url).read()
return json.loads(response.dec... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Request Yahoo Finance recent quotes. | Can you generate the documentation for the following Python 3 function
def request_quotes(tickers_list, selected_columns=['*']):
__validate_list(tickers_list)
__validate_list(selected_columns)
query = 'select {cols} from yahoo.finance.quotes where symbol in ({vals})'
query = query.format(
cols='... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.