output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def setattr_path(obj, path, value):
"""
Set an attribute path, as defined by a string separated by '__'.
setattr_path(foo, 'a__b__c', value) is equivalent to "foo.a.b.c = value".
"""
path = path.split('__')
o = obj
for name in path[:-1]:
o = getattr(o, name)
setattr(o, path[-1], ... | Write a Python 3 script for
setting an attribute path as defined by a string separated by __. | As a Python code analyst, you investigate and solve complex coding mysteries |
def generate_rst_docs(directory, classes, missing_objects=None):
"""
Generate documentation for tri.declarative APIs
:param directory: directory to write the .rst files into
:param classes: list of classes to generate documentation for
:param missing_objects: tuple of objects to count as missing ma... | Implement a function in Python 3 to
generate the. rst files for the current node. | As a python code expert, you are capable of creating scripts from specifications. |
Make a copy of a subset of a registry. | Can you tell what is the following Python 3 function doing
def reg_copy(reg, keys=None):
if keys is None:
keys = reg.keys()
reg_cls = type(reg)
new_reg = reg_cls()
mk = {} # empty dictionary for meta keys
# loop over registry meta names
for m in reg_cls.meta_names:
mstar = getat... | As a Python code composer, you craft elegant and concise scripts. |
def get_covariance(datargs, outargs, vargs, datvar, outvar):
"""
Get covariance matrix.
:param datargs: data arguments
:param outargs: output arguments
:param vargs: variable arguments
:param datvar: variance of data arguments
:param outvar: variance of output ar... | Write a Python 3 function for
getting the covariance matrix for the given data and output variables. | You are a Python code generator, capable of creating scripts from specifications. |
def calculate(self, calc, formula_reg, data_reg, out_reg,
timestep=None, idx=None):
"""
Calculate looping over specified repeat arguments.
:param calc: Calculation to loop over.
:param formula_reg: Formula registry
:param data_reg: Data registry
:param ... | How would you code a function in Python 3 to
calculate the repeat arguments for a specific time period. | As a python code expert, you are capable of creating scripts from specifications. |
def listen_many(*rooms):
"""Listen for changes in all registered listeners in all specified rooms"""
rooms = set(r.conn for r in rooms)
for room in rooms:
room.validate_listeners()
with ARBITRATOR.condition:
while any(r.connected for r in rooms):
ARBITRATOR.condition.wait()
... | How would you implement a function in Python 3 that
listens for changes in all registered listeners in all specified rooms | You are a Python code analyst, evaluating scripts for potential improvements. |
Connect to the websocket through asyncio http interface | Here you have a function in Python 3, explain what it does
def connect(self, username, checksum, password=None, key=None):
ws_url = (
f"{BASE_WS_URL}?room={self.room.room_id}&cs={checksum}&nick={username}"
f"&rn={random_id(6)}&t={int(time.time() * 1000)}&transport=websocket&EIO=3"
... | You are a Python code generator, capable of creating scripts from specifications. |
Send an ack message to the broker. | Can you generate a brief explanation for the following Python 3 code
def send_ack(self):
if self.last_ack == self.proto.max_id:
return
LOGGER.debug("ack (%d)", self.proto.max_id)
self.last_ack = self.proto.max_id
self.send_message(f"4{to_json([self.proto.max_id])}") | As a Python code composer, you craft elegant and concise scripts. |
Makes a regular API call | Can you generate a brief explanation for the following Python 3 code
def make_call(self, fun, *args):
obj = {"fn": fun, "args": list(args)}
obj = [self.proto.max_id, [[0, ["call", obj]], self.proto.send_count]]
self.send_message(f"4{to_json(obj)}")
self.proto.send_count += 1 | As a Python code composer, you craft elegant and concise scripts. |
Makes an API call with a callback to wait for | Given the following Python 3 function, write the documentation
def make_call_with_cb(self, fun, *args):
cid, event = self.handler.register_callback()
argscp = list(args)
argscp.append(cid)
self.make_call(fun, *argscp)
return event | As a python code expert, you are capable of creating scripts from specifications. |
Make a REST API call | Make a summary of the following Python 3 code
def make_api_call(self, call, params):
if not isinstance(params, dict):
raise ValueError("params argument must be a dictionary")
kw = dict(
params=params,
headers={"Origin": BASE_URL, "Referer": f"{BASE_URL}/r/{self.room.... | You are a Python code generator, capable of creating scripts from specifications. |
Reraise an exception passed by the event thread | Given the following Python 3 function, write the documentation
def reraise(self, ex):
self.exception = ex
self.process_queues(forced=True) | As a Python code analyst, you investigate and solve complex coding mysteries |
Process incoming messages according to engine - io rules. | Given the following Python 3 function, write the documentation
def on_message(self, new_data):
# https://github.com/socketio/engine.io-protocol
LOGGER.debug("new frame [%r]", new_data)
try:
what = int(new_data[0])
data = new_data[1:]
data = data and from_json... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_listener(self, event_type, callback):
"""Add a listener for specific event type.
You'll need to actually listen for changes using the listen method"""
if not self.connected:
# wait for errors set by reraise method
time.sleep(1)
if self.exception:
... | Write a Python 3 function that can
add a listener for specific event type. | As a python code expert, you are capable of creating scripts from specifications. |
def process_queues(self, forced=False):
"""Process queues if any have data queued"""
with self.lock:
if (not forced and not self.must_process) or not self.queues_enabled:
return
self.must_process = False
ARBITRATOR.awaken() | Can you create a Python 3 function that
processes queues if any have data queued | As a Python code composer, you craft elegant and concise scripts. |
def validate_listeners(self):
"""Validates that some listeners are actually registered"""
if self.exception:
# pylint: disable=raising-bad-type
raise self.exception
listeners = self.__listeners_for_thread
if not sum(len(l) for l in listeners):
raise ... | Write a Python 3 script for
validating that some listeners are actually registered | As a Python code translator, you convert algorithms and pseudocode into Python. |
def listen(self):
"""Listen for changes in all registered listeners."""
self.validate_listeners()
with ARBITRATOR.condition:
while self.connected:
ARBITRATOR.condition.wait()
if not self.run_queues():
break | How would you implement a function in Python 3 that
listens for changes in all registered listeners. | As a Python code analyst, you investigate and solve complex coding mysteries |
Run all queues that have data queued | Can you tell what is the following Python 3 function doing
def run_queues(self):
if self.exception:
# pylint: disable=raising-bad-type
raise self.exception
listeners = self.__listeners_for_thread
return sum(l.process() for l in listeners) > 0 | As a Python code analyst, you investigate and solve complex coding mysteries |
def __add_prop(self, key, admin=False):
"""Add gettable and settable room config property during runtime"""
def getter(self):
return self.config[key]
def setter(self, val):
if admin and not self.admin:
raise RuntimeError(
f"You can't ... | How would you code a function in Python 3 to
add gettable and settable room config property during runtime | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets a value for a room config | Here you have a function in Python 3, explain what it does
def __set_config_value(self, key, value):
self.check_owner()
params = {"room": self.room_id, "config": to_json({key: value})}
resp = self.conn.make_api_call("setRoomConfig", params)
if "error" in resp:
raise RuntimeE... | You are a Python code analyst, evaluating scripts for potential improvements. |
Listen for changes in all registered listeners. | Can you generate the documentation for the following Python 3 function
def listen(self, once=False):
if once:
# we listen for time event and return false so our
# run_queues function will be also falsy and break the loop
self.add_listener("time", lambda _: False)
ret... | You are a Python code architect, reviewing and designing scalable and efficient code |
This method is used to expire the files in the cache. | Can you generate a brief explanation for the following Python 3 code
def __expire_files(self):
self.__files = OrderedDict(
item for item in self.__files.items() if not item[1].expired
) | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_user_stats(self, name):
"""Return data about the given user. Returns None if user
does not exist."""
req = self.conn.get(BASE_URL + "/user/" + name)
if req.status_code != 200 or not name:
return None
return self.conn.make_api_call("getUserInfo", {"name": nam... | Implement a function in Python 3 to
return data about the given user. Returns None if the user does not exist. Returns None if the user does not exist. | You are a Python code analyst, evaluating scripts for potential improvements. |
def post_chat(self, msg, is_me=False, is_a=False):
"""Posts a msg to this room's chat. Set me=True if you want to /me"""
if len(msg) > self.config.max_message:
raise ValueError(
f"Chat message must be at most {self.config.max_message} characters."
)
while... | Implement a Python 3 function for
posting a msg to this room s chat. Set me = True. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def upload_file(
self,
filename,
upload_as=None,
blocksize=None,
callback=None,
information_callback=None,
allow_timeout=False,
):
"""Uploads a file with given filename to this room.
You may specify upload_as to change the name it is uploaded a... | Create a Python 3 function for
uploading a file to this room. | You are a Python code architect, reviewing and designing scalable and efficient code |
Close connection to this room | Can you tell what is the following Python 3 function doing
def close(self):
if hasattr(self, "conn"):
self.conn.close()
del self.conn
if hasattr(self, "user"):
del self.user | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sets the user_info dict entry through a tuple. | Given the following Python 3 function, write the documentation
def user_info(self, kv):
key, value = kv
self.__user_info[key] = value | As a Python code analyst, you investigate and solve complex coding mysteries |
def fileinfo(self, fid):
"""Ask lain about what he knows about given file. If the given file
exists in the file dict, it will get updated."""
if not isinstance(fid, str):
raise TypeError("Your file ID must be a string")
try:
info = self.conn.make_call_with_cb("ge... | Can you write a function in Python 3 where it
asks lain about what he knows about a given file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate a new upload key | Here you have a function in Python 3, explain what it does
def _generate_upload_key(self, allow_timeout=False):
# Wait for server to set username if not set already.
while not self.user.nick:
with ARBITRATOR.condition:
ARBITRATOR.condition.wait()
while True:
... | You are a Python code generator, capable of creating scripts from specifications. |
def delete_files(self, ids):
"""Remove one or more files"""
self.check_owner()
if not isinstance(ids, list):
raise TypeError("You must specify list of files to delete!")
self.conn.make_call("deleteFiles", ids) | How would you code a function in Python 3 to
remove one or more files | As a python code expert, you are capable of creating scripts from specifications. |
Transfer owner to new owner | How would you explain what the following Python 3 function does
def transfer_owner(self, new_owner):
if not self.owner and not self.admin:
raise RuntimeError("You need more street creed to do this")
new_owner = new_owner.strip().lower()
if not new_owner:
raise ValueErro... | You are a Python code analyst, evaluating scripts for potential improvements. |
def add_janitor(self, janitor):
"""Add janitor to the room"""
if not self.owner and not self.admin:
raise RuntimeError("Not enough street creed to do this")
janitor = janitor.strip().lower()
if not janitor:
raise ValueError("Empty strings cannot be janitors")
... | Implement a function in Python 3 to
add a janitor to the room | You are a Python code analyst, evaluating scripts for potential improvements. |
Remove a janitor from the room | Can you generate the documentation for the following Python 3 function
def remove_janitor(self, janitor):
if not self.owner and not self.admin:
raise RuntimeError("Not enough street creed to do this")
janitor = janitor.strip().lower()
if not janitor:
raise ValueError("E... | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads the environment from the resultdir if not None and returns it. | Can you generate a brief explanation for the following Python 3 code
def _make_env(resultdir=None):
env = {
"config": {}, # The config
"resultdir": "", # Path to the result directory
"config_file": "", # The initial config file
"nodes": {}, ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Saves one environment.
Args:
env (dict): the env dict to save. | Explain what the following Python 3 code does
def _save_env(env):
env_path = os.path.join(env["resultdir"], "env")
if os.path.isdir(env["resultdir"]):
with open(env_path, "w") as f:
yaml.dump(env, f) | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator for an Enos Task.
This decorator checks if an environment file exists. | Explain what the following Python 3 code does
def _check_env(fn):
def decorator(*args, **kwargs):
# If no directory is provided, set the default one
resultdir = kwargs.get("--env", SYMLINK_NAME)
# Check if the env file exists
env_path = os.path.join(resultdir, "env")
if not o... | As a Python code composer, you craft elegant and concise scripts. |
Set or get the directory to store experiment results. | How would you explain what the following Python 3 function does
def _set_resultdir(name=None):
# Compute file path of results directory
resultdir_name = name or "enos_" + datetime.today().isoformat()
resultdir_path = os.path.abspath(resultdir_name)
# Raise error if a related file exists
if os.path.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def register(self, newdata, *args, **kwargs):
"""
Register data in registry. Meta for each data is specified by positional
or keyword arguments after the new data and consists of the following:
* ``uncertainty`` - Map of uncertainties in percent corresponding to new
keys. The ... | Can you create a Python 3 function that
registers new data in the data store. | As a Python code composer, you craft elegant and concise scripts. |
def _is_cached(self, ext='.json'):
"""
Determine if ``filename`` is cached using extension ``ex`` a string.
:param ext: extension used to cache ``filename``, default is '.json'
:type ext: str
:return: True if ``filename`` is cached using extensions ``ex``
:rtype: bool
... | Can you implement a function in Python 3 that
determines if the filename is cached using the given extension. | You are a Python code generator, capable of creating scripts from specifications. |
Save data as JSON file. | How would you explain what the following Python 3 function does
def saveas_json(self, save_name):
# make pycharm by defining inferred objects
meta = getattr(self, DataSourceBase._meta_attr)
param_file = getattr(self, DataSourceBase._param_file)
# JSONEncoder removes units and converts ar... | You are a Python code generator, capable of creating scripts from specifications. |
def edit(self, edits, data_reg):
"""
Edit data in :class:`Data_Source`. Sets :attr:`issaved` to ``False``.
"""
data_reg.update(edits)
self._is_saved = False | How would you implement a function in Python 3 that
edits data in data_reg. | As a Python code composer, you craft elegant and concise scripts. |
Return list of slitlets from string specification. | Can you tell what is the following Python 3 function doing
def list_slitlets_from_string(s, islitlet_min, islitlet_max):
# protection
if not isinstance(s, str):
print('type(s): ', type(s))
print('ERROR: function expected a string parameter')
# initialize empty output
set_slitlets = set... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function takes a string path to allow query -ing from another Orm class and returns a Query object that represents the object in the class A. | Can you tell what is the following Python 3 function doing
def ref(self, orm_classpath, cls_pk=None):
# split orm from module path
orm_module, orm_class = get_objects(orm_classpath)
# if orm_classpath.startswith("."):
# # we handle relative classpaths by using the orm_class and its p... | You are a Python code analyst, evaluating scripts for potential improvements. |
set a unique field to be selected | Can you tell what is the following Python 3 function doing
def unique_field(self, field_name):
self.fields_set.options["unique"] = True
return self.select_field(field_name) | As a Python code analyst, you investigate and solve complex coding mysteries |
set multiple fields to be selected | Can you generate the documentation for the following Python 3 function
def select_fields(self, *fields):
if fields:
if not isinstance(fields[0], basestring):
fields = list(fields[0]) + list(fields)[1:]
for field_name in fields:
field_name = self._normalize_field... | As a Python code composer, you craft elegant and concise scripts. |
def set_field(self, field_name, field_val=None):
"""
set a field into .fields attribute
n insert/update queries, these are the fields that will be inserted/updated into the db
"""
field_name = self._normalize_field_name(field_name)
self.fields_set.append(field_name, [fie... | Write a Python 3 function for
setting a field into the internal list of fields that will be inserted into the db | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a field to the where clause of the resource. | Explain what the following Python 3 code does
def in_field(self, field_name, *field_vals, **field_kwargs):
field_name = self._normalize_field_name(field_name)
fv = make_list(field_vals[0]) if field_vals else None
if field_kwargs:
for k in field_kwargs:
if not field_kw... | As a python code expert, you are capable of creating scripts from specifications. |
def nlike_field(self, field_name, *field_val, **field_kwargs):
"""Perform a field_name NOT LIKE field_val query
:param field_name: string, the field we are filtering on
:param field_val: string, the like query: %val, %val%, val%
:returns: self, for fluid interface
"""
if... | Write a Python 3 script to
perform a field_name NOT LIKE field_val query on the resource object | As a Python code analyst, you investigate and solve complex coding mysteries |
sort this query by field_name in directrion
| Can you tell what is the following Python 3 function doing
def sort_field(self, field_name, direction, field_vals=None):
field_name = self._normalize_field_name(field_name)
if direction > 0:
direction = 1
elif direction < 0:
direction = -1
else:
raise ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(self, limit=None, page=None):
"""
get results from the db
return -- Iterator()
"""
has_more = False
self.bounds.paginate = True
limit_paginate, offset = self.bounds.get(limit, page)
self.default_val = []
results = self._query('get')
... | Create a Python 3 function to
get results from the dbget | As a Python code translator, you convert algorithms and pseudocode into Python. |
get one row from the db | Can you generate the documentation for the following Python 3 function
def get_one(self):
self.default_val = None
o = self.default_val
d = self._query('get_one')
if d:
o = self.orm_class(d, hydrate=True)
return o | As a Python code composer, you craft elegant and concise scripts. |
def values(self, limit=None, page=None):
"""
convenience method to get just the values from the query (same as get().values())
if you want to get all values, you can use: self.all().values()
"""
return self.get(limit=limit, page=page).values() | Can you write a function in Python 3 where it
gets all the values from the query | As a Python code composer, you craft elegant and concise scripts. |
return a list of the primary keys of the current record set | How would you explain what the following Python 3 function does
def pks(self, limit=None, page=None):
self.fields_set.reset()
return self.select_pk().values(limit, page) | As a Python code composer, you craft elegant and concise scripts. |
convenience method for running is_pk. get_one | Given the following Python 3 function, write the documentation
def get_pk(self, field_val):
field_name = self.schema.pk.name
return self.is_field(field_name, field_val).get_one() | You are a Python code generator, capable of creating scripts from specifications. |
def count(self):
"""return the count of the criteria"""
# count queries shouldn't care about sorting
fields_sort = self.fields_sort
self.fields_sort = self.fields_sort_class()
self.default_val = 0
ret = self._query('count')
# restore previous values now that co... | Create a Python 3 function to
return the count of the criteria | As a python code expert, you are capable of creating scripts from specifications. |
persist the. fields using. fields_where | How would you explain what the following Python 3 function does
def update(self):
self.default_val = 0
#fields = self.fields
#fields = self.orm_class.depart(self.fields, is_update=True)
#self.set_fields(fields)
return self.interface.update(
self.schema,
se... | As a python code expert, you are capable of creating scripts from specifications. |
def raw(self, query_str, *query_args, **query_options):
"""
use the interface.query() method to pass in your own raw query without
any processing
NOTE -- This will allow you to make any raw query and will usually return
raw results, it won't wrap those results in a prom.Orm iter... | Implement a function in Python 3 to
query the internal cache for the current entry set | As a Python code analyst, you investigate and solve complex coding mysteries |
map and reduce the tables in the database | Can you generate the documentation for the following Python 3 function
def reduce(self, target_map, target_reduce, threads=0):
if not threads:
threads = multiprocessing.cpu_count()
# we subtract one for the main process
map_threads = threads - 1 if threads > 1 else 1
q = se... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def cache_key(self, method_name):
"""decides if this query is cacheable, returns a key if it is, otherwise empty"""
key = ""
method = getattr(self, "cache_key_{}".format(method_name), None)
if method:
key = method()
return key | Create a Python 3 function to
decide if this query is cacheable returns a key if it is otherwise empty | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a sanitized version of the object. | Can you generate a brief explanation for the following Python 3 code
def normalize(self):
logger.debug("normalize: {}".format(type(self).__name__))
normalize_headers = self._normalize_headers()
return TableData(
self.__normalize_table_name(),
normalize_headers,
... | As a Python code composer, you craft elegant and concise scripts. |
Apply units to data originally loaded by NumPyLoadTxtReader or NumPyGenFromTxtReader. | Here you have a function in Python 3, explain what it does
def _apply_units_to_numpy_data_readers(parameters, data):
# apply header units
header_param = parameters.get('header') # default is None
# check for headers
if header_param:
fields = header_param['fields'] # header fields
# dic... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _read_header(f, header_param):
"""
Read and parse data from 1st line of a file.
:param f: :func:`file` or :class:`~StringIO.StringIO` object from which to
read 1st line.
:type f: file
:param header_param: Parameters used to parse the data from the header.
Contains "delimiter" an... | How would you code a function in Python 3 to
read and parse data from 1st line of a file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _apply_units(data_data, data_units, fname):
"""
Apply units to data.
:param data_data: NumPy structured array with data from fname.
:type data_data: :class:`numpy.ndarray`
:param data_units: Units of fields in data_data.
:type data_units: dict
:param fname: Name of file from which data_... | Write a Python 3 function that can
apply units to data. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert unicode strings in a list of lists to ascii in a list of tuples. | How would you explain what the following Python 3 function does
def _utf8_list_to_ascii_tuple(utf8_list):
for n, utf8 in enumerate(utf8_list):
utf8_list[n][0] = str(utf8[0])
utf8_list[n][1] = str(utf8[1])
utf8_list[n] = tuple(utf8) | As a Python code composer, you craft elegant and concise scripts. |
Load JSON data.
:param filename: name of JSON file with data
:type filename: str
:return: data
:rtype: dict | How would you explain what the following Python 3 function does
def load_data(self, filename, *args, **kwargs):
# append .json extension if needed
if not filename.endswith('.json'):
filename += '.json' # append "json" to filename
# open file and load JSON data
with open(file... | You are a Python code analyst, evaluating scripts for potential improvements. |
def apply_units_to_cache(self, data):
"""
Apply units to data read using :class:`JSONReader`.
:param data: cached data
:return: data with units applied
:rtype: :class:`~pint.unit.Quantity`
"""
for k, val in self.parameters.iteritems():
if 'units' in v... | Can you implement a function in Python 3 that
applies units to data read using JSONReader. | You are a Python code architect, reviewing and designing scalable and efficient code |
def load_data(self, filename, *args, **kwargs):
"""
Load parameters from Excel spreadsheet.
:param filename: Name of Excel workbook with data.
:type filename: str
:returns: Data read from Excel workbook.
:rtype: dict
"""
# workbook read from file
... | How would you code a function in Python 3 to
load data from Excel file. | As a Python code composer, you craft elegant and concise scripts. |
Apply units to cached data read using JSONReader. | Here you have a function in Python 3, explain what it does
def apply_units_to_cache(self, data):
# iterate through sheets in parameters
# iterate through the parameters on each sheet
for param, pval in self.parameters.iteritems():
# try to apply units
try:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
load data from text file using numpy. loadtxt | How would you explain what the following Python 3 function does
def load_data(self, filename, *args, **kwargs):
# header keys
header_param = self.parameters.get('header') # default is None
# data keys
data_param = self.parameters['data'] # raises KeyError if no 'data'
dtype = d... | As a Python code analyst, you investigate and solve complex coding mysteries |
def load_data(self, filename, *args, **kwargs):
"""
load data from text file.
:param filename: name of file to read
:type filename: str
:returns: data read from file using :func:`numpy.genfromtxt`
:rtype: dict
:raises: :exc:`~simkit.core.exceptions.UnnamedDataErr... | Can you write a function in Python 3 where it
loads data from text file using numpy. genfromtxt | As a python code expert, you are capable of creating scripts from specifications. |
def load_data(self, filename, *args, **kwargs):
"""
Load parameterized data from different sheets.
"""
# load parameterized data
data = super(ParameterizedXLS, self).load_data(filename)
# add parameter to data
parameter_name = self.parameterization['parameter']['n... | Write a Python 3 function for
loading parameterized data from different sheets. | As a Python code composer, you craft elegant and concise scripts. |
Apply units to data reader. | Can you generate a brief explanation for the following Python 3 code
def apply_units_to_cache(self, data):
# parameter
parameter_name = self.parameters['parameter']['name']
parameter_units = str(self.parameters['parameter']['units'])
data[parameter_name] *= UREG(parameter_units)
... | You are a Python code generator, capable of creating scripts from specifications. |
Load text data from different sheets. | Given the following Python 3 function, write the documentation
def load_data(self, filename, *args, **kwargs):
# load text data
data = super(MixedTextXLS, self).load_data(filename)
# iterate through sheets in parameters
for sheet_params in self.parameters.itervalues():
# iter... | As a Python code analyst, you investigate and solve complex coding mysteries |
Mark the occurrence of a given number of events. | Given the following Python 3 function, write the documentation
def mark(self, n=1):
self.tick_if_necessary()
self.count += n
self.m1_rate.update(n)
self.m5_rate.update(n)
self.m15_rate.update(n) | You are a Python code generator, capable of creating scripts from specifications. |
def _load(self, layer=None):
"""
Load or update all or part of :attr:`model`.
:param layer: Optionally load only specified layer.
:type layer: str
"""
# open model file for reading and convert JSON object to dictionary
# read and load JSON parameter map file as "... | Can you write a function in Python 3 where it
loads or update all or part of model. | As a python code expert, you are capable of creating scripts from specifications. |
def _update(self, layer=None):
"""
Update layers in model.
"""
meta = getattr(self, ModelBase._meta_attr)
if not layer:
layers = self.layers
else:
# convert non-sequence to tuple
layers = _listify(layer)
for layer in layers:
... | Can you write a function in Python 3 where it
updates the internal state of the object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _initialize(self):
"""
Initialize model and layers.
"""
meta = getattr(self, ModelBase._meta_attr)
# read modelfile, convert JSON and load/update model
if self.param_file is not None:
self._load()
LOGGER.debug('model:\n%r', self.model)
# in... | Write a Python 3 script to
initialize model and layers. | You are a Python code architect, reviewing and designing scalable and efficient code |
Load or update a model or layers in a model. | Given the following Python 3 function, write the documentation
def load(self, modelfile, layer=None):
# read modelfile, convert JSON and load/update model
self.param_file = modelfile
self._load(layer)
self._update(layer) | As a Python code composer, you craft elegant and concise scripts. |
Edit model.
:param layer: Layer of model to edit
:type layer: str
:param item: Items to edit.
:type item: dict
:param delete: Flag to return
:class:`~simkit.core.layers.Layer` to delete item.
:type delete: bool | Can you generate a brief explanation for the following Python 3 code
def edit(self, layer, item, delete=False):
# get layer attribute with model data
if hasattr(self, layer):
layer_obj = getattr(self, layer)
else:
raise AttributeError('missing layer: %s', layer)
i... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add(self, layer, items):
"""
Add items in model.
"""
for k in items.iterkeys():
if k in self.model[layer]:
raise Exception('item %s is already in layer %s' % (k, layer))
self.model[layer].update(items)
# this should also update Layer.layer,... | Write a Python 3 script for
adding items in model. | As a Python code analyst, you investigate and solve complex coding mysteries |
Delete items in model. | Here you have a function in Python 3, explain what it does
def delete(self, layer, items):
# Use edit to get the layer obj containing item
items = _listify(items) # make items a list if it's not
layer_obj = self.edit(layer, dict.fromkeys(items), delete=True)
for k in items:
... | As a python code expert, you are capable of creating scripts from specifications. |
Save a model file. | Explain what the following Python 3 code does
def save(self, modelfile, layer=None):
if layer:
obj = {layer: self.model[layer]}
else:
obj = self.model
with open(modelfile, 'w') as fp:
json.dump(obj, fp, indent=2, sort_keys=True) | You are a Python code analyst, evaluating scripts for potential improvements. |
Execute a command in the command layer. | How would you explain what the following Python 3 function does
def command(self, cmd, progress_hook=None, *args, **kwargs):
cmds = cmd.split(None, 1) # split commands and simulations
sim_names = cmds[1:] # simulations
if not sim_names:
sim_names = self.cmd_layer.reg.iterkeys()
... | You are a Python code generator, capable of creating scripts from specifications. |
Attempts to log in as the current user with given password | Make a summary of the following Python 3 code
def login(self, password):
if self.logged_in:
raise RuntimeError("User already logged in!")
params = {"name": self.nick, "password": password}
resp = self.conn.make_api_call("login", params)
if "error" in resp:
raise... | As a Python code composer, you craft elegant and concise scripts. |
Attempts to carry over the login state from another room | Can you tell what is the following Python 3 function doing
def login_transplant(self, other):
if not other.logged_in:
raise ValueError("Other room is not logged in")
cookie = other.session
if not cookie:
raise ValueError("Other room has no cookie")
self.conn.cook... | You are a Python code generator, capable of creating scripts from specifications. |
Logs your user out | Make a summary of the following Python 3 code
def logout(self):
if not self.logged_in:
raise RuntimeError("User is not logged in")
if self.conn.connected:
params = {"room": self.conn.room.room_id}
resp = self.conn.make_api_call("logout", params)
if not re... | You are a Python code analyst, evaluating scripts for potential improvements. |
Change the name of your user | Can you generate a brief explanation for the following Python 3 code
def change_nick(self, new_nick):
if self.logged_in:
raise RuntimeError("User must be logged out")
self.__verify_username(new_nick)
self.conn.make_call("command", self.nick, "nick", new_nick)
self.nick = ne... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Registers the current user with the given password. | Can you tell what is the following Python 3 function doing
def register(self, password):
if len(password) < 8:
raise ValueError("Password must be at least 8 characters.")
params = {"name": self.nick, "password": password}
resp = self.conn.make_api_call("register", params)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Raises an exception if the given username is not valid. | Can you generate the documentation for the following Python 3 function
def __verify_username(self, username):
if len(username) > self.__max_length or len(username) < 3:
raise ValueError(
f"Username must be between 3 and {self.__max_length} characters."
)
if any(c... | As a Python code composer, you craft elegant and concise scripts. |
def update(self, value, timestamp=None):
"""Add a value to the reservoir.
:param value: the value to be added
:param timestamp: the epoch timestamp of the value in seconds, defaults
to the current timestamp if not specified.
"""
if timestamp is None:
tim... | Can you write a function in Python 3 where it
adds a value to the reservoir. | You are a Python code architect, reviewing and designing scalable and efficient code |
A common feature of the above techniques that allows us to track the decayed weights efficiently. This is done by scaling the counts and other quantities based on the current time of the current entry. | Can you generate the documentation for the following Python 3 function
def rescale(self, now):
old_start_time = self.start_time
self.start_time = self.current_time_in_fractional_seconds()
self.next_scale_time = now + RESCALE_THRESHOLD_S
new_values = treap.treap()
for key in self... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_objects(classpath, calling_classpath=""):
"""
given a classpath like foo.bar.Baz return module foo.bar and class Baz
objects
.. seealso::
https://docs.python.org/2.5/whatsnew/pep-328.html
https://www.python.org/dev/peps/pep-0328/
:param classpath: string, the full python cl... | Can you write a function in Python 3 where it
returns module and class objects given a classpath like foo. bar. Baz or foo. bar. Che. Che is the class name of the class name of Che. Che is the class name of the Che class in the Che class Baz. Che. Che is the class name of Che. Che is the class name of Che. Che is the c... | As a Python code composer, you craft elegant and concise scripts. |
This function takes a dict or kwargs and returns a dict that can be used to create a new base object for the base object | How would you explain what the following Python 3 function does
def make_dict(fields, fields_kwargs):
ret = {}
if fields:
ret.update(fields)
if fields_kwargs:
ret.update(fields_kwargs)
return ret | As a Python code translator, you convert algorithms and pseudocode into Python. |
writes the line and count newlines after the line | Explain what the following Python 3 code does
def write_line(self, line, count=1):
self.write(line)
self.write_newlines(count) | You are a Python code analyst, evaluating scripts for potential improvements. |
add a value to the queue with priority using the key to know uniqueness | Can you generate a brief explanation for the following Python 3 code
def add(self, key, val, priority=None):
if key in self.item_finder:
self.remove(key)
else:
# keep the queue contained
if self.full():
raise OverflowError("Queue is full")
i... | As a python code expert, you are capable of creating scripts from specifications. |
def remove(self, key):
"""remove the value found at key from the queue"""
item = self.item_finder.pop(key)
item[-1] = None
self.removed_count += 1 | Write a Python 3 script to
remove the value found at key from the queue | As a Python code composer, you craft elegant and concise scripts. |
def popitem(self):
"""remove the next prioritized [key, val, priority] and return it"""
pq = self.pq
while pq:
priority, key, val = heapq.heappop(pq)
if val is None:
self.removed_count -= 1
else:
del self.item_finder[key]
... | Write a Python 3 script for
removing the next prioritized key val priority and return it | As a python code expert, you are capable of creating scripts from specifications. |
def full(self):
"""Return True if the queue is full"""
if not self.size: return False
return len(self.pq) == (self.size + self.removed_count) | Implement a Python 3 function for
returning True if the queue is full False otherwise | As a Python code composer, you craft elegant and concise scripts. |
def extract_slitlet2d(image_2k2k, sltlim):
"""Extract slitlet 2d image from image with original EMIR dimensions.
Parameters
----------
image_2k2k : 2d numpy array, float
Original image (dimensions NAXIS1 * NAXIS2)
sltlim : instance of SlitLimits class
Object containing relevant info... | Can you implement a function in Python 3 that
extracts slitlet 2d image from image with original EMIR dimensions. | As a Python code analyst, you investigate and solve complex coding mysteries |
def compute_slitlet_boundaries(
filename, grism, spfilter, list_slitlets,
size_x_medfilt, size_y_savgol,
times_sigma_threshold,
bounddict, debugplot=0):
"""Compute slitlet boundaries using continuum lamp images.
Parameters
----------
filename : string
Input conti... | Create a Python 3 function for
computing the slitlet boundaries using a 2D image. | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.