output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def loaders(*specifiers):
"""
Generates loaders in the specified order.
Arguments can be `.Locality` instances, producing the loader(s) available
for that locality, `str` instances (used as file path templates) or
`callable`s. These can be mixed:
.. code-block:: python
# define a load... | Implement a Python 3 function for
generating a generator that yields the available locality loaders for the specified locality. | You are a Python code generator, capable of creating scripts from specifications. |
def load(*fps, missing=Missing.silent):
"""
Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Con... | Can you write a function in Python 3 where it
reads a. Configuration instance from file - like objects. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def loadf(*fnames, default=_NoDefault, missing=Missing.silent):
"""
Read a `.Configuration` instance from named files.
:param fnames: name of the files to ``open()``
:param default: `dict` or `.Configuration` to use when a file does not
exist (default is to raise a `FileNotFoundError`)
:par... | Write a Python 3 function for
reading a. Configuration instance from named files. | You are a Python code analyst, evaluating scripts for potential improvements. |
def loads(*strings, missing=Missing.silent):
"""
Read a `.Configuration` instance from strings.
:param strings: configuration contents
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Configuration` instance ... | Can you implement a function in Python 3 that
reads a. Configuration instance from a list of strings. | You are a Python code analyst, evaluating scripts for potential improvements. |
Read a. Configuration instance by name. | Can you generate a brief explanation for the following Python 3 code
def load_name(*names, load_order=DEFAULT_LOAD_ORDER, extension='yaml', missing=Missing.silent):
def generate_sources():
# argument order for product matters, for names "foo" and "bar":
# /etc/foo.yaml before /etc/bar.yaml, but both... | You are a Python code generator, capable of creating scripts from specifications. |
Acquire lock. Blocks until acquired if block is True otherwise returns False. | Can you generate a brief explanation for the following Python 3 code
def acquire(self, block=True):
while True:
# Try to set the lock
if self.redis.set(self.name, self.value, px=self.timeout, nx=True):
# It's ours until the timeout now
return True
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def refresh(self):
"""Refresh an existing lock to prevent it from expiring.
Uses a LUA (EVAL) script to ensure only a lock which we own is being overwritten.
Returns True if refresh succeeded, False if not."""
keys = [self.name]
args = [self.value, self.timeout]
# Redis d... | Can you create a Python 3 function that
refreshes an existing lock. | As a Python code analyst, you investigate and solve complex coding mysteries |
Run the process if nobody else is. | Given the following Python 3 function, write the documentation
def run(self):
log.info("Waiting for lock, currently held by %s", self.lock.who())
if self.lock.acquire():
log.info("Lock '%s' acquired", self.lockname)
# We got the lock, so we make sure the process is running and k... | As a Python code composer, you craft elegant and concise scripts. |
Clean up making sure the process is stopped before we pack up and go home. | How would you explain what the following Python 3 function does
def cleanup(self):
if self.process is None: # Process wasn't running yet, so nothing to worry about
return
if self.process.poll() is None:
log.info("Sending TERM to %d", self.process.pid)
self.process.te... | As a Python code analyst, you investigate and solve complex coding mysteries |
def validate(data, schema, defined_keys=False):
"""
Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against
"""
if isinstance(data, dict):
validator = Validator(data, schema, ... | Write a Python 3 script to
validate the incoming data against the current node s node s node s schema. | You are a Python code architect, reviewing and designing scalable and efficient code |
def traverser(self, data, schema, tree):
"""
Traverses the dictionary, recursing onto itself if
it sees appropriate key/value pairs that indicate that
there is a need for more validation in a branch below us.
"""
if hasattr(schema, '__validator_leaf__'):
retur... | Can you implement a function in Python 3 that
traverses the dictionary and checks if the data is valid for a particular key value pair. | As a python code expert, you are capable of creating scripts from specifications. |
def key_leaf(self, data, schema, tree):
"""
The deepest validation we can make in any given circumstance for a key.
Does not recurse, it will just receive both values and the tree,
passing them on to the :fun:`enforce` function.
"""
key, value = data
schema_key, s... | Implement a Python 3 function for
validating that a key is a leaf of a tree. | You are a Python code generator, capable of creating scripts from specifications. |
Validate that a value is a leaf of a tree. | Can you tell what is the following Python 3 function doing
def value_leaf(self, data, schema, tree):
key, value = data
schema_key, schema_value = schema
if hasattr(schema_value, '__validator_leaf__'):
return schema_value(value, tree)
enforce(value, schema_value, tree, 'value... | As a Python code analyst, you investigate and solve complex coding mysteries |
def strfdelta(tdelta, fmt):
"""
Used to format `datetime.timedelta` objects. Works just like `strftime`
>>> strfdelta(duration, '%H:%M:%S')
param tdelta: Time duration which is an instance of datetime.timedelta
param fmt: The pattern to format the timedelta with
rtype: str
"""
substitu... | Write a Python 3 script to
return a string representation of a datetime. timedelta object. Works just like strftime | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_user_information():
"""
Returns the user's information
:rtype: (str, int, str)
"""
try:
import pwd
_username = pwd.getpwuid(os.getuid())[0]
_userid = os.getuid()
_uname = os.uname()[1]
except ImportError:
import getpass
_username = getpass... | Implement a function in Python 3 to
return the user s information | As a Python code composer, you craft elegant and concise scripts. |
def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None):
"""
Authenticate APP using token credentials:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
:return: ~ServicePrincipalCredentials credentials
"""
... | Write a Python 3 function that can
authenticate the App using the token credentials. | You are a Python code architect, reviewing and designing scalable and efficient code |
Prepare a docker image that will run in the cloud, mounting the asset and executing the algorithm.
:param asset_url
:param algorithm_url
:param resource_group_name:
:param account_name:
:param account_key:
:param share_name_input:
:param share_name_output:
... | Make a summary of the following Python 3 code
def exec_container(self,
asset_url,
algorithm_url,
resource_group_name,
account_name,
account_key,
location,
shar... | You are a Python code architect, reviewing and designing scalable and efficient code |
Lists the container groups in the specified resource group. | Can you generate the documentation for the following Python 3 function
def list_container_groups(self, resource_group_name):
print("Listing container groups in resource group '{0}'...".format(resource_group_name))
container_groups = self.client.container_groups.list_by_resource_group(resource_group_nam... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def fastalite(handle):
"""Return a sequence of namedtuple objects from a fasta file with
attributes (id, description, seq) given open file-like object
``handle``
"""
Seq = namedtuple('Seq', ['id', 'description', 'seq'])
header, seq = '', []
for line in handle:
if line.startswith('... | Implement a Python 3 function for
returning a sequence of namedtuple objects from a fasta file with attributes ( id description seq | You are a Python code analyst, evaluating scripts for potential improvements. |
def fastqlite(handle):
"""Return a sequence of namedtuple objects from a fastq file with
attributes (id, description, seq, qual) given open file-like
object ``handle``. This parser assumes that lines corresponding to
sequences and quality scores are not wrapped. Raises
``ValueError`` for malformed r... | How would you implement a function in Python 3 that
returns a sequence of namedtuple objects from a fastq file with attributes ( id description seq qual | You are a Python code analyst, evaluating scripts for potential improvements. |
def cauldron_extras(self):
""" Yield extra tuples containing a field name and a callable that takes
a row
"""
for extra in super(Dimension, self).cauldron_extras:
yield extra
if self.formatters:
prop = self.id + '_raw'
else:
prop = sel... | Write a Python 3 function that can
yield extra tuples containing a field name and a callable that takes a row | As a Python code translator, you convert algorithms and pseudocode into Python. |
Make sure we have the right column suffixes. | How would you explain what the following Python 3 function does
def make_column_suffixes(self):
if self.column_suffixes:
return self.column_suffixes
if len(self.columns) == 0:
return ()
elif len(self.columns) == 1:
if self.formatters:
return ... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_condition(
cond, selectable, aggregated=False, default_aggregation='sum'
):
"""Create a SQLAlchemy clause from a condition."""
if cond is None:
return None
else:
if 'and' in cond:
conditions = [
parse_condition(
c, selectable, ag... | Create a Python 3 function to
create a SQLAlchemy clause from a condition. | You are a Python code analyst, evaluating scripts for potential improvements. |
Tokenize a string by splitting it by + and - and return a list of words. | Make a summary of the following Python 3 code
def tokenize(s):
# Crude tokenization
s = s.replace('+', ' PLUS ').replace('-', ' MINUS ') \
.replace('/', ' DIVIDE ').replace('*', ' MULTIPLY ')
words = [w for w in s.split(' ') if w]
return words | As a Python code analyst, you investigate and solve complex coding mysteries |
def _find_in_columncollection(columns, name):
""" Find a column in a column collection by name or _label"""
for col in columns:
if col.name == name or getattr(col, '_label', None) == name:
return col
return None | How would you code a function in Python 3 to
find a column in a column collection by name or _label | You are a Python code architect, reviewing and designing scalable and efficient code |
def find_column(selectable, name):
"""
Find a column named `name` in selectable
:param selectable:
:param name:
:return: A column object
"""
from recipe import Recipe
if isinstance(selectable, Recipe):
selectable = selectable.subquery()
# Selectable is a table
if isins... | Implement a function in Python 3 to
find a column named name in selectable | As a python code expert, you are capable of creating scripts from specifications. |
def parse_field(fld, selectable, aggregated=True, default_aggregation='sum'):
""" Parse a field object from yaml into a sqlalchemy expression """
# An aggregation is a callable that takes a single field expression
# None will perform no aggregation
aggregation_lookup = {
'sum': func.sum,
... | Implement a Python 3 function for
parsing a field object from yaml into a sqlalchemy expression | You are a Python code generator, capable of creating scripts from specifications. |
def ingredient_from_dict(ingr_dict, selectable):
"""Create an ingredient from an dictionary.
This object will be deserialized from yaml """
# TODO: This is deprecated in favor of
# ingredient_from_validated_dict
# Describe the required params for each kind of ingredient
# The key is the param... | How would you code a function in Python 3 to
create an ingredient from a dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
Converts a validated field to sqlalchemy. Field references are kept in selectable | Explain what the following Python 3 code does
def parse_validated_field(fld, selectable):
aggr_fn = IngredientValidator.aggregation_lookup[fld['aggregation']]
field = find_column(selectable, fld['value'])
for operator in fld.get('operators', []):
op = operator['operator']
other_field = par... | You are a Python code analyst, evaluating scripts for potential improvements. |
def ingredient_from_validated_dict(ingr_dict, selectable):
""" Create an ingredient from an dictionary.
This object will be deserialized from yaml """
validator = IngredientValidator(schema=ingr_dict['kind'])
if not validator.validate(ingr_dict):
raise Exception(validator.errors)
ingr_dict... | Write a Python 3 function that can
create an ingredient from a dictionary. | As a Python code composer, you craft elegant and concise scripts. |
Auto generate a Shelf from a SQLAlchemy Table. | Given the following Python 3 function, write the documentation
def AutomaticShelf(table):
if hasattr(table, '__table__'):
table = table.__table__
config = introspect_table(table)
return Shelf.from_config(config, table) | You are a Python code generator, capable of creating scripts from specifications. |
Given a SQLAlchemy Table object return a Shelf description suitable
for passing to Shelf. from_config.
| Given the following Python 3 function, write the documentation
def introspect_table(table):
d = {}
for c in table.columns:
if isinstance(c.type, String):
d[c.name] = {'kind': 'Dimension', 'field': c.name}
if isinstance(c.type, (Integer, Float)):
d[c.name] = {'kind': 'Metr... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pop(self, k, d=_POP_DEFAULT):
"""Pop an ingredient off of this shelf."""
if d is _POP_DEFAULT:
return self._ingredients.pop(k)
else:
return self._ingredients.pop(k, d) | Create a Python 3 function to
pop an ingredient off of this shelf. | As a python code expert, you are capable of creating scripts from specifications. |
def dimension_ids(self):
""" Return the Dimensions on this shelf in the order in which
they were used."""
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Dimension)
]) | Can you implement a function in Python 3 that
returns the list of Dimension objects on this shelf in the order in which they were used. | You are a Python code generator, capable of creating scripts from specifications. |
def metric_ids(self):
""" Return the Metrics on this shelf in the order in which
they were used. """
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Metric)
]) | Can you implement a function in Python 3 that
returns the list of Metrics on this shelf in the order in which they were used. | As a python code expert, you are capable of creating scripts from specifications. |
Return the IDs of all the Filtered Metrics on this shelf. | How would you explain what the following Python 3 function does
def filter_ids(self):
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Filter)
]) | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_config(
cls,
obj,
selectable,
ingredient_constructor=ingredient_from_validated_dict,
metadata=None
):
"""Create a shelf using a dict shelf definition.
:param obj: A Python dictionary describing a Shelf.
:param selectable: A SQLAlchemy Table, ... | Implement a function in Python 3 to
create a new Shelf from a dictionary containing a dictionary containing ingredients defined in obj. | You are a Python code generator, capable of creating scripts from specifications. |
def from_yaml(cls, yaml_str, selectable, **kwargs):
"""Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf that ... | Implement a Python 3 function for
creating a shelf from a yaml string containing the ingredients defined in the yaml file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_validated_yaml(cls, yaml_str, selectable, **kwargs):
"""Create a shelf using a yaml shelf definition.
:param yaml_str: A string containing yaml ingredient definitions.
:param selectable: A SQLAlchemy Table, a Recipe, or a SQLAlchemy
join to select from.
:return: A shelf... | How would you implement a function in Python 3 that
creates a shelf from a validated yaml string. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find(self, obj, filter_to_class=Ingredient, constructor=None):
"""
Find an Ingredient, optionally using the shelf.
:param obj: A string or Ingredient
:param filter_to_class: The Ingredient subclass that obj must be an
instance of
:param constructor: An optional call... | Can you implement a function in Python 3 that
finds an Ingredient optionally using the shelf. | You are a Python code generator, capable of creating scripts from specifications. |
Make columns group_bys filters havings
| Can you generate the documentation for the following Python 3 function
def brew_query_parts(self):
columns, group_bys, filters, havings = [], [], set(), set()
for ingredient in self.ingredients():
if ingredient.query_columns:
columns.extend(ingredient.query_columns)
... | You are a Python code generator, capable of creating scripts from specifications. |
Add any calculated values to each row of a resultset generating a namedtuple containing the values of all the ingredients that have been added for that sample. | Can you tell what is the following Python 3 function doing
def enchant(self, list, cache_context=None):
enchantedlist = []
if list:
sample_item = list[0]
# Extra fields to add to each row
# With extra callables
extra_fields, extra_callables = [], []
... | You are a Python code generator, capable of creating scripts from specifications. |
Toggles whether automatic filters are applied to a recipe. | Can you generate a brief explanation for the following Python 3 code
def apply_automatic_filters(self, value):
if self.apply != value:
self.dirty = True
self.apply = value
return self.recipe | You are a Python code generator, capable of creating scripts from specifications. |
Sets the automatic_filters dictionary to apply to this recipe. | Make a summary of the following Python 3 code
def automatic_filters(self, value):
assert isinstance(value, dict)
self._automatic_filters = value
self.dirty = True
return self.recipe | You are a Python code architect, reviewing and designing scalable and efficient code |
Modify the postquery_parts dictionary with the information from the recipe that has dimensions
Resummarize it over one of the dimensions returning averages of the aracite metrics. | Can you generate the documentation for the following Python 3 function
def modify_postquery_parts(self, postquery_parts):
if self._summarize_over is None:
return postquery_parts
assert self._summarize_over in self.recipe.dimension_ids
# Start with a subquery
subq = postquery... | You are a Python code analyst, evaluating scripts for potential improvements. |
Should this recipe be anonymized | Explain what the following Python 3 code does
def anonymize(self, value):
assert isinstance(value, bool)
if self._anonymize != value:
self.dirty = True
self._anonymize = value
# Builder pattern must return the recipe
return self.recipe | As a Python code composer, you craft elegant and concise scripts. |
Add anonymizers to the last position of formatters | Given the following Python 3 function, write the documentation
def add_ingredients(self):
for ingredient in self.recipe._cauldron.values():
if hasattr(ingredient.meta, 'anonymizer'):
anonymizer = ingredient.meta.anonymizer
# Build a FakerAnonymizer if we have a strin... | You are a Python code generator, capable of creating scripts from specifications. |
Blends a base recipe into the base recipe. | Can you generate a brief explanation for the following Python 3 code
def blend(self, blend_recipe, join_base, join_blend):
assert isinstance(blend_recipe, Recipe)
self.blend_recipes.append(blend_recipe)
self.blend_types.append('inner')
self.blend_criteria.append((join_base, join_blend))... | You are a Python code architect, reviewing and designing scalable and efficient code |
Modify the postquery_parts dictionary with the values of the related recipe and the values of the related recipe. | Here you have a function in Python 3, explain what it does
def modify_postquery_parts(self, postquery_parts):
if not self.blend_recipes:
return postquery_parts
for blend_recipe, blend_type, blend_criteria in \
zip(self.blend_recipes,
self.blend_types,
... | As a Python code composer, you craft elegant and concise scripts. |
Adds a comparison recipe to a base recipe. | Can you generate a brief explanation for the following Python 3 code
def compare(self, compare_recipe, suffix='_compare'):
assert isinstance(compare_recipe, Recipe)
assert isinstance(suffix, basestring)
self.compare_recipe.append(compare_recipe)
self.suffix.append(suffix)
self.di... | You are a Python code analyst, evaluating scripts for potential improvements. |
Modify the postquery_parts dictionary with the values of the base recipe and the values of the base recipe. | Can you generate a brief explanation for the following Python 3 code
def modify_postquery_parts(self, postquery_parts):
if not self.compare_recipe:
return postquery_parts
for compare_recipe, compare_suffix in zip(
self.compare_recipe, self.suffix
):
compariso... | As a Python code analyst, you investigate and solve complex coding mysteries |
def list(self, container_or_share_name, container=None, account=None):
"""List the blobs/files inside a container/share_name.
Args:
container_or_share_name(str): Name of the container/share_name where we want to list the blobs/files.
container(bool): flag to know it you are li... | Can you implement a function in Python 3 that
lists the blobs and files inside a container or share. | As a python code expert, you are capable of creating scripts from specifications. |
def generate_url(self, remote_file):
"""Sign a remote file to distribute. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
remote_file(str): The blob that we want to sign.
"""
parse_url = _parse_url(remote_file)
key = self.st... | Write a Python 3 script for
generating a URL for the remote file to distribute. | You are a Python code architect, reviewing and designing scalable and efficient code |
Delete a file from the cloud. | How would you explain what the following Python 3 function does
def delete(self, remote_file):
if 'core.windows.net' not in remote_file:
self.logger.error("Source or destination must be a azure storage url (format "
"https://myaccount.blob.core.windows.net/mycontainer/m... | As a Python code composer, you craft elegant and concise scripts. |
def copy(self, source_path, dest_path, account=None, group_name=None):
"""Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
source_path(str): The path of the file to be copied.
dest_path(str): The d... | Can you implement a function in Python 3 that
copies a file from one path to another. | You are a Python code generator, capable of creating scripts from specifications. |
def prettyprintable_sql(statement, dialect=None, reindent=True):
"""
Generate an SQL expression string with bound parameters rendered inline
for the given SQLAlchemy statement. The function can also receive a
`sqlalchemy.orm.Query` object instead of statement.
WARNING: Should only be used for debug... | Can you write a function in Python 3 where it
returns a SQL expression string that can be used to render a SQLAlchemy query. | As a python code expert, you are capable of creating scripts from specifications. |
Replace a format with a default value | Can you generate the documentation for the following Python 3 function
def _normalize_coerce_to_format_with_lookup(self, v):
try:
return self.format_lookup.get(v, v)
except TypeError:
# v is something we can't lookup (like a list)
return v | You are a Python code generator, capable of creating scripts from specifications. |
Coerce a string to a dict. | Make a summary of the following Python 3 code
def _normalize_coerce_to_field_dict(self, v):
def tokenize(s):
""" Tokenize a string by splitting it by + and -
>>> tokenize('this + that')
['this', '+', 'that']
>>> tokenize('this+that')
['this', '+', '... | As a Python code analyst, you investigate and solve complex coding mysteries |
Is not a list or dict | Given the following Python 3 function, write the documentation
def _validate_type_scalar(self, value):
if isinstance(
value, _int_types + (_str_type, float, date, datetime, bool)
):
return True | As a Python code analyst, you investigate and solve complex coding mysteries |
def from_config(cls, shelf, obj, **kwargs):
"""
Construct a Recipe from a plain Python dictionary.
Most of the directives only support named ingredients, specified as
strings, and looked up on the shelf. But filters can be specified as
objects.
Additionally, each Recipe... | Write a Python 3 function that can
construct a Recipe from a plain Python dictionary. | You are a Python code architect, reviewing and designing scalable and efficient code |
Defines a shelf to use for this recipe | How would you explain what the following Python 3 function does
def shelf(self, shelf=None):
if shelf is None:
self._shelf = Shelf({})
elif isinstance(shelf, Shelf):
self._shelf = shelf
elif isinstance(shelf, dict):
self._shelf = Shelf(shelf)
else:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def metrics(self, *metrics):
""" Add a list of Metric ingredients to the query. These can either be
Metric objects or strings representing metrics on the shelf.
The Metric expression will be added to the query's select statement.
The metric value is a property of each row of the result.... | Write a Python 3 function for
adding a list of Metric ingredients to the recipe. | As a python code expert, you are capable of creating scripts from specifications. |
Add a list of Dimension ingredients to the recipe. | Can you generate a brief explanation for the following Python 3 code
def dimensions(self, *dimensions):
for d in dimensions:
self._cauldron.use(self._shelf.find(d, Dimension))
self.dirty = True
return self | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a list of filters to the recipe. | Explain what the following Python 3 code does
def filters(self, *filters):
def filter_constructor(f, shelf=None):
if isinstance(f, BinaryExpression):
return Filter(f)
else:
return f
for f in filters:
self._cauldron.use(
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def order_by(self, *order_bys):
""" Add a list of ingredients to order by to the query. These can
either be Dimension or Metric objects or strings representing
order_bys on the shelf.
The Order_by expression will be added to the query's order_by statement
:param order_bys: Orde... | Implement a Python 3 function for
adding a list of ingredients to order_by to the recipe. | You are a Python code generator, capable of creating scripts from specifications. |
def limit(self, limit):
""" Limit the number of rows returned from the database.
:param limit: The number of rows to return in the recipe. 0 will
return all rows.
:type limit: int
"""
if self._limit != limit:
self.dirty = True
self._... | Write a Python 3 function for
limiting the number of rows returned from the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Offset the number of rows before returning rows from the database. | Here you have a function in Python 3, explain what it does
def offset(self, offset):
if self._offset != offset:
self.dirty = True
self._offset = offset
return self | As a Python code analyst, you investigate and solve complex coding mysteries |
Determine if the running engine is postgres. | Explain what the following Python 3 code does
def _is_postgres(self):
if self._is_postgres_engine is None:
is_postgres_engine = False
try:
dialect = self.session.bind.engine.name
if 'redshift' in dialect or 'postg' in dialect or 'pg' in \
... | As a Python code composer, you craft elegant and concise scripts. |
Build a list of order by columns | Here you have a function in Python 3, explain what it does
def _prepare_order_bys(self):
order_bys = OrderedSet()
if self._order_bys:
for ingredient in self._order_bys:
if isinstance(ingredient, Dimension):
# Reverse the ordering columns so that dimensions... | As a Python code composer, you craft elegant and concise scripts. |
def query(self):
"""
Generates a query using the ingredients supplied by the recipe.
:return: A SQLAlchemy query
"""
if len(self._cauldron.ingredients()) == 0:
raise BadRecipe('No ingredients have been added to this recipe')
if not self.dirty and self._query:... | Write a Python 3 function for
generating a SQLAlchemy query for the current set of ingredients for the current cauldron entry. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if the recipe is dirty False otherwise | Can you generate the documentation for the following Python 3 function
def dirty(self):
if self._dirty:
return True
else:
for extension in self.recipe_extensions:
if extension.dirty:
return True
return False | As a Python code translator, you convert algorithms and pseudocode into Python. |
def dirty(self, value):
""" If dirty is true set the recipe to dirty flag. If false,
clear the recipe and all extension dirty flags """
if value:
self._dirty = True
else:
self._dirty = False
for extension in self.recipe_extensions:
exte... | Create a Python 3 function to
set the recipe to dirty flag. | As a Python code composer, you craft elegant and concise scripts. |
Return an alias to a table name. | Can you tell what is the following Python 3 function doing
def as_table(self, name=None):
if name is None:
name = self._id
return alias(self.subquery(), name=name) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a list of result objects. | Can you generate the documentation for the following Python 3 function
def all(self):
starttime = fetchtime = enchanttime = time.time()
fetched_from_cache = False
if self.dirty or self.all_dirty:
query = self.query()
self._all = query.all()
# If we're using a... | As a Python code composer, you craft elegant and concise scripts. |
Validates that all of the keys in one of the sets of keys in value are defined as keys of value. | Make a summary of the following Python 3 code
def _validate_condition_keys(self, field, value, error):
if 'field' in value:
operators = self.nonscalar_conditions + self.scalar_conditions
matches = sum(1 for k in operators if k in value)
if matches == 0:
error(... | You are a Python code generator, capable of creating scripts from specifications. |
def survival(self,parents,offspring,elite=None,elite_index=None,X=None,X_O=None,F=None,F_O=None):
"""routes to the survival method, returns survivors"""
if self.sel == 'tournament':
survivors, survivor_index = self.tournament(parents + offspring, self.tourn_size, num_selections = len(parents... | Implement a Python 3 function for
routing to the survival method returns survivors | As a python code expert, you are capable of creating scripts from specifications. |
conducts tournament selection of size tourn_size | Make a summary of the following Python 3 code
def tournament(self,individuals,tourn_size, num_selections=None):
winners = []
locs = []
if num_selections is None:
num_selections = len(individuals)
for i in np.arange(num_selections):
# sample pool with replacement
... | As a Python code analyst, you investigate and solve complex coding mysteries |
conducts lexicase selection for de - aggregated fitness vectors | Can you generate a brief explanation for the following Python 3 code
def lexicase(self,F, num_selections=None, survival = False):
if num_selections is None:
num_selections = F.shape[0]
winners = []
locs = []
individual_locs = np.arange(F.shape[0])
fo... | As a Python code composer, you craft elegant and concise scripts. |
def epsilon_lexicase(self, F, sizes, num_selections=None, survival = False):
"""conducts epsilon lexicase selection for de-aggregated fitness vectors"""
# pdb.set_trace()
if num_selections is None:
num_selections = F.shape[0]
if self.c: # use c library
# defi... | Implement a function in Python 3 to
conduct epsilon lexicase selection for de - aggregated fitness vectors | As a Python code analyst, you investigate and solve complex coding mysteries |
median absolute deviation statistic | Here you have a function in Python 3, explain what it does
def mad(self,x, axis=None):
return np.median(np.abs(x - np.median(x, axis)), axis) | You are a Python code analyst, evaluating scripts for potential improvements. |
deterministic crowding implementation (for non-steady state).
offspring compete against the parent they are most similar to, here defined as
the parent they are most correlated with.
the offspring only replace their parent if they are more fit. | Here you have a function in Python 3, explain what it does
def deterministic_crowding(self,parents,offspring,X_parents,X_offspring):
# get children locations produced from crossover
cross_children = [i for i,o in enumerate(offspring) if len(o.parentid) > 1]
# order offspring so that they are lin... | You are a Python code analyst, evaluating scripts for potential improvements. |
def variation(self,parents):
"""performs variation operators on parents."""
# downselect to features that are important
if (self.valid(parents) and
self.ml_type != 'SVC' and self.ml_type != 'SVR'):
# this is needed because svm has a bug that throws valueerror on
... | How would you code a function in Python 3 to
perform variation operators on parents. | You are a Python code analyst, evaluating scripts for potential improvements. |
subtree - like swap crossover between programs p_i and p_j. | Explain what the following Python 3 code does
def cross(self,p_i,p_j, max_depth = 2):
# only choose crossover points for out_types available in both programs
# pdb.set_trace()
# determine possible outttypes
types_p_i = [t for t in [p.out_type for p in p_i]]
types_p_j = [t for t i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mutate(self,p_i,func_set,term_set): #, max_depth=2
"""point mutation, addition, removal"""
self.point_mutate(p_i,func_set,term_set) | Create a Python 3 function for
mutating a set of functions and terms | You are a Python code generator, capable of creating scripts from specifications. |
point mutation on individual p_i | Can you tell what is the following Python 3 function doing
def point_mutate(self,p_i,func_set,term_set):
# point mutation
x = self.random_state.randint(len(p_i))
arity = p_i[x].arity[p_i[x].in_type]
# find eligible replacements based on arity and type
reps = [n for n in func_set+... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def is_valid_program(self,p):
"""checks whether program p makes a syntactically valid tree.
checks that the accumulated program length is always greater than the
accumulated arities, indicating that the appropriate number of arguments is
alway present for functions. It then checks that ... | Write a Python 3 script for
checking whether a program p makes a syntactically valid tree. | As a Python code analyst, you investigate and solve complex coding mysteries |
run utility function for MDR nodes. | How would you explain what the following Python 3 function does
def run_MDR(n,stack_float,labels=None):
# need to check that tmp is categorical
x1 = stack_float.pop()
x2 = stack_float.pop()
# check data is categorical
if len(np.unique(x1))<=3 and len(np.unique(x2))<=3:
tmp = np.vstack((x1,x... | As a Python code analyst, you investigate and solve complex coding mysteries |
def stack_2_eqn(self,p):
"""returns equation string for program stack"""
stack_eqn = []
if p: # if stack is not empty
for n in p.stack:
self.eval_eqn(n,stack_eqn)
return stack_eqn[-1]
return [] | Can you implement a function in Python 3 that
returns equation string for program stack | You are a Python code architect, reviewing and designing scalable and efficient code |
returns equation strings from stacks | Given the following Python 3 function, write the documentation
def stacks_2_eqns(self,stacks):
if stacks:
return list(map(lambda p: self.stack_2_eqn(p), stacks))
else:
return [] | As a Python code analyst, you investigate and solve complex coding mysteries |
def make_program(self,stack,func_set,term_set,max_d,ntype):
"""makes a program stack"""
# print("stack:",stack,"max d:",max_d)
if max_d == 0:
ts = [t for t in term_set if t.out_type==ntype]
if not ts:
raise ValueError('no ts. ntype:'+ntype+'. term_set out... | Write a Python 3 script for
making a program stack | You are a Python code generator, capable of creating scripts from specifications. |
initializes population of features as GP stacks. | Can you generate a brief explanation for the following Python 3 code
def init_pop(self):
pop = Pop(self.population_size)
seed_with_raw_features = False
# make programs
if self.seed_with_ml:
# initial population is the components of the default ml model
if (self.ml... | As a Python code translator, you convert algorithms and pseudocode into Python. |
This function is called by the command line to run the FEW. | Can you tell what is the following Python 3 function doing
def main():
parser = argparse.ArgumentParser(description='A feature engineering wrapper'
' for machine learning algorithms.',
add_help=False)
parser.add_argument('INPUT_FILE', ty... | As a Python code analyst, you investigate and solve complex coding mysteries |
Fit the model to data | How would you explain what the following Python 3 function does
def fit(self, features, labels):
# setup data
# imputation
if self.clean:
features = self.impute_data(features)
# save the number of features
self.n_features = features.shape[1]
self.n_samples = ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def transform(self,x,inds=None,labels = None):
"""return a transformation of x using population outputs"""
if inds:
# return np.asarray(Parallel(n_jobs=10)(delayed(self.out)(I,x,labels,self.otype)
# for I in inds)).transpose()
return np.asar... | How would you code a function in Python 3 to
return a transformation of x using population outputs | As a python code expert, you are capable of creating scripts from specifications. |
def impute_data(self,x):
"""Imputes data set containing Nan values"""
imp = Imputer(missing_values='NaN', strategy='mean', axis=0)
return imp.fit_transform(x) | Can you create a Python 3 function that
imputes data set containing Nan values | As a Python code translator, you convert algorithms and pseudocode into Python. |
def clean(self,x):
"""remove nan and inf rows from x"""
return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] | Create a Python 3 function to
remove nan and inf rows from x | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_with_zeros(self,x):
""" set nan and inf rows from x to zero"""
x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] = 0
return x | Can you implement a function in Python 3 that
sets nan and inf rows from x to zero | You are a Python code generator, capable of creating scripts from specifications. |
def predict(self, testing_features):
"""predict on a holdout data set."""
# print("best_inds:",self._best_inds)
# print("best estimator size:",self._best_estimator.coef_.shape)
if self.clean:
testing_features = self.impute_data(testing_features)
if self._best_inds:
... | Write a Python 3 script to
predict on a holdout data set. | You are a Python code generator, capable of creating scripts from specifications. |
def score(self, testing_features, testing_labels):
"""estimates accuracy on testing set"""
# print("test features shape:",testing_features.shape)
# print("testing labels shape:",testing_labels.shape)
yhat = self.predict(testing_features)
return self.scoring_function(testing_label... | Can you implement a function in Python 3 that
estimates accuracy on testing set | As a Python code composer, you craft elegant and concise scripts. |
Exports engineered features of the current model to a file. | Make a summary of the following Python 3 code
def export(self, output_file_name):
if self._best_estimator is None:
raise ValueError('A model has not been optimized. Please call fit()'
' first.')
# Write print_model() to file
with open(output_file_name, '... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.