output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Create an object from a JSON string. | How would you explain what the following Python 3 function does
def from_json(cls, jsonmsg):
import json
msg = json.loads(jsonmsg)
obj = cls(**msg)
obj.validate()
return obj | As a python code expert, you are capable of creating scripts from specifications. |
def validate(self):
""" Applies all defined validation to the current
state of the object, and raises an error if
they are not all met.
Raises:
ValidationError: if validations do not pass
"""
missing = self.missing_property_names()
if len(missing) >... | Write a Python 3 script for
applying all defined validations to the current state of the object and raises an error if they are not met. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of properties which are required and missing. | Here you have a function in Python 3, explain what it does
def missing_property_names(self):
propname = lambda x: self.__prop_names__[x]
missing = []
for x in self.__required__:
# Allow the null type
propinfo = self.propinfo(propname(x))
null_type = False
... | As a python code expert, you are capable of creating scripts from specifications. |
Wrapper to debug things | Explain what the following Python 3 code does
def construct(self, uri, *args, **kw):
logger.debug(util.lazy_format("Constructing {0}", uri))
if ('override' not in kw or kw['override'] is False) \
and uri in self.resolved:
logger.debug(util.lazy_format("Using existing {0}", ur... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _build_literal(self, nm, clsdata):
"""@todo: Docstring for _build_literal
:nm: @todo
:clsdata: @todo
:returns: @todo
"""
cls = type(str(nm), tuple((LiteralValue,)), {
'__propinfo__': {
'__literal__': clsdata,
'__title__': clsdata.get('title'),
... | Can you create a Python 3 function that
builds a LiteralValue class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Builds the object with the given name. | Make a summary of the following Python 3 code
def _build_object(self, nm, clsdata, parents,**kw):
logger.debug(util.lazy_format("Building object {0}", nm))
# To support circular references, we tag objects that we're
# currently building as "under construction"
self.under_construction.ad... | As a Python code composer, you craft elegant and concise scripts. |
def build_classes(self,strict=False, named_only=False, standardize_names=True):
"""
Build all of the classes named in the JSONSchema.
Class names will be transformed using inflection by default, so names
with spaces in the schema will be camelcased, while names without
spaces wi... | Can you write a function in Python 3 where it
builds all of the classes in the JSONSchema. | You are a Python code architect, reviewing and designing scalable and efficient code |
Interpolate the data field of the n - th entry table into a single column of the n - th entry table. | Can you tell what is the following Python 3 function doing
def _interp(self, data):
row_interpol_data = self._interp_axis(data, 0)
interpol_data = self._interp_axis(row_interpol_data, 1)
return interpol_data | You are a Python code generator, capable of creating scripts from specifications. |
def _interp_axis(self, data, axis):
"""The *data* field contains the data to be interpolated. It is
expected that values reach out to the *data* boundaries.
With *axis*=0 this method interpolates along rows and *axis*=1 it
interpolates along colums.
For column mode the *data* in... | Write a Python 3 script to
interpolate data along a given axis. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def interpolate(self):
"""Do the interpolation and return resulting longitudes and latitudes.
"""
self.latitude = self._interp(self.lat_tiepoint)
self.longitude = self._interp(self.lon_tiepoint)
return self.latitude, self.longitude | Write a Python 3 function that can
do the interpolation and return resulting longitudes and latitudes. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _execute(self, query, model, adapter, raw=False):
"""
We have to override this because in some situation
(such as with Filebackend, or any dummy backend)
we have to parse / adapt results *before* when can execute the query
"""
values = self.load(model, adapter)
... | How would you code a function in Python 3 to
execute a query on the store. | As a Python code composer, you craft elegant and concise scripts. |
Get the given key from the cache if present. | Make a summary of the following Python 3 code
def get(self, key, default=None, reraise=False):
if not self.enabled:
if reraise:
raise exceptions.DisabledCache()
return default
try:
return self._get(key)
except exceptions.NotInCache:
... | As a Python code composer, you craft elegant and concise scripts. |
def set(self, key, value, timeout=NotSet):
"""
Set the given key to the given value in the cache.
A timeout may be provided, otherwise, the :py:attr:`Cache.default_timeout`
will be used.
:param key: the key to which the value will be bound
:type key: str
:param v... | Can you implement a function in Python 3 that
sets the given key to the given value in the cache. | As a Python code composer, you craft elegant and concise scripts. |
def unique_everseen(seq):
"""Solution found here : http://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order"""
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))] | Write a Python 3 function for
returning a list of unique elements in the given sequence. | As a python code expert, you are capable of creating scripts from specifications. |
Update the hints of the underlying queryset | Given the following Python 3 function, write the documentation
def hints(self, **kwargs):
new_query = self.query.clone()
new_query.hints.update(kwargs)
return self._clone(query=new_query) | As a python code expert, you are capable of creating scripts from specifications. |
def build_filter_from_kwargs(self, **kwargs):
"""Convert django-s like lookup to SQLAlchemy ones"""
query = None
for path_to_convert, value in kwargs.items():
path_parts = path_to_convert.split('__')
lookup_class = None
try:
# We check if the ... | Can you create a Python 3 function that
converts django - s like lookup to SQLAlchemy ones | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of all the items in the local dataset | Can you generate a brief explanation for the following Python 3 code
def locally(self):
from .backends import python
from . import models
store = python.IterableStore(values=self)
return store.query(self.manager.model).all() | As a Python code composer, you craft elegant and concise scripts. |
Calculate the line numbers where the swath will be split in smaller
granules for parallel processing | Given the following Python 3 function, write the documentation
def get_scene_splits(nlines_swath, nlines_scan, n_cpus):
nscans = nlines_swath // nlines_scan
if nscans < n_cpus:
nscans_subscene = 1
else:
nscans_subscene = nscans // n_cpus
nlines_subscene = nscans_subscene * nlines_scan
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get 1km geolocation from 20km tiepoints. | How would you explain what the following Python 3 function does
def metop20kmto1km(lons20km, lats20km):
cols20km = np.array([0] + list(range(4, 2048, 20)) + [2047])
cols1km = np.arange(2048)
lines = lons20km.shape[0]
rows20km = np.arange(lines)
rows1km = np.arange(lines)
along_track_order = 1
... | You are a Python code generator, capable of creating scripts from specifications. |
Get 1km geolocation for modis from 5km tiepoints. | Can you generate the documentation for the following Python 3 function
def modis5kmto1km(lons5km, lats5km):
cols5km = np.arange(2, 1354, 5) / 5.0
cols1km = np.arange(1354) / 5.0
lines = lons5km.shape[0] * 5
rows5km = np.arange(2, lines, 5) / 5.0
rows1km = np.arange(lines) / 5.0
along_track_orde... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _multi(fun, lons, lats, chunk_size, cores=1):
"""Work on multiple cores.
"""
pool = Pool(processes=cores)
splits = get_scene_splits(lons.shape[0], chunk_size, cores)
lons_parts = np.vsplit(lons, splits)
lats_parts = np.vsplit(lats, splits)
results = [pool.apply_async(fun,
... | Can you implement a function in Python 3 that
works on multiple cores. | As a Python code composer, you craft elegant and concise scripts. |
def modis1kmto500m(lons1km, lats1km, cores=1):
"""Getting 500m geolocation for modis from 1km tiepoints.
http://www.icare.univ-lille1.fr/tutorials/MODIS_geolocation
"""
if cores > 1:
return _multi(modis1kmto500m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols500m = np.aran... | Write a Python 3 script for
getting 500m geolocation for modis from 1km tiepoints. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get 250m geolocation for modis from 1km tiepoints. | Here you have a function in Python 3, explain what it does
def modis1kmto250m(lons1km, lats1km, cores=1):
if cores > 1:
return _multi(modis1kmto250m, lons1km, lats1km, 10, cores)
cols1km = np.arange(1354)
cols250m = np.arange(1354 * 4) / 4.0
along_track_order = 1
cross_track_order = 3
... | You are a Python code generator, capable of creating scripts from specifications. |
Generic function for modis5km to 1km tiepoints. | Here you have a function in Python 3, explain what it does
def generic_modis5kmto1km(*data5km):
cols5km = np.arange(2, 1354, 5)
cols1km = np.arange(1354)
lines = data5km[0].shape[0] * 5
rows5km = np.arange(2, lines, 5)
rows1km = np.arange(lines)
along_track_order = 1
cross_track_order = 3
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def fill_borders(self, *args):
"""Extrapolate tiepoint lons and lats to fill in the border of the
chunks.
"""
to_run = []
cases = {"y": self._fill_row_borders,
"x": self._fill_col_borders}
for dim in args:
try:
to_run.append(c... | How would you code a function in Python 3 to
extrapolate tiepoint lons and lats to fill in the border of the chunks. | You are a Python code architect, reviewing and designing scalable and efficient code |
Extrapolate the column of data to get the first and last together
with the data. | How would you explain what the following Python 3 function does
def _extrapolate_cols(self, data, first=True, last=True):
if first:
pos = self.col_indices[:2]
first_column = _linear_extrapolate(pos,
(data[:, 0], data[:, 1]),
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Fill the first and last column of the data by extrapolation. | Make a summary of the following Python 3 code
def _fill_col_borders(self):
first = True
last = True
if self.col_indices[0] == self.hcol_indices[0]:
first = False
if self.col_indices[-1] == self.hcol_indices[-1]:
last = False
for num, data in enumerate(sel... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _extrapolate_rows(self, data, row_indices, first_index, last_index):
"""Extrapolate the rows of data, to get the first and last together
with the data.
"""
pos = row_indices[:2]
first_row = _linear_extrapolate(pos,
(data[0, :], data[1,... | Write a Python 3 script for
extrapolating the rows of data to get the first and last together with the data. | As a python code expert, you are capable of creating scripts from specifications. |
def _fill_row_borders(self):
"""Add the first and last rows to the data by extrapolation.
"""
lines = len(self.hrow_indices)
chunk_size = self.chunk_size or lines
factor = len(self.hrow_indices) / len(self.row_indices)
tmp_data = []
for num in range(len(self.tie_... | Create a Python 3 function to
fill the first and last rows of the tables. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Interpolate the cartesian coordinates. | How would you explain what the following Python 3 function does
def _interp(self):
if np.all(self.hrow_indices == self.row_indices):
return self._interp1d()
xpoints, ypoints = np.meshgrid(self.hrow_indices,
self.hcol_indices)
for num, data in ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _interp1d(self):
"""Interpolate in one dimension.
"""
lines = len(self.hrow_indices)
for num, data in enumerate(self.tie_data):
self.new_data[num] = np.empty((len(self.hrow_indices),
len(self.hcol_indices)),
... | Implement a Python 3 function for
interpolating in one dimension. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_lons_from_cartesian(x__, y__):
"""Get longitudes from cartesian coordinates.
"""
return rad2deg(arccos(x__ / sqrt(x__ ** 2 + y__ ** 2))) * sign(y__) | How would you implement a function in Python 3 that
gets longitudes from cartesian coordinates. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get latitudes from cartesian coordinates. | Make a summary of the following Python 3 code
def get_lats_from_cartesian(x__, y__, z__, thr=0.8):
# if we are at low latitudes - small z, then get the
# latitudes only from z. If we are at high latitudes (close to the poles)
# then derive the latitude using x and y:
lats = np.where(np.logical_and(np.l... | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_tiepoints(self, lon, lat):
"""Defines the lon,lat tie points.
"""
self.lon_tiepoint = lon
self.lat_tiepoint = lat | Write a Python 3 function for
defining the lon lat tie points. | As a Python code composer, you craft elegant and concise scripts. |
def compute_expansion_alignment(satz_a, satz_b, satz_c, satz_d):
"""All angles in radians."""
zeta_a = satz_a
zeta_b = satz_b
phi_a = compute_phi(zeta_a)
phi_b = compute_phi(zeta_b)
theta_a = compute_theta(zeta_a, phi_a)
theta_b = compute_theta(zeta_b, phi_b)
phi = (phi_a + phi_b) / 2
... | Write a Python 3 function for
computing expansion and alignment for a single node. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert lon latitudes to cartesian coordinates. | Given the following Python 3 function, write the documentation
def lonlat2xyz(lons, lats):
R = 6370997.0
x_coords = R * da.cos(da.deg2rad(lats)) * da.cos(da.deg2rad(lons))
y_coords = R * da.cos(da.deg2rad(lats)) * da.sin(da.deg2rad(lons))
z_coords = R * da.sin(da.deg2rad(lats))
return x_coords, y_co... | As a python code expert, you are capable of creating scripts from specifications. |
Get longitudes from cartesian coordinates. | Explain what the following Python 3 code does
def xyz2lonlat(x__, y__, z__):
R = 6370997.0
lons = da.rad2deg(da.arccos(x__ / da.sqrt(x__ ** 2 + y__ ** 2))) * da.sign(y__)
lats = da.sign(z__) * (90 - da.rad2deg(da.arcsin(da.sqrt(x__ ** 2 + y__ ** 2) / R)))
return lons, lats | As a Python code analyst, you investigate and solve complex coding mysteries |
Collect all fields declared on the class and remove them from attrs
| Can you tell what is the following Python 3 function doing
def setup_fields(attrs):
fields = {}
iterator = list(attrs.items())
for key, value in iterator:
if not isinstance(value, Field):
continue
fields[key] = value
del attrs[key]
return fields | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse a line of jing output to a list of line column type_ and message. | Given the following Python 3 function, write the documentation
def _parse_jing_line(line):
parts = line.split(':', 4)
filename, line, column, type_, message = [x.strip() for x in parts]
if type_ == 'fatal':
if message in KNOWN_FATAL_MESSAGES_MAPPING:
message = KNOWN_FATAL_MESSAGES_MAPPIN... | As a Python code composer, you craft elegant and concise scripts. |
Parse the jing output into a tuple of line column type and message. | Can you generate the documentation for the following Python 3 function
def _parse_jing_output(output):
output = output.strip()
values = [_parse_jing_line(l) for l in output.split('\n') if l]
return tuple(values) | As a python code expert, you are capable of creating scripts from specifications. |
def jing(rng_filepath, *xml_filepaths):
"""Run jing.jar using the RNG file against the given XML file."""
cmd = ['java', '-jar']
cmd.extend([str(JING_JAR), str(rng_filepath)])
for xml_filepath in xml_filepaths:
cmd.append(str(xml_filepath))
proc = subprocess.Popen(cmd,
... | How would you implement a function in Python 3 that
runs jing. jar using the RNG file against the given XML file. | You are a Python code generator, capable of creating scripts from specifications. |
def import_obj_from_str(s):
"""Returns an import object (either ImportImport or FromImport) from text.
"""
ast_obj = ast.parse(s).body[0]
return ast_type_to_import_type[type(ast_obj)](ast_obj) | Can you create a Python 3 function that
returns an import object from text. | You are a Python code analyst, evaluating scripts for potential improvements. |
def from_str(cls, s):
"""Construct an import object from a string."""
ast_obj = ast.parse(s).body[0]
if not isinstance(ast_obj, cls._expected_ast_type):
raise AssertionError(
'Expected ast of type {!r} but got {!r}'.format(
cls._expected_ast_type,
... | How would you implement a function in Python 3 that
constructs an import object from a string. | You are a Python code generator, capable of creating scripts from specifications. |
def sort(imports, separate=True, import_before_from=True, **classify_kwargs):
"""Sort import objects into groups.
:param list imports: FromImport / ImportImport objects
:param bool separate: Whether to classify and return separate segments
of imports based on classification.
:param bool import_... | Write a Python 3 function for
sorting the list of imports into a single segment list. | You are a Python code generator, capable of creating scripts from specifications. |
Classifies an import by its package. | Here you have a function in Python 3, explain what it does
def classify_import(module_name, application_directories=('.',)):
# Only really care about the first part of the path
base, _, _ = module_name.partition('.')
found, module_path, is_builtin = _get_module_info(
base, application_directories,
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def parse_metadata(elm_tree):
"""Given an element-like object (:mod:`lxml.etree`)
lookup the metadata and return the found elements
:param elm_tree: the root xml element
:type elm_tree: an element-like object from :mod:`lxml.etree`
:returns: common metadata properties
:rtype: dict
"""
... | Can you implement a function in Python 3 that
gives an element - like object containing a root xml element return the common metadata properties. | As a python code expert, you are capable of creating scripts from specifications. |
Validates the given CNXML file against the CNXML - JING RNG. | Given the following Python 3 function, write the documentation
def validate_cnxml(*content_filepaths):
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(CNXML_JING_RNG, *content_filepaths) | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate_collxml(*content_filepaths):
"""Validates the given COLLXML file against the collxml-jing.rng RNG."""
content_filepaths = [Path(path).resolve() for path in content_filepaths]
return jing(COLLXML_JING_RNG, *content_filepaths) | Write a Python 3 function for
validating the given COLLXML file against the collxml - jing. rng RNG. | You are a Python code analyst, evaluating scripts for potential improvements. |
Roll back a refpkg. | Can you tell what is the following Python 3 function doing
def action(args):
log.info('loading reference package')
r = refpkg.Refpkg(args.refpkg, create=False)
# First check if we can do n rollbacks
q = r.contents
for i in range(args.n):
if q['rollback'] is None:
log.error('Can... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the target market trend for a date - based dataset. | How would you explain what the following Python 3 function does
def set_targets(x, delta=10):
data = [] # Keep track of targets
for row, _ in x.iterrows():
if row == x.shape[0] - 1: # Can't predict yet, done.
break
# Get closing prices
curr_close = x.close[row]
next_... | You are a Python code generator, capable of creating scripts from specifications. |
Evaluates technical analysis features from JSON data. | Explain what the following Python 3 code does
def eval_features(json):
return {'close' : json[-1]['close'],
'sma' : SMA.eval_from_json(json),
'rsi' : RSI.eval_from_json(json),
'so' : SO.eval_from_json(json),
'obv' : OBV.eval_from_json(json)} | You are a Python code generator, capable of creating scripts from specifications. |
def target_code_to_name(code):
""" Converts an int target code to a target name
Since self.TARGET_CODES is a 1:1 mapping, perform a reverse lookup
to get the more readable name.
Args:
code: Value from self.TARGET_CODES
Returns:
String target name corresponding to the given code.
... | Write a Python 3 script to
convert an int target code to a target name. | You are a Python code generator, capable of creating scripts from specifications. |
Initializes a machine learning model for the given data set. | Here you have a function in Python 3, explain what it does
def setup_model(x, y, model_type='random_forest', seed=None, **kwargs):
assert len(x) > 1 and len(y) > 1, 'Not enough data objects to train on (minimum is at least two, you have (x: {0}) and (y: {1}))'.format(len(x), len(y))
sets = namedtuple('Datasets... | As a python code expert, you are capable of creating scripts from specifications. |
def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day,
DIRECTION, self.unit, self.count)
return poloniex... | Can you write a function in Python 3 where it
gets market chart data from today to a previous date | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses market data JSON for technical analysis indicators and sets the features of the technical analysis indicators. | Explain what the following Python 3 code does
def set_features(self, partition=1):
if len(self.json) < partition + 1:
raise ValueError('Not enough dates for the specified partition size: {0}. Try a smaller partition.'.format(partition))
data = []
for offset in range(len(self.json) ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def set_long_features(self, features, columns_to_set=[], partition=2):
""" Sets features of double the duration
Example: Setting 14 day RSIs to longer will create add a
feature column of a 28 day RSIs.
Args:
features: Pandas DataFrame instance with columns as numpy.floa... | How would you implement a function in Python 3 that
sets the long features of double the duration of the entry. | As a python code expert, you are capable of creating scripts from specifications. |
Return list of features and their importances in classification | Given the following Python 3 function, write the documentation
def feature_importances(self):
feature_names = [feature for feature in self.features.train]
return list(zip(feature_names, self.feature_importances_)) | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the exit code of the process. | Can you generate a brief explanation for the following Python 3 code
def exitcode(self):
if self._process is None:
raise ProcessError(
"Process '%s' has not been started yet" % self.name)
return self._process.exitcode | You are a Python code architect, reviewing and designing scalable and efficient code |
def initialize(self):
"""
Initialize instance attributes. You can override this method in
the subclasses.
"""
self.main_pid = os.getpid()
self.processes.extend(self.init_service_processes())
self.processes.extend(self.init_tornado_workers()) | Implement a Python 3 function for
initializing the instance attributes. | You are a Python code generator, capable of creating scripts from specifications. |
def sigusr1_handler(self, unused_signum, unused_frame):
"""
Handle SIGUSR1 signal. Call function which is defined in the
**settings.SIGUSR1_HANDLER**. If main process, forward the
signal to all child processes.
"""
for process in self.processes:
if process.pid... | Create a Python 3 function to
handle SIGUSR1 signal. Call function which is defined in the cfg file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def init_service_processes(self):
"""
Prepare processes defined in the **settings.SERVICE_PROCESSES**.
Return :class:`list` of the :class:`ProcessWrapper` instances.
"""
processes = []
for process_struct in getattr(
self.context.config.settings, 'SERVICE_... | Can you create a Python 3 function that
initializes the service processes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Prepare worker instances for all Tornado applications. Return a list of the ProcessWrapper instances. | Explain what the following Python 3 code does
def init_tornado_workers(self):
workers = []
for tornado_app in get_tornado_apps(self.context, debug=False):
interface = tornado_app.settings['interface']
if not interface.port and not interface.unix_socket:
raise Va... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Start processes and check their status. When some processes crashes start it again. | Can you generate a brief explanation for the following Python 3 code
def start_processes(self, max_restarts=-1):
while 1:
for process in self.processes:
if not process:
# When process has not been started, start it
if not process.has_started:
... | As a python code expert, you are capable of creating scripts from specifications. |
def taxtable_to_tree(handle):
"""Read a CSV taxonomy from *handle* into a Tree."""
c = csv.reader(handle, quoting=csv.QUOTE_NONNUMERIC)
header = next(c)
rootdict = dict(list(zip(header, next(c))))
t = Tree(rootdict['tax_id'], rank=rootdict[
'rank'], tax_name=rootdict['tax_name'])
fo... | Implement a Python 3 function for
reading a CSV taxonomy from handle into a Tree. | You are a Python code analyst, evaluating scripts for potential improvements. |
def lonely_company(taxonomy, tax_ids):
"""Return a set of species tax_ids which will makes those in *tax_ids* not lonely.
The returned species will probably themselves be lonely.
"""
return [taxonomy.species_below(taxonomy.sibling_of(t)) for t in tax_ids] | Can you implement a function in Python 3 that
returns a set of species tax_ids which will make those in tax_ids not lonely. | You are a Python code architect, reviewing and designing scalable and efficient code |
def solid_company(taxonomy, tax_ids):
"""Return a set of non-lonely species tax_ids that will make those in *tax_ids* not lonely."""
res = []
for t in tax_ids:
res.extend(taxonomy.nary_subtree(taxonomy.sibling_of(t), 2) or [])
return res | Write a Python 3 script to
return a set of non - lonely species tax_ids that will make those in tax_ids not lonely. | You are a Python code analyst, evaluating scripts for potential improvements. |
def eval_algorithm(curr, prev):
""" Evaluates OBV
Args:
curr: Dict of current volume and close
prev: Dict of previous OBV and close
Returns:
Float of OBV
"""
if curr['close'] > prev['close']:
v = curr['volume']
elif curr['... | Implement a function in Python 3 to
evaluate the algorithm of the OBV . | As a Python code composer, you craft elegant and concise scripts. |
def eval_from_json(json):
""" Evaluates OBV from JSON (typically Poloniex API response)
Args:
json: List of dates where each entry is a dict of raw market data.
Returns:
Float of OBV
"""
closes = poloniex.get_attribute(json, 'close')
volumes = po... | Can you write a function in Python 3 where it
evaluates the OBV from a JSON object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def scratch_file(unlink=True, **kwargs):
"""Create a temporary file and return its name.
Additional arguments are passed to :class:`tempfile.NamedTemporaryFile`
At the start of the with block a secure, temporary file is created
and its name returned. At the end of the with block it is
deleted.
... | Write a Python 3 script for
creating a temporary file and return its name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def open(self, name, *mode):
"""
Return an open file object for a file in the reference package.
"""
return self.file_factory(self.file_path(name), *mode) | Create a Python 3 function to
return an open file object for a file in the reference package. | As a python code expert, you are capable of creating scripts from specifications. |
def open_resource(self, resource, *mode):
"""
Return an open file object for a particular named resource in this
reference package.
"""
return self.open(self.resource_name(resource), *mode) | Write a Python 3 function that can
return an open file object for a particular resource in this reference package. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the name of the file within the reference package for a particular named resource. | Explain what the following Python 3 code does
def resource_name(self, resource):
if not(resource in self.contents['files']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['files'][resource] | You are a Python code generator, capable of creating scripts from specifications. |
def resource_md5(self, resource):
"""Return the stored MD5 sum for a particular named resource."""
if not(resource in self.contents['md5']):
raise ValueError("No such resource %r in refpkg" % (resource,))
return self.contents['md5'][resource] | Implement a function in Python 3 to
return the stored MD5 sum for a particular resource. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _set_defaults(self):
"""
Set some default values in the manifest.
This method should be called after loading from disk, but before
checking the integrity of the reference package.
"""
self.contents.setdefault('log', [])
self.contents.setdefault('rollback', No... | Implement a function in Python 3 to
set some default values in the manifest. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _sync_to_disk(self):
"""Write any changes made on Refpkg to disk.
Other methods of Refpkg that alter the contents of the package
will call this method themselves. Generally you should never
have to call it by hand. The only exception would be if
another program has changed... | Can you implement a function in Python 3 that
writes any changes made on Refpkg to disk. | You are a Python code architect, reviewing and designing scalable and efficient code |
Read any changes made on disk to this Refpkg. | Explain what the following Python 3 code does
def _sync_from_disk(self):
try:
fobj = self.open_manifest('r')
except IOError as e:
if e.errno == errno.ENOENT:
raise ValueError(
"couldn't find manifest file in %s" % (self.path,))
eli... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _add_file(self, key, path):
"""Copy a file into the reference package."""
filename = os.path.basename(path)
base, ext = os.path.splitext(filename)
if os.path.exists(self.file_path(filename)):
with tempfile.NamedTemporaryFile(
dir=self.path, prefix=base... | Create a Python 3 function for
copying a file into the reference package. | You are a Python code architect, reviewing and designing scalable and efficient code |
Checks if this RefPkg is invalid. | Can you tell what is the following Python 3 function doing
def is_invalid(self):
# Manifest file contains the proper keys
for k in ['metadata', 'files', 'md5']:
if not(k in self.contents):
return "Manifest file missing key %s" % k
if not(isinstance(self.contents[k... | As a Python code composer, you craft elegant and concise scripts. |
def update_metadata(self, key, value):
"""Set *key* in the metadata to *value*.
Returns the previous value of *key*, or None if the key was
not previously set.
"""
old_value = self.contents['metadata'].get(key)
self.contents['metadata'][key] = value
self._log('Up... | Write a Python 3 script for
updating the metadata for the specified key. Returns the previous value of key. | As a Python code analyst, you investigate and solve complex coding mysteries |
def update_file(self, key, new_path):
"""Insert file *new_path* into the refpkg under *key*.
The filename of *new_path* will be preserved in the refpkg
unless it would conflict with a previously existing file, in
which case a suffix is appended which makes it unique. The
previo... | Create a Python 3 function to
update the file with the given key. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Reroot the phylogenetic tree. | Make a summary of the following Python 3 code
def reroot(self, rppr=None, pretend=False):
with scratch_file(prefix='tree', suffix='.tre') as name:
# Use a specific path to rppr, otherwise rely on $PATH
subprocess.check_call([rppr or 'rppr', 'reroot',
'-... | You are a Python code architect, reviewing and designing scalable and efficient code |
def update_phylo_model(self, stats_type, stats_file, frequency_type=None):
"""Parse a stats log and use it to update ``phylo_model``.
``pplacer`` expects its input to include the deatils of the
phylogenetic model used for creating a tree in JSON format
under the key ``phylo_model``, but... | How would you code a function in Python 3 to
parse a stats log and use it to update the phylo model. | You are a Python code generator, capable of creating scripts from specifications. |
Revert the previous modification to the refpkg. | How would you explain what the following Python 3 function does
def rollback(self):
# This is slightly complicated because of Python's freakish
# assignment semantics and because we don't store multiple
# copies of the log.
if self.contents['rollback'] is None:
raise ValueErr... | As a python code expert, you are capable of creating scripts from specifications. |
def rollforward(self):
"""Restore a reverted modification to the refpkg.
"""
if self.contents['rollforward'] is None:
raise ValueError("No operation to roll forward on refpkg")
new_log_message = self.contents['rollforward'][0]
new_contents = self.contents['rollforward... | Write a Python 3 script to
restore a reverted modification to the refpkg. | You are a Python code architect, reviewing and designing scalable and efficient code |
def strip(self):
"""Remove rollbacks, rollforwards, and all non-current files.
When distributing a refpkg, you probably want to distribute as
small a one as possible. strip removes everything from the
refpkg which is not relevant to its current state.
"""
self._sync_fro... | Can you implement a function in Python 3 that
removes rollbacks rollforwards and all non - current files. | As a python code expert, you are capable of creating scripts from specifications. |
def start_transaction(self):
"""Begin a transaction to group operations on the refpkg.
All the operations until the next call to
``commit_transaction`` will be recorded as a single operation
for rollback and rollforward, and recorded with a single line
in the log.
"""
... | Write a Python 3 function that can
begin a transaction to group operations on the refpkg. | As a python code expert, you are capable of creating scripts from specifications. |
def commit_transaction(self, log=None):
"""Commit a transaction, with *log* as the log entry."""
self.current_transaction['rollback'].pop('log')
self.current_transaction['rollback'].pop('rollforward')
self.contents['log'].insert(
0, log and log or self.current_transaction['lo... | How would you code a function in Python 3 to
commit a transaction with a given log entry. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_db(self):
"""Load the taxonomy into a sqlite3 database.
This will set ``self.db`` to a sqlite3 database which contains all of
the taxonomic information in the reference package.
"""
db = taxdb.Taxdb()
db.create_tables()
reader = csv.DictReader(self.open... | Can you implement a function in Python 3 that
loads the taxonomy into a sqlite3 database. | As a python code expert, you are capable of creating scripts from specifications. |
def most_recent_common_ancestor(self, *ts):
"""Find the MRCA of some tax_ids.
Returns the MRCA of the specified tax_ids, or raises ``NoAncestor`` if
no ancestor of the specified tax_ids could be found.
"""
if len(ts) > 200:
res = self._large_mrca(ts)
else:
... | Can you write a function in Python 3 where it
finds the most recent common ancestor of the specified tax_ids. | You are a Python code architect, reviewing and designing scalable and efficient code |
Find the MRCA using a temporary table. | How would you explain what the following Python 3 function does
def _large_mrca(self, ts):
cursor = self.db.cursor()
cursor.execute("""
DROP TABLE IF EXISTS _mrca_temp
""")
cursor.execute("""
CREATE TEMPORARY TABLE _mrca_temp(
child TEXT PRIMARY ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Find a small MRCA using query parameters. | Explain what the following Python 3 code does
def _small_mrca(self, ts):
cursor = self.db.cursor()
qmarks = ', '.join('?' * len(ts))
cursor.execute("""
SELECT parent
FROM parents
JOIN taxa
ON parent = taxa.tax_id
... | As a Python code composer, you craft elegant and concise scripts. |
Deprecated alias for resource_path *. | Given the following Python 3 function, write the documentation
def file_abspath(self, resource):
warnings.warn(
"file_abspath is deprecated; use resource_path instead",
DeprecationWarning, stacklevel=2)
return self.resource_path(resource) | As a python code expert, you are capable of creating scripts from specifications. |
Deprecated alias for resource_name. | Can you tell what is the following Python 3 function doing
def file_name(self, resource):
warnings.warn(
"file_name is deprecated; use resource_name instead",
DeprecationWarning, stacklevel=2)
return self.resource_name(resource) | You are a Python code architect, reviewing and designing scalable and efficient code |
def file_md5(self, resource):
"""Deprecated alias for *resource_md5*."""
warnings.warn(
"file_md5 is deprecated; use resource_md5 instead",
DeprecationWarning, stacklevel=2)
return self.resource_md5(resource) | Create a Python 3 function to
deprecate alias for resource_md5. Use resource_md5 instead. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_app_settings(parser, known_args):
"""
Return **settings** module of the application according to
either command line argument or **SHELTER_SETTINGS_MODULE**
environment variable.
"""
args, dummy_remaining = parser.parse_known_args(known_args)
settings_module_path = (
args.set... | Write a Python 3 script to
return the settings module of the application according to the command line argument or the SHELTER_SETTINGS_MODULE environment variable. | As a python code expert, you are capable of creating scripts from specifications. |
def get_management_commands(settings):
"""
Find registered managemend commands and return their classes
as a :class:`dict`. Keys are names of the management command
and values are classes of the management command.
"""
app_commands = getattr(settings, 'MANAGEMENT_COMMANDS', ())
commands = {}... | How would you implement a function in Python 3 that
returns a dictionary of all management commands registered in the settings. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_config_class(settings):
"""
According to **settings.CONFIG_CLASS** return either config class
defined by user or default :class:`shelter.core.config.Config`.
"""
config_cls_name = getattr(settings, 'CONFIG_CLASS', '')
if config_cls_name:
config_cls = import_object(config_cls_name... | Write a Python 3 script for
returning either config class or default. | As a Python code composer, you craft elegant and concise scripts. |
Main function for the management command line. | Can you tell what is the following Python 3 function doing
def main(args=None):
# Base command line parser. Help is not allowed because command
# line is parsed in two stages - in the first stage is found setting
# module of the application, in the second stage are found management
# command's arguments... | You are a Python code generator, capable of creating scripts from specifications. |
Return a new vector scaled to given length | Can you tell what is the following Python 3 function doing
def as_length(self, value):
new_vec = self.copy()
new_vec.length = value
return new_vec | As a python code expert, you are capable of creating scripts from specifications. |
Return a new vector scaled by given decimal percent | Here you have a function in Python 3, explain what it does
def as_percent(self, value):
new_vec = self.copy()
new_vec.length = value * self.length
return new_vec | As a python code expert, you are 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.