output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Generate a wave from a wavetable. | Explain what the following Python 3 code does
def table_wave(params, frequency=400, amplitude=1,
offset=0, table=None):
'''
Generate a wave from a wavetable
:param params: buffer parameters, controls length of signal created
:param frequency: wave frequency (array or value)
:param am... | You are a Python code architect, reviewing and designing scalable and efficient code |
Generates a sine wave from a buffer parameters controls length of signal created
| Can you generate a brief explanation for the following Python 3 code
def sine_wave(params, frequency=400, amplitude=1, offset=0):
'''
Generate a sine wave
Convenience function, table_wave generates a sine wave by default
:param params: buffer parameters, controls length of signal created
:param freq... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def midi2f(params, midi=69):
'''
Convert a midi value to a frequency.
Midi value 69 corresponds to A4 (440Hz). Changing the midi value by 1 corresponds to
one semitone
:param params: buffer parameters, controls length of signal created
:param midi: midi value
:return: array of resulting freq... | Can you write a function in Python 3 where it
converts a midi value to a frequency. | As a python code expert, you are capable of creating scripts from specifications. |
def get_lookup(self, lookup_name):
"""Fetch Lookup by name"""
from protean.core.repository import BaseLookup
lookup = self._get_lookup(lookup_name)
# If unable to find Lookup, or if Lookup is the wrong class, raise Error
if lookup is None or (lookup is not None and not issubclas... | How would you implement a function in Python 3 that
fetches Lookup by name | You are a Python code generator, capable of creating scripts from specifications. |
def merge_dicts(dicts):
"""
Merge dicts in reverse to preference the order of the original list. e.g.,
merge_dicts([a, b]) will preference the keys in 'a' over those in 'b'.
"""
merged = {}
for d in reversed(dicts):
merged.update(d)
return merged | Write a Python 3 function for
merging a list of dicts into a single dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def register_lookup(cls, lookup, lookup_name=None):
"""Register a Lookup to a class"""
if lookup_name is None:
lookup_name = lookup.lookup_name
if 'class_lookups' not in cls.__dict__:
cls.class_lookups = {}
cls.class_lookups[lookup_name] = lookup
cls._cle... | Implement a function in Python 3 to
register a Lookup to a class | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _unregister_lookup(cls, lookup, lookup_name=None):
"""
Remove given lookup from cls lookups. For use in tests only as it's
not thread-safe.
"""
if lookup_name is None:
lookup_name = lookup.lookup_name
del cls.class_lookups[lookup_name] | Write a Python 3 function for
removing given lookup from cls. class_lookups. | You are a Python code generator, capable of creating scripts from specifications. |
Deconstruct a Q Object | Explain what the following Python 3 code does
def deconstruct(self):
path = '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
args, kwargs = (), {}
if len(self.children) == 1 and not isinstance(self.children[0], Q):
child = self.children[0]
kwargs = {child[0... | As a python code expert, you are capable of creating scripts from specifications. |
Perform a necessary import or imports. | Can you generate a brief explanation for the following Python 3 code
def perform_import(val):
if val is None:
return None
elif isinstance(val, str):
return import_from_string(val)
elif isinstance(val, (list, tuple)):
return [import_from_string(item) for item in val]
return val | As a python code expert, you are capable of creating scripts from specifications. |
def import_from_string(val):
"""
Attempt to import a class from a string representation.
"""
try:
module_path, class_name = val.rsplit('.', 1)
module = import_module(module_path)
return getattr(module, class_name)
except (ImportError, AttributeError) as e:
msg = f"Cou... | Implement a Python 3 function for
attempting to import a class from a string representation. | As a Python code analyst, you investigate and solve complex coding mysteries |
def set_context(self, data):
"""Load Context with data"""
for key in data:
setattr(self.local_context, key, data[key]) | Write a Python 3 function that can
load Context with data | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _reset_values(self, instance):
"""Reset all associated values and clean up dictionary items"""
self.value = None
self.reference.value = None
instance.__dict__.pop(self.field_name, None)
instance.__dict__.pop(self.reference.field_name, None)
self.reference.delete_cache... | Can you write a function in Python 3 where it
resets all associated values and clean up dictionary items | As a Python code composer, you craft elegant and concise scripts. |
def linked_attribute(self):
"""Choose the Linkage attribute between `via` and designated `id_field` of the target class
This method is initially called from `__set_name__()` -> `get_attribute_name()`
at which point, the `to_cls` has not been initialized properly. We simply default
the l... | How would you implement a function in Python 3 that
chooses the Linkage attribute between via and designated id_field of the target class. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _linked_attribute(self, owner):
"""Choose the Linkage attribute between `via` and own entity's `id_field`
FIXME Explore converting this method into an attribute, and treating it
uniformly at `association` level.
"""
return self.via or (utils.inflection.underscore(owner... | Write a Python 3 function for
choosing the Linkage attribute between via and own entity s id_field | As a python code expert, you are capable of creating scripts from specifications. |
Fetch Multiple linked objects | Explain what the following Python 3 code does
def _fetch_objects(self, key, value):
return self.to_cls.query.filter(**{key: value}) | As a Python code composer, you craft elegant and concise scripts. |
async def _write_frame_awaiting_response(self, waiter_id, frame, request,
no_wait, check_open=True, drain=True):
'''Write a frame and set a waiter for
the response (unless no_wait is set)'''
if no_wait:
await self._write_frame(frame, request, check_open=check... | Write a Python 3 script for
writing a frame and set a waiter for the response ( unless no_wait is set | As a Python code analyst, you investigate and solve complex coding mysteries |
This function adds a sequence of sounds to a buffer containing the length of the source_specs. | How would you explain what the following Python 3 function does
def sequencer(params, source_specs):
'''
Add a sequence of sounds to a buffer
:param params: buffer parameters, controls length of signal created
:param source_spec: list of tuples containing (source, sample). The source is added into the o... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _load_base_class_fields(new_class, bases, attrs):
"""If this class is subclassing another Entity, add that Entity's
fields. Note that we loop over the bases in *reverse*.
This is necessary in order to maintain the correct order of fields.
"""
for base in reversed(bases):
... | Create a Python 3 function for
loading the fields from the base classes. | You are a Python code analyst, evaluating scripts for potential improvements. |
Load field items into Class.
COOKIES This method sets up the primary attribute of an association.
COOKIES | Given the following Python 3 function, write the documentation
def _load_fields(new_class, attrs):
for attr_name, attr_obj in attrs.items():
if isinstance(attr_obj, (Field, Reference)):
setattr(new_class, attr_name, attr_obj)
new_class.meta_.declared_fields[attr_name]... | You are a Python code analyst, evaluating scripts for potential improvements. |
Walk through relation fields and setup shadow attributes | Make a summary of the following Python 3 code
def _set_up_reference_fields(new_class):
if new_class.meta_.declared_fields:
for _, field in new_class.meta_.declared_fields.items():
if isinstance(field, Reference):
shadow_field_name, shadow_field = field.get_shadow_... | As a Python code composer, you craft elegant and concise scripts. |
def _create_id_field(new_class):
"""Create and return a default ID field that is Auto generated"""
id_field = Auto(identifier=True)
setattr(new_class, 'id', id_field)
id_field.__set_name__(new_class, 'id')
# Ensure ID field is updated properly in Meta attribute
new_clas... | How would you code a function in Python 3 to
create and return a default ID field that is Auto generated | As a Python code composer, you craft elegant and concise scripts. |
def _load_attributes(new_class):
"""Load list of attributes from declared fields"""
for field_name, field_obj in new_class.meta_.declared_fields.items():
new_class.meta_.attributes[field_obj.get_attribute_name()] = field_obj | Can you implement a function in Python 3 that
loads list of attributes from declared fields | You are a Python code architect, reviewing and designing scalable and efficient code |
Return the unique fields for this entity | Make a summary of the following Python 3 code
def unique_fields(self):
return [(field_name, field_obj)
for field_name, field_obj in self.declared_fields.items()
if field_obj.unique] | As a Python code composer, you craft elegant and concise scripts. |
def to_dict(self):
""" Return entity data as a dictionary """
return {field_name: getattr(self, field_name, None)
for field_name in self.meta_.declared_fields} | Write a Python 3 function that can
return entity data as a dictionary | You are a Python code architect, reviewing and designing scalable and efficient code |
Deepclone the entity but reset state | Can you tell what is the following Python 3 function doing
def clone(self):
clone_copy = copy.deepcopy(self)
clone_copy.state_ = EntityState()
return clone_copy | As a python code expert, you are capable of creating scripts from specifications. |
def get(cls, identifier: Any) -> 'Entity':
"""Get a specific Record from the Repository
:param identifier: id of the record to be fetched from the repository.
"""
logger.debug(f'Lookup `{cls.__name__}` object with identifier {identifier}')
# Get the ID field for the entity
... | Implement a function in Python 3 to
get a specific Record from the Repository. | You are a Python code generator, capable of creating scripts from specifications. |
Reloads the entity from the repository | Given the following Python 3 function, write the documentation
def reload(self) -> None:
if not self.state_.is_persisted or self.state_.is_changed:
raise InvalidStateError(f'`{self.__class__.__name__}` object is in invalid state')
# Retrieve the entity's ID by the configured Identifier fiel... | As a Python code analyst, you investigate and solve complex coding mysteries |
Find a specific entity record that matches one or more criteria. | How would you explain what the following Python 3 function does
def find_by(cls, **kwargs) -> 'Entity':
logger.debug(f'Lookup `{cls.__name__}` object with values '
f'{kwargs}')
# Find this item in the repository or raise Error
results = cls.query.filter(**kwargs).limit(1).a... | As a Python code analyst, you investigate and solve complex coding mysteries |
def exists(cls, excludes_, **filters):
""" Return `True` if objects matching the provided filters and excludes
exist if not return false.
Calls the `filter` method by default, but can be overridden for better and
quicker implementations that may be supported by a database.
... | Write a Python 3 script to
return True if objects matching the provided filters and excludes exist if not return false. | You are a Python code generator, capable of creating scripts from specifications. |
def create(cls, *args, **kwargs) -> 'Entity':
"""Create a new record in the repository.
Also performs unique validations before creating the entity
:param args: positional arguments for the entity
:param kwargs: keyword arguments for the entity
"""
logger.debug(
... | Write a Python 3 script for
creating a new record in the repository. | You are a Python code architect, reviewing and designing scalable and efficient code |
def save(self):
"""Save a new Entity into repository.
Performs unique validations before creating the entity.
"""
logger.debug(
f'Saving `{self.__class__.__name__}` object')
# Fetch Model class and connected repository from Repository Factory
model_cls = rep... | Write a Python 3 script to
save a new Entity into the repository. | You are a Python code architect, reviewing and designing scalable and efficient code |
Update an existing entity s data attributes and returns the new entity. | How would you explain what the following Python 3 function does
def update(self, *data, **kwargs) -> 'Entity':
logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}')
# Fetch Model class and connected repository from Repository Factory
model_cls = repo_factory.ge... | As a Python code composer, you craft elegant and concise scripts. |
def _validate_unique(self, create=True):
""" Validate the unique constraints for the entity """
# Build the filters from the unique constraints
filters, excludes = {}, {}
for field_name, field_obj in self.meta_.unique_fields:
lookup_value = getattr(self, field_name, None)
... | Implement a function in Python 3 to
validate the unique constraints for the entity. | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete(self):
"""Delete a Record from the Repository
will perform callbacks and run validations before deletion.
Throws ObjectNotFoundError if the object was not found in the repository.
"""
# Fetch Model class and connected repository from Repository Factory
model_... | How would you code a function in Python 3 to
delete a Record from the Repository and return the object. | As a Python code composer, you craft elegant and concise scripts. |
def add(self, item, count=1):
'''
When we receive stream of data, we add them in the chunk
which has limit on the no. of items that it will store.
>>> s = StreamCounter(5,5)
>>> data_stream = ['a','b','c','d']
>>> for item in data_stream:
... s.add(item)
... | Can you create a Python 3 function that
adds an item to the internal dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Drop the oldest chunk from the internal counts. | Can you generate a brief explanation for the following Python 3 code
def _drop_oldest_chunk(self):
'''
To handle the case when the items comming in the chunk
is more than the maximum capacity of the chunk. Our intent
behind is to remove the oldest chunk. So that the items come
fl... | As a Python code composer, you craft elegant and concise scripts. |
Get the count of an item from the cache. | How would you explain what the following Python 3 function does
def get(self, item, default=0, normalized=False):
'''
When we have the stream of data pushed in the chunk
we can retrive count of an item using this method.
>>> stream_counter_obj = StreamCounter(5,5)
>>> data_stream... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert the message to a mime compliant email string | Can you generate a brief explanation for the following Python 3 code
def message(self):
return '\n'.join(
[self.from_email, str(self.to), self.subject, self.body]) | You are a Python code architect, reviewing and designing scalable and efficient code |
def recipients(self):
"""
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
"""
return [email for email in (self.to + self.cc + self.bcc) if email] | Write a Python 3 script to
return a list of all recipients of the email. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_connection(self, fail_silently=False):
"""Retrieve connection to send email"""
from protean.services.email import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection | Write a Python 3 function that can
retrieve connection to send email | As a Python code translator, you convert algorithms and pseudocode into Python. |
Send the email message. | Can you generate the documentation for the following Python 3 function
def send(self, fail_silently=False):
if not self.recipients():
# Don't bother creating the network connection if
# there's nobody to send to.
return 0
return self.get_connection(fail_silently).send... | As a python code expert, you are capable of creating scripts from specifications. |
Adds a static route to the internal routes dict. | Given the following Python 3 function, write the documentation
def add_static_route(self, method: Union[str, Methods], route: str, handler: Callable,
skip_middleware=False):
"""
Adds a static route. A static route is a special route that
doesnt follow any of the normal r... | You are a Python code analyst, evaluating scripts for potential improvements. |
def prefix(self, prefix):
"""
Adds a prefix to routes contained within.
"""
original_prefix = self._prefix
self._prefix += prefix
yield self
self._prefix = original_prefix | How would you code a function in Python 3 to
add a prefix to routes contained within. | As a Python code composer, you craft elegant and concise scripts. |
def normalized_messages(self, no_field_name='_entity'):
"""Return all the error messages as a dictionary"""
if isinstance(self.messages, dict):
return self.messages
if not self.field_names:
return {no_field_name: self.messages}
return dict((name, self.messages) f... | Can you write a function in Python 3 where it
returns all the error messages as a dictionary | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a random string of a specified length. | Can you tell what is the following Python 3 function doing
def generate_random_string(length=6):
'''
Returns a random string of a specified length.
>>> len(generate_random_string(length=25))
25
Test randomness. Try N times and observe no duplicaton
>>> N = 100
>>> len(set(generate_random_s... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_timestamp(dt=None):
'''
Return current timestamp if @dt is None
else return timestamp of @dt.
>>> t = datetime.datetime(2015, 0o5, 21)
>>> get_timestamp(t)
1432166400
'''
if dt is None: dt = datetime.datetime.utcnow()
t = dt.utctimetuple()
return calendar.timegm(t) | Can you implement a function in Python 3 that
returns current timestamp of the last 1432166400 - > 1432166400 - > 1432166400 | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_datetime(epoch):
'''
get datetime from an epoch timestamp
>>> get_datetime(1432188772)
datetime.datetime(2015, 5, 21, 6, 12, 52)
'''
t = time.gmtime(epoch)
dt = datetime.datetime(*t[:6])
return dt | Can you implement a function in Python 3 that
gets datetime from an epoch timestamp | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert a timestamp to a date in the current date format. | Make a summary of the following Python 3 code
def convert_ts(tt):
'''
tt: time.struct_time(tm_year=2012, tm_mon=10, tm_mday=23, tm_hour=0,
tm_min=0, tm_sec=0, tm_wday=1, tm_yday=297, tm_isdst=-1)
>>> tt = time.strptime("23.10.2012", "%d.%m.%Y")
>>> convert_ts(tt)
1350950400
tt: time.struct... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts unicode encoding to str
| Can you tell what is the following Python 3 function doing
def xcode(text, encoding='utf8', mode='ignore'):
'''
Converts unicode encoding to str
>>> xcode(b'hello')
b'hello'
>>> xcode('hello')
b'hello'
'''
return text.encode(encoding, mode) if isinstance(text, str) else text | You are a Python code architect, reviewing and designing scalable and efficient code |
def serialize_dict_keys(d, prefix=""):
"""returns all the keys in nested a dictionary.
>>> sorted(serialize_dict_keys({"a": {"b": {"c": 1, "b": 2} } }))
['a', 'a.b', 'a.b.b', 'a.b.c']
"""
keys = []
for k, v in d.items():
fqk = '{}{}'.format(prefix, k)
keys.append(fqk)
if ... | Implement a Python 3 function for
returning all the keys in nested a dictionary. | As a Python code composer, you craft elegant and concise scripts. |
def flatten_dict(d,
parent_key='', sep='.',
ignore_under_prefixed=True,
mark_value=True):
'''
Flattens a nested dictionary
>>> from pprint import pprint
>>> d = {"a": {"b": {"c": 1, "b": 2, "__d": 'ignore', "_e": "mark"} } }
>>> fd = flatten_dict(d... | Implement a function in Python 3 to
flatten a nested dictionary d into a nested dictionary of items. | You are a Python code generator, capable of creating scripts from specifications. |
Get the ultimate value of an attribute in an object. | Can you generate the documentation for the following Python 3 function
def deepgetattr(obj, attr, default=AttributeError):
try:
return reduce(getattr, attr.split('.'), obj)
except AttributeError:
if default is not AttributeError:
return default
raise | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_file_limits(n):
'''
Set the limit on number of file descriptors
that this process can open.
'''
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (n, n))
return True
except ValueError:
return False | Can you implement a function in Python 3 that
sets the limit on number of file descriptors that this process can open. | As a python code expert, you are capable of creating scripts from specifications. |
Memoizes the result of a function f. | Explain what the following Python 3 code does
def memoize(f):
'''
Caches result of a function
From: https://goo.gl/aXt4Qy
>>> import time
>>> @memoize
... def test(msg):
... # Processing for result that takes time
... time.sleep(1)
... return msg
>>>
>>> for... | As a python code expert, you are capable of creating scripts from specifications. |
Given a python import path load the object | Make a summary of the following Python 3 code
def load_object(imp_path):
'''
Given a python import path, load the object
For dynamic imports in a program
>>> isdir = load_object('os.path.isdir')
>>> isdir('/tmp')
True
>>> num = load_object('numbers.Number')
>>> isinstance('x', num)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _run_validators(self, value):
"""Perform validation on ``value``. Raise a :exc:`ValidationError` if
validation does not succeed.
"""
if value in self.empty_values:
return
errors = []
for validator in self.validators:
try:
valid... | Write a Python 3 script for
performing validation on value. Raise a : exc : ValidationException if validation does not succeed. | As a Python code analyst, you investigate and solve complex coding mysteries |
Load the value for the field and run validators and return the value. | Can you generate the documentation for the following Python 3 function
def _load(self, value: Any):
if value in self.empty_values:
# If a default has been set for the field return it
if self.default is not None:
default = self.default
value = default() if... | You are a Python code generator, capable of creating scripts from specifications. |
Extract lookup method based on key name format | How would you explain what the following Python 3 function does
def _extract_lookup(self, key):
parts = key.split('__')
# 'exact' is the default lookup if there was no explicit comparison op in `key`
# Assume there is only one `__` in the key.
# FIXME Change for child attribute query... | As a Python code analyst, you investigate and solve complex coding mysteries |
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform from json to Request
Exception:
ValueError: If path does not exist.
"""
try:
return Request.from_jsonf_to_list(payload.file, encoding=self.config.encoding)
except TypeError as e... | Implement a Python 3 function for
transforming from json to Request | As a Python code composer, you craft elegant and concise scripts. |
def get_backend_expiry(self, expiry=DEFAULT_EXPIRY):
"""
Return the expiry value usable by this backend based upon the provided
timeout.
"""
if expiry == DEFAULT_EXPIRY:
expiry = self.default_expiry
elif expiry == 0:
# avoid time.time() related pre... | Create a Python 3 function to
return the expiry value usable by this backend based upon the provided timeout. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_many(self, keys):
"""
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Return a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the respo... | Write a Python 3 function that can
fetch a bunch of keys from the cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
def incr(self, key, delta=1):
"""
Add delta to value in the cache. If the key does not exist, raise a
ValueError exception.
"""
value = self.get(key)
if value is None:
raise ValueError("Key '%s' not found" % key)
new_value = value + delta
self.... | Can you implement a function in Python 3 that
increments the value of a key in the cache. | As a Python code composer, you craft elegant and concise scripts. |
Set a bunch of values in the cache at once from a dict of key - value pairs. | Make a summary of the following Python 3 code
def set_many(self, data, expiry=DEFAULT_EXPIRY):
for key, value in data.items():
self.set(key, value, expiry=expiry)
return [] | As a Python code composer, you craft elegant and concise scripts. |
Call when initialize Jumeaux!!
| Given the following Python 3 function, write the documentation
def init_logger(v_num: int):
logging.addLevelName(LogLevel.INFO_LV1.value, 'INFO_LV1') # type: ignore # Prevent for enum problem
logging.addLevelName(LogLevel.INFO_LV2.value, 'INFO_LV2') # type: ignore # Prevent for enum problem
logging.addLev... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _initialize_providers(self):
"""Read config file and initialize providers"""
configured_providers = active_config.DATABASES
provider_objects = {}
if not isinstance(configured_providers, dict) or configured_providers == {}:
raise ConfigurationError(
"'DATA... | How would you implement a function in Python 3 that
reads config file and initialize providers | As a Python code composer, you craft elegant and concise scripts. |
def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return self._providers[provider_name]
except KeyError:
... | Write a Python 3 function for
fetching a specific provider with the specified name in Configuration file | You are a Python code generator, capable of creating scripts from specifications. |
Fetch connection from Provider | Make a summary of the following Python 3 code
def get_connection(self, provider_name='default'):
try:
return self._providers[provider_name].get_connection()
except KeyError:
raise AssertionError(f'No Provider registered with name {provider_name}') | As a python code expert, you are capable of creating scripts from specifications. |
def update_defaults(self, ext_config):
""" Update the default settings for an extension from an object"""
for setting in dir(ext_config):
if setting.isupper() and not hasattr(self, setting):
setattr(self, setting, getattr(ext_config, setting)) | Create a Python 3 function to
update the default settings for an extension from an object | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is a generator function that returns a sequence of nodes that are not yet in the tree. | Can you generate a brief explanation for the following Python 3 code
def keeprunning(wait_secs=0, exit_on_success=False,
on_success=None, on_error=None, on_done=None):
'''
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when er... | As a python code expert, you are capable of creating scripts from specifications. |
def register(self, entity_cls, provider_name=None):
""" Register the given model with the factory
:param entity_cls: Entity class to be registered
:param provider: Optional provider to associate with Entity class
"""
self._validate_entity_cls(entity_cls)
# Register the e... | Can you write a function in Python 3 where it
registers the given entity with the factory. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _find_entity_in_records_by_class_name(self, entity_name):
"""Fetch by Entity Name in values"""
records = {
key: value for (key, value)
in self._registry.items()
if value.name == entity_name
}
# If more than one record was found, we are dealing with... | Create a Python 3 function for
fetching by Entity Name in values | As a Python code translator, you convert algorithms and pseudocode into Python. |
Fetch Entity record with Entity class details | Here you have a function in Python 3, explain what it does
def _get_entity_by_class(self, entity_cls):
entity_qualname = fully_qualified_name(entity_cls)
if entity_qualname in self._registry:
return self._registry[entity_qualname]
else:
return self._find_entity_in_records... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_entity_by_name(self, entity_name):
"""Fetch Entity record with an Entity name"""
if entity_name in self._registry:
return self._registry[entity_name]
else:
return self._find_entity_in_records_by_class_name(entity_name) | Can you write a function in Python 3 where it
fetches an Entity record with an Entity name | You are a Python code architect, reviewing and designing scalable and efficient code |
Validate that the given Entity class is a valid class. | How would you explain what the following Python 3 function does
def _validate_entity_cls(self, entity_cls):
# Import here to avoid cyclic dependency
from protean.core.entity import Entity
if not issubclass(entity_cls, Entity):
raise AssertionError(
f'Entity {entity_c... | As a Python code analyst, you investigate and solve complex coding mysteries |
Retrieve Model class connected to Entity | How would you explain what the following Python 3 function does
def get_model(self, entity_cls):
entity_record = self._get_entity_by_class(entity_cls)
model_cls = None
if entity_record.model_cls:
model_cls = entity_record.model_cls
else:
# We should ask the Provi... | As a Python code composer, you craft elegant and concise scripts. |
Retrieve a Repository for the Model with a live connection | Explain what the following Python 3 code does
def get_repository(self, entity_cls):
entity_record = self._get_entity_by_class(entity_cls)
provider = self.get_provider(entity_record.provider_name)
return provider.get_repository(entity_record.entity_cls) | You are a Python code generator, capable of creating scripts from specifications. |
Set heater values from heater data. | Explain what the following Python 3 code does
async def set_heater_values(heater_data, heater):
heater.current_temp = heater_data.get('currentTemp')
heater.device_status = heater_data.get('deviceStatus')
heater.available = heater.device_status == 0
heater.name = heater_data.get('deviceName')
heater.... | As a python code expert, you are capable of creating scripts from specifications. |
Close the Mill connection. | Can you generate a brief explanation for the following Python 3 code
def sync_connect(self):
loop = asyncio.get_event_loop()
task = loop.create_task(self.connect())
loop.run_until_complete(task) | As a Python code analyst, you investigate and solve complex coding mysteries |
def sync_close_connection(self):
"""Close the Mill connection."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.close_connection())
loop.run_until_complete(task) | How would you code a function in Python 3 to
close the Mill connection. | As a python code expert, you are capable of creating scripts from specifications. |
Send a command to Mill. | Make a summary of the following Python 3 code
async def request(self, command, payload, retry=3):
# pylint: disable=too-many-return-statements
if self._token is None:
_LOGGER.error("No token")
return None
_LOGGER.debug(command, payload)
nonce = ''.join(random.c... | You are a Python code generator, capable of creating scripts from specifications. |
Send a request to the server and return the response. | Here you have a function in Python 3, explain what it does
def sync_request(self, command, payload, retry=2):
loop = asyncio.get_event_loop()
task = loop.create_task(self.request(command, payload, retry))
return loop.run_until_complete(task) | You are a Python code architect, reviewing and designing scalable and efficient code |
async def update_rooms(self):
"""Request data."""
homes = await self.get_home_list()
for home in homes:
payload = {"homeId": home.get("homeId"), "timeZoneNum": "+01:00"}
data = await self.request("selectRoombyHome", payload)
rooms = data.get('roomInfo', [])
... | Write a Python 3 script for
requesting data for all rooms and heaters. | As a Python code composer, you craft elegant and concise scripts. |
def sync_update_rooms(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_rooms())
return loop.run_until_complete(task) | Write a Python 3 function that can
request data from the server. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set room temps by name. | Given the following Python 3 function, write the documentation
async def set_room_temperatures_by_name(self, room_name, sleep_temp=None,
comfort_temp=None, away_temp=None):
"""Set room temps by name."""
if sleep_temp is None and comfort_temp is None and away_t... | You are a Python code architect, reviewing and designing scalable and efficient code |
def sync_update_heaters(self):
"""Request data."""
loop = asyncio.get_event_loop()
task = loop.create_task(self.update_heaters())
loop.run_until_complete(task) | Can you create a Python 3 function that
updates the list of available HEALPix entries. | As a Python code composer, you craft elegant and concise scripts. |
async def throttle_update_heaters(self):
"""Throttle update device."""
if (self._throttle_time is not None
and dt.datetime.now() - self._throttle_time < MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_time = dt.datetime.now()
await self.update_heaters() | How would you code a function in Python 3 to
throttle update the list of available HEALPix entries. | As a Python code analyst, you investigate and solve complex coding mysteries |
async def throttle_update_all_heaters(self):
"""Throttle update all devices and rooms."""
if (self._throttle_all_time is not None
and dt.datetime.now() - self._throttle_all_time
< MIN_TIME_BETWEEN_UPDATES):
return
self._throttle_all_time = dt.datetime.... | Write a Python 3 script to
throttle update all devices and rooms. | You are a Python code architect, reviewing and designing scalable and efficient code |
def exec(self, payload: Log2ReqsAddOnPayload) -> TList[Request]:
"""Transform csv as below.
"title1","/path1","a=1&b=2","header1=1&header2=2"
"title2","/path2","c=1"
"title3","/path3",,"header1=1&header2=2"
"title4","/path4"
Exception:
ValueEr... | Implement a Python 3 function for
transforming csv as below. | You are a Python code architect, reviewing and designing scalable and efficient code |
def echo(params, source, delay, strength):
'''
Create an echo
:param params:
:param source:
:param delay:
:param strength:
:return:
'''
source = create_buffer(params, source)
delay = create_buffer(params, delay)
strength = create_buffer(params, strength)
output = source[:... | Write a Python 3 function for
echoing a single nucite object. | You are a Python code generator, capable of creating scripts from specifications. |
def _clone(self):
"""
Return a copy of the current QuerySet.
"""
clone = self.__class__(self._entity_cls, criteria=self._criteria,
offset=self._offset, limit=self._limit,
order_by=self._order_by)
return clone | Write a Python 3 function that can
return a copy of the current QuerySet. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add a Q - object to the current filter. | Here you have a function in Python 3, explain what it does
def _add_q(self, q_object):
self._criteria = self._criteria._combine(q_object, q_object.connector) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def limit(self, limit):
"""Limit number of records"""
clone = self._clone()
if isinstance(limit, int):
clone._limit = limit
return clone | Can you create a Python 3 function that
limits number of records | As a Python code translator, you convert algorithms and pseudocode into Python. |
def offset(self, offset):
"""Fetch results after `offset` value"""
clone = self._clone()
if isinstance(offset, int):
clone._offset = offset
return clone | Write a Python 3 script for
fetching results after offset value | As a Python code translator, you convert algorithms and pseudocode into Python. |
def order_by(self, order_by: Union[set, str]):
"""Update order_by setting for filter set"""
clone = self._clone()
if isinstance(order_by, str):
order_by = {order_by}
clone._order_by = clone._order_by.union(order_by)
return clone | Write a Python 3 script for
updating order_by setting for filter set | You are a Python code architect, reviewing and designing scalable and efficient code |
Fetch all the items in the QuerySet | Can you generate a brief explanation for the following Python 3 code
def all(self):
logger.debug(f'Query `{self.__class__.__name__}` objects with filters {self}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Repository Factory... | You are a Python code architect, reviewing and designing scalable and efficient code |
Updates all objects with details given if they match a set of conditions supplied. | Make a summary of the following Python 3 code
def update(self, *data, **kwargs):
updated_item_count = 0
try:
items = self.all()
for item in items:
item.update(*data, **kwargs)
updated_item_count += 1
except Exception:
# FIXME L... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Runs raw query on the database and returns the objects of the specified type. | Explain what the following Python 3 code does
def raw(self, query: Any, data: Any = None):
logger.debug(f'Query `{self.__class__.__name__}` objects with raw query {query}')
# Destroy any cached results
self._result_cache = None
# Fetch Model class and connected repository from Reposito... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Deletes matching objects from the Repository and returns the number of objects deleted. | Can you tell what is the following Python 3 function doing
def delete(self):
# Fetch Model class and connected repository from Repository Factory
deleted_item_count = 0
try:
items = self.all()
for item in items:
item.delete()
deleted_item_... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Updates all objects with details given if they match a set of conditions supplied. | How would you explain what the following Python 3 function does
def update_all(self, *args, **kwargs):
updated_item_count = 0
repository = repo_factory.get_repository(self._entity_cls)
try:
updated_item_count = repository.update_all(self._criteria, *args, **kwargs)
except E... | You are a Python code analyst, evaluating scripts for potential improvements. |
Deletes objects that match a set of conditions supplied. | Can you generate a brief explanation for the following Python 3 code
def delete_all(self, *args, **kwargs):
deleted_item_count = 0
repository = repo_factory.get_repository(self._entity_cls)
try:
deleted_item_count = repository.delete_all(self._criteria)
except Exception:
... | 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.