output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
jsonschema RefResolver object for the base schema. | Given the following Python 3 function, write the documentation
def resolver(self):
if self._resolver is not None:
return self._resolver
if self._schema_path is not None:
# the documentation for ref resolving
# https://github.com/Julian/jsonschema/issues/98
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def validate(self, value, validator):
"""Validates and returns the value.
If the value does not validate against the schema, SchemaValidationError
will be raised.
:param value: A value to validate (usually a dict).
:param validator: An instance of a jsonschema validator class, ... | Write a Python 3 function for
validating and returns the value. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def validate_json(self, json_value, validator):
"""Validates and returns the parsed JSON string.
If the value is not valid JSON, ParseError will be raised. If it is
valid JSON, but does not validate against the schema,
SchemaValidationError will be raised.
:param str json_value... | Create a Python 3 function for
validating and returns the parsed JSON string. | You are a Python code generator, capable of creating scripts from specifications. |
Create an instance of the class from a YAML or JSON schema file. | Can you generate a brief explanation for the following Python 3 code
def from_file(cls, schema_filepath, *args, **kwargs):
schema_filepath = os.path.abspath(schema_filepath)
try:
with open(schema_filepath, 'r') as schema_file:
schema = yaml.load(schema_file.read())
ex... | You are a Python code analyst, evaluating scripts for potential improvements. |
def execute_flow(self, custom_command="", is_config=False):
""" Execute flow which run custom command on device
:param custom_command: the command to execute on device
:param is_config: if True then run command in configuration mode
:return: command execution output
"""
... | Implement a function in Python 3 to
execute a command on the device and return the output | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_custom_config_command(self, custom_command):
""" Execute custom command in configuration mode on device
:param custom_command: command
:return: result of command execution
"""
return self.run_command_flow.execute_flow(custom_command=custom_command, is_config=True) | How would you implement a function in Python 3 that
executes custom command in configuration mode on device | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_rethinkdb_url(s):
'''
Parses a url like this rethinkdb://server1:port,server2:port/database/table
Returns:
tuple `(['server1:port', 'server2:port'], database, table)`
`table` and `database` may be None
Raises:
ValueError if url cannot be parsed as a rethinkdb url
... | Implement a function in Python 3 to
parse a rethinkdb url and returns a ParsedRethinkDbUrl object | As a Python code analyst, you investigate and solve complex coding mysteries |
Encode Async options for JSON encoding. | Make a summary of the following Python 3 code
def encode_async_options(async):
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
# JSON don't like datetimes.
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def decode_async_options(options):
"""Decode Async options from JSON decoding."""
async_options = copy.deepcopy(options)
# JSON don't like datetimes.
eta = async_options.get('task_args', {}).get('eta')
if eta:
from datetime import datetime
async_options['task_args']['eta'] = dateti... | Write a Python 3 function that can
decode Async options from JSON decoding. | You are a Python code generator, capable of creating scripts from specifications. |
def defaults(**options):
"""Set default Async options on the function decorated.
Note: you must pass the decorated function by reference, not as a
"path.string.to.function" for this to have any effect.
"""
_check_options(options)
def real_decorator(function):
function._async_options = ... | Can you implement a function in Python 3 that
sets default Async options on the function decorated. Note: you must pass the decorated function by reference, not as a "path.string.to.function" for this to have any effect. | As a python code expert, you are capable of creating scripts from specifications. |
def _persist_result(self):
"""Store this Async's result in persistent storage."""
self._prepare_persistence_engine()
return self._persistence_engine.store_async_result(
self.id, self.result) | Create a Python 3 function for
storing this Async s result in persistent storage. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _initialize_recursion_depth(self):
"""Ensure recursion info is initialized, if not, initialize it."""
from furious.context import get_current_async
recursion_options = self._options.get('_recursion', {})
current_depth = recursion_options.get('current', 0)
max_depth = recurs... | Can you create a Python 3 function that
ensures recursion info is initialized if not initialize it. | As a Python code analyst, you investigate and solve complex coding mysteries |
Check recursion depth, raise AsyncRecursionError if too deep. | How would you explain what the following Python 3 function does
def check_recursion_depth(self):
from furious.async import MAX_DEPTH
recursion_options = self._options.get('_recursion', {})
max_depth = recursion_options.get('max', MAX_DEPTH)
# Check if recursion check has been disabled,... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _update_job(self, target, args, kwargs):
"""Specify the function this async job is to execute when run."""
target_path, options = get_function_path_and_options(target)
assert isinstance(args, (tuple, list)) or args is None
assert isinstance(kwargs, dict) or kwargs is None
i... | Implement a Python 3 function for
specifying the function this async job is to execute when run. | As a Python code composer, you craft elegant and concise scripts. |
Set the ExecutionContext this async is executing under. | Here you have a function in Python 3, explain what it does
def set_execution_context(self, execution_context):
if self._execution_context:
raise errors.AlreadyInContextError
self._execution_context = execution_context | As a Python code composer, you craft elegant and concise scripts. |
Safely update this async job s configuration options. | Can you generate the documentation for the following Python 3 function
def update_options(self, **options):
_check_options(options)
if 'persistence_engine' in options:
options['persistence_engine'] = reference_to_path(
options['persistence_engine'])
if 'id' in opti... | You are a Python code analyst, evaluating scripts for potential improvements. |
def to_task(self):
"""Return a task object representing this async job."""
from google.appengine.api.taskqueue import Task
from google.appengine.api.taskqueue import TaskRetryOptions
self._increment_recursion_level()
self.check_recursion_depth()
url = "%s/%s" % (ASYNC_E... | Implement a function in Python 3 to
return a Task object representing this async job. | As a Python code analyst, you investigate and solve complex coding mysteries |
Start the task in the queue. | How would you explain what the following Python 3 function does
def start(self, transactional=False, async=False, rpc=None):
from google.appengine.api import taskqueue
task = self.to_task()
queue = taskqueue.Queue(name=self.get_queue())
retry_transient = self._options.get('retry_transie... | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_dict(cls, async):
"""Return an async job from a dict output by Async.to_dict."""
async_options = decode_async_options(async)
target, args, kwargs = async_options.pop('job')
return cls(target, args, kwargs, **async_options) | How would you implement a function in Python 3 that
returns an async job from a dict output by Async. to_dict. | As a Python code composer, you craft elegant and concise scripts. |
Load the specified persistence engine or the default if none is set. | Make a summary of the following Python 3 code
def _prepare_persistence_engine(self):
if self._persistence_engine:
return
persistence_engine = self._options.get('persistence_engine')
if persistence_engine:
self._persistence_engine = path_to_reference(persistence_engine)
... | You are a Python code generator, capable of creating scripts from specifications. |
Get the parent async id. | How would you explain what the following Python 3 function does
def _get_parent_id(self):
parent_id = self._options.get('parent_id')
if parent_id:
return parent_id
from furious.context import get_current_async
try:
async = get_current_async()
except erro... | As a Python code composer, you craft elegant and concise scripts. |
def full_id(self):
"""Return the full_id for this Async. Consists of the parent id, id and
context id.
"""
full_id = ""
if self.parent_id:
full_id = ":".join([self.parent_id, self.id])
else:
full_id = self.id
if self.context_id:
... | Can you implement a function in Python 3 that
returns the full_id for this Async. Consists of the parent id and context id. | As a python code expert, you are capable of creating scripts from specifications. |
Increment the current_depth based on either the enclosing
Async.
Async. Checkpoints the current_depth and stores the current_depth and max_depth options. | Explain what the following Python 3 code does
def _increment_recursion_level(self):
# Update the recursion info. This is done so that if an async created
# outside an executing context, or one previously created is later
# loaded from storage, that the "current" setting is correctly set.
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Return this Async s Context Id if it exists. | Explain what the following Python 3 code does
def context_id(self):
if not self._context_id:
self._context_id = self._get_context_id()
self.update_options(context_id=self._context_id)
return self._context_id | You are a Python code analyst, evaluating scripts for potential improvements. |
Converts the payload to a serializable dict. | Can you generate the documentation for the following Python 3 function
def _payload_to_dict(self):
if self.status != self.ERROR or not self.payload:
return self.payload
import traceback
return {
"error": self.payload.error,
"args": self.payload.args,
... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a HTTPMethod instance to create a PUT route. | Can you generate the documentation for the following Python 3 function
def put(func: Callable, allowed_exceptions: List = None,
title: str = None, req_obj_type: Callable = None) -> HTTPMethod:
"""Returns a HTTPMethod instance to create a PUT route.
:see: :class:`~doctor.routing.HTTPMethod`
"""
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a handler method that will be used in a handler class. | Given the following Python 3 function, write the documentation
def create_http_method(logic: Callable, http_method: str,
handle_http: Callable, before: Callable = None,
after: Callable = None) -> Callable:
"""Create a handler method to be used in a handler class.
:... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_handler_name(route: Route, logic: Callable) -> str:
"""Gets the handler name.
:param route: A Route instance.
:param logic: The logic function.
:returns: A handler class name.
"""
if route.handler_name is not None:
return route.handler_name
if any(m for m in route.methods if... | Write a Python 3 function for
getting the handler name. | As a python code expert, you are capable of creating scripts from specifications. |
def create_routes(routes: Tuple[HTTPMethod], handle_http: Callable,
default_base_handler_class: Any) -> List[Tuple[str, Any]]:
"""Creates handler routes from the provided routes.
:param routes: A tuple containing the route and another tuple with
all http methods allowed for the route.... | Write a Python 3 function that can
create the handler routes from the provided routes. | As a python code expert, you are capable of creating scripts from specifications. |
def parse_args(options={}, *args, **kwds):
"""
Parser of arguments.
dict options {
int min_items: Min of required items to fold one tuple. (default: 1)
int max_items: Count of items in one tuple. Last `max_items-min_items`
items is by default set to None. (default: 1)
bo... | Create a Python 3 function to
parse command line arguments. | You are a Python code generator, capable of creating scripts from specifications. |
def simple_state_machine():
"""Pick a number, if it is more than some cuttoff continue the chain."""
from random import random
from furious.async import Async
number = random()
logging.info('Generating a number... %s', number)
if number > 0.25:
logging.info('Continuing to do stuff.')
... | Create a Python 3 function for
picking a number and continue the chain. | You are a Python code architect, reviewing and designing scalable and efficient code |
def render_attrs(attrs):
"""
Render HTML attributes, or return '' if no attributes needs to be rendered.
"""
if attrs is not None:
def parts():
for key, value in sorted(attrs.items()):
if value is None:
continue
if value is True:
... | Can you write a function in Python 3 where it
renders HTML attributes, or return '' if no attributes needs to be rendered. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Persist async marker and async the completion check | Can you generate a brief explanation for the following Python 3 code
def context_completion_checker(async):
store_async_marker(async.id, async.result.status if async.result else -1)
logging.debug("Async check completion for: %s", async.context_id)
current_queue = _get_current_queue()
from furious.asyn... | You are a Python code generator, capable of creating scripts from specifications. |
Check if all Async jobs within a Context have been run. | Can you generate the documentation for the following Python 3 function
def _completion_checker(async_id, context_id):
if not context_id:
logging.debug("Context for async %s does not exist", async_id)
return
context = FuriousContext.from_id(context_id)
marker = FuriousCompletionMarker.get_b... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns a flag for markers being found for the task_ids. | Can you tell what is the following Python 3 function doing
def _check_markers(task_ids, offset=10):
shuffle(task_ids)
has_errors = False
for index in xrange(0, len(task_ids), offset):
keys = [ndb.Key(FuriousAsyncMarker, id)
for id in task_ids[index:index + offset]]
markers... | You are a Python code architect, reviewing and designing scalable and efficient code |
Transactionally complete the context. | Make a summary of the following Python 3 code
def _mark_context_complete(marker, context, has_errors):
current = None
if marker:
current = marker.key.get()
if not current:
return False
if current and current.complete:
return False
current.complete = True
current.has_... | As a Python code composer, you craft elegant and concise scripts. |
Insert the event s asyncs and cleanup tasks. | Can you generate a brief explanation for the following Python 3 code
def _insert_post_complete_tasks(context):
logging.debug("Context %s is complete.", context.id)
# Async event handlers
context.exec_event_handler('complete', transactional=True)
# Insert cleanup tasks
try:
# TODO: If trac... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _cleanup_markers(context_id, task_ids):
"""Delete the FuriousAsyncMarker entities corresponding to ids."""
logging.debug("Cleanup %d markers for Context %s",
len(task_ids), context_id)
# TODO: Handle exceptions and retries here.
delete_entities = [ndb.Key(FuriousAsyncMarker, id) ... | Can you create a Python 3 function that
deletes the FuriousAsyncMarker entities corresponding to ids. | As a python code expert, you are capable of creating scripts from specifications. |
Persist a furious. context. Context object into the datastore by loading it
into a FuriousContext ndb. Model.
| Here you have a function in Python 3, explain what it does
def store_context(context):
logging.debug("Attempting to store Context %s.", context.id)
entity = FuriousContext.from_context(context)
# TODO: Handle exceptions and retries here.
marker = FuriousCompletionMarker(id=context.id)
key, _ = nd... | You are a Python code architect, reviewing and designing scalable and efficient code |
def store_async_result(async_id, async_result):
"""Persist the Async's result to the datastore."""
logging.debug("Storing result for %s", async_id)
key = FuriousAsyncMarker(
id=async_id, result=json.dumps(async_result.to_dict()),
status=async_result.status).put()
logging.debug("Settin... | Write a Python 3 function that can
persist the Async s result to the datastore. | You are a Python code analyst, evaluating scripts for potential improvements. |
Persist a marker indicating the Async ran to the datastore. | Can you generate the documentation for the following Python 3 function
def store_async_marker(async_id, status):
logging.debug("Attempting to mark Async %s complete.", async_id)
# QUESTION: Do we trust if the marker had a flag result to just trust it?
marker = FuriousAsyncMarker.get_by_id(async_id)
i... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Yield out the results found on the markers for the context task ids. | Can you tell what is the following Python 3 function doing
def iter_context_results(context, batch_size=10, task_cache=None):
for futures in iget_batches(context.task_ids, batch_size=batch_size):
for key, future in futures:
task = future.get_result()
if task_cache is not None:
... | As a Python code composer, you craft elegant and concise scripts. |
Yields out a map of the keys and futures in batches of the batch size. | Given the following Python 3 function, write the documentation
def iget_batches(task_ids, batch_size=10):
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id)
for keys in i_batch(imap(make_key, task_ids), batch_size):
yield izip(keys, ndb.get_multi_async(keys)) | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_context(cls, context):
"""Create a `cls` entity from a context."""
return cls(id=context.id, context=context.to_dict()) | Write a Python 3 script to
create a cls entity from a context. | As a Python code analyst, you investigate and solve complex coding mysteries |
Load a cls entity and instantiate the Context it stores. | Can you generate a brief explanation for the following Python 3 code
def from_id(cls, id):
from furious.context import Context
# TODO: Handle exceptions and retries here.
entity = cls.get_by_id(id)
if not entity:
raise FuriousContextNotFoundError(
"Context en... | You are a Python code analyst, evaluating scripts for potential improvements. |
def items(self):
"""Yield the async reuslts for the context."""
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | How would you code a function in Python 3 to
yield the async reuslts for the context. | As a Python code analyst, you investigate and solve complex coding mysteries |
def values(self):
"""Yield the async reuslt values for the context."""
for _, task in self._tasks:
if not (task and task.result):
yield None
else:
yield json.loads(task.result)["payload"] | Implement a function in Python 3 to
yield the async reuslt values for the context. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def aiidalab_display(obj, downloadable=True, **kwargs):
"""Display AiiDA data types in Jupyter notebooks.
:param downloadable: If True, add link/button to download content of displayed AiiDA object.
Defers to IPython.display.display for any objects it does not recognize.
"""
from aiidalab_widgets_... | How would you code a function in Python 3 to
display AiiDA object in Jupyter notebooks. | As a Python code composer, you craft elegant and concise scripts. |
def __password(self):
"""Returning the password and immediately destroying it"""
passwd = copy(self._inp_password.value)
self._inp_password.value = ''
return passwd | Write a Python 3 function that can
return the password and immediately destroying it | You are a Python code generator, capable of creating scripts from specifications. |
Returns the proxy password and immediately destroying it | Can you tell what is the following Python 3 function doing
def __proxy_password(self):
passwd = copy(self._inp_proxy_password.value)
self._inp_proxy_password.value = ''
return passwd | You are a Python code architect, reviewing and designing scalable and efficient code |
Loking for username in user s input and config file | Given the following Python 3 function, write the documentation
def username(self):
if len(self._inp_username.value.strip()) == 0: # if username provided by user
if not self.hostname is None:
config = parse_sshconfig(self.hostname)
if 'user' in config: # if username is... | You are a Python code analyst, evaluating scripts for potential improvements. |
def load(cls, rr, pk):
'''
Retrieves a document from the database, by primary key.
'''
if pk is None:
return None
d = rr.table(cls.table).get(pk).run()
if d is None:
return None
doc = cls(rr, d)
return doc | Can you implement a function in Python 3 that
loads a single object from the database by primary key. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates the table if it doesn t exist. | Can you generate the documentation for the following Python 3 function
def table_ensure(cls, rr):
'''
Creates the table if it doesn't exist.
'''
dbs = rr.db_list().run()
if not rr.dbname in dbs:
logging.info('creating rethinkdb database %s', repr(rr.dbname))
... | You are a Python code generator, capable of creating scripts from specifications. |
def pk_field(self):
'''
Name of the primary key field as retrieved from rethinkdb table
metadata, 'id' by default. Should not be overridden. Override
`table_create` if you want to use a nonstandard field as the primary
key.
'''
if not self._pk:
try:
... | How would you code a function in Python 3 to
return the name of the primary key field as retrieved from rethinkdb table SetException metadata by default. Should not be overridden. Override table_create by default. | As a Python code composer, you craft elegant and concise scripts. |
Saves the current object to rethinkdb. | How would you explain what the following Python 3 function does
def save(self):
'''
Persist changes to rethinkdb. Updates only the fields that have
changed. Performs insert rather than update if the document has no
primary key or if the primary key is absent from the database.
I... | You are a Python code generator, capable of creating scripts from specifications. |
def refresh(self):
'''
Refresh the document from the database.
'''
d = self.rr.table(self.table).get(self.pk_value).run()
if d is None:
raise KeyError
for k in d:
dict.__setitem__(
self, k, watch(d[k], callback=self._updated, fi... | Implement a function in Python 3 to
refresh the document from the database. | As a Python code analyst, you investigate and solve complex coding mysteries |
Parses xml file with xml_path and returns XmlNode | Make a summary of the following Python 3 code
def parse(self, xml_file, view_name=None) -> XmlNode:
self._setup_parser()
try:
self._view_name = view_name
self._parser.ParseFile(xml_file)
except ExpatError as error:
# pylint: disable=E1101
raise Xml... | As a python code expert, you are capable of creating scripts from specifications. |
def find_unrelated(x, plim=0.1, axis=0):
"""Find indicies of insignificant un-/correlated variables
Example:
--------
i, j = find_unrelated(x, plim, rlim)
"""
# transpose if axis<>0
if axis is not 0:
x = x.T
# read dimensions and allocate variables
_, c = x.shape
p... | How would you implement a function in Python 3 that
finds un - related variables in a tree. | You are a Python code generator, capable of creating scripts from specifications. |
Handle apply connectivity changes request json | Make a summary of the following Python 3 code
def apply_connectivity_changes(self, request):
if request is None or request == "":
raise Exception(self.__class__.__name__, "request is None or empty")
holder = JsonRequestDeserializer(jsonpickle.decode(request))
if not holder or not ... | As a python code expert, you are capable of creating scripts from specifications. |
Validate the action from the request json according to APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST
TracingEnabled | Can you tell what is the following Python 3 function doing
def _validate_request_action(self, action):
is_fail = False
fail_attribute = ""
for class_attribute in self.APPLY_CONNECTIVITY_CHANGES_ACTION_REQUIRED_ATTRIBUTE_LIST:
if type(class_attribute) is tuple:
if not ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_vlan_list(self, vlan_str):
""" Get VLAN list from input string
:param vlan_str:
:return list of VLANs or Exception
"""
result = set()
for splitted_vlan in vlan_str.split(","):
if "-" not in splitted_vlan:
if validate_vlan_number(spli... | Write a Python 3 function that can
get VLAN list from input string | As a Python code composer, you craft elegant and concise scripts. |
Adds VLAN to the specified number of VLANs in the specified local interface. | Can you tell what is the following Python 3 function doing
def add_vlan(self, vlan_id, full_name, port_mode, qnq, c_tag):
try:
action_result = self.add_vlan_flow.execute_flow(vlan_range=vlan_id,
port_mode=port_mode,
... | You are a Python code generator, capable of creating scripts from specifications. |
This method is used to remove VLAN from the interface. | Here you have a function in Python 3, explain what it does
def remove_vlan(self, vlan_id, full_name, port_mode):
try:
action_result = self.remove_vlan_flow.execute_flow(vlan_range=vlan_id,
port_name=full_name,
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def render_view(view_name, **args):
'''Process view and return root Node'''
try:
root_xml = get_view_root(view_name)
return render(root_xml, **args)
except CoreError as error:
error.add_view_info(ViewInfo(view_name, None))
raise
except:
info = exc_info()
e... | Can you implement a function in Python 3 that
processes view and return root Node | As a Python code composer, you craft elegant and concise scripts. |
def get_view_root(view_name: str) -> XmlNode:
'''Parses xml file and return root XmlNode'''
try:
path = join(deps.views_folder, '{0}.{1}'.format(view_name, deps.view_ext))
parser = Parser()
if path not in _XML_CACHE:
with open(path, 'rb') as xml_file:
_XML_CAC... | Write a Python 3 function for
parsing xml file and returns root XmlNode | You are a Python code generator, capable of creating scripts from specifications. |
Imports passed module class function full name and stores it to node s globals | Can you generate the documentation for the following Python 3 function
def import_global(node: Node, key: str, path: Any):
node.node_globals[key] = import_path(path) | As a Python code analyst, you investigate and solve complex coding mysteries |
def inject_global(node: Node, global_key: str, inject_key: Any):
"""Resolves passed dependency and stores it to node's globals"""
value = get_current_scope().container.get(inject_key)
set_global(node, global_key, value) | Write a Python 3 script to
resolve passed dependency and stores it to node s globals | You are a Python code generator, capable of creating scripts from specifications. |
Adds passed value to node s globals | Can you generate a brief explanation for the following Python 3 code
def set_global(node: Node, key: str, value: Any):
node.node_globals[key] = value | You are a Python code analyst, evaluating scripts for potential improvements. |
Calls node instance method | Can you generate a brief explanation for the following Python 3 code
def call(node: Node, key: str, value: Any):
value = _to_list(value)
if not value or not isinstance(value[-1], dict):
value.append({})
args = value[0:-1]
kwargs = value[-1]
node.__dict__[key](*args, **kwargs) | You are a Python code generator, capable of creating scripts from specifications. |
Make a request against the app. | Can you generate the documentation for the following Python 3 function
def request(self, rule, view_class, annotation):
headers = self._get_headers(rule, annotation)
example_values = self._get_example_values(rule, annotation)
# If any of the example values for DELETE/GET HTTP methods are dicts
... | As a Python code composer, you craft elegant and concise scripts. |
Subscribes to key changes | Can you tell what is the following Python 3 function doing
def observe(self, key: str, callback: Callable[[Any, Any], None]):
if key not in self._callbacks:
self._add_key(key)
self._callbacks[key].append(callback) | As a Python code analyst, you investigate and solve complex coding mysteries |
Releases callback from key changes | How would you explain what the following Python 3 function does
def release(self, key: str, callback: Callable[[Any, Any], None]):
try:
self._callbacks[key].remove(callback)
except (KeyError, ValueError):
pass | You are a Python code generator, capable of creating scripts from specifications. |
def observe(self, key, callback: Callable[[Any, Any], None]):
"""Subscribes to key changes"""
if key not in self.__dict__ and key not in self._callbacks:
raise KeyError('Entity ' + str(self) + 'doesn''t have attribute' + key)
super().observe(key, callback) | Write a Python 3 script for
subscribing to key changes | You are a Python code generator, capable of creating scripts from specifications. |
def observe_all(self, callback: Callable[[str, Any, Any], None]):
"""Subscribes to all keys changes"""
self._all_callbacks.append(callback) | Can you create a Python 3 function that
subscribes to all keys changes | You are a Python code generator, capable of creating scripts from specifications. |
def release_all(self, callback: Callable[[str, Any, Any], None]):
"""Releases callback from all keys changes"""
self._all_callbacks.remove(callback) | Write a Python 3 script for
releasing callback from all keys changes | You are a Python code generator, capable of creating scripts from specifications. |
def remove_key(self, key):
"""Remove own key, value"""
try:
self._own_keys.discard(key)
if self._parent and self._parent.has_key(key):
self._container[key] = self._parent[key]
else:
del self._container[key]
except KeyError:
... | Write a Python 3 script to
remove own key value | As a Python code translator, you convert algorithms and pseudocode into Python. |
def add_rule(self, binding_type: str, rule: BindingRule):
"""Adds new rule"""
if binding_type not in self._rules:
self._rules[binding_type] = []
self._rules[binding_type].insert(0, rule) | Can you write a function in Python 3 where it
adds a new rule to the list of rules for the given type. | You are a Python code generator, capable of creating scripts from specifications. |
def find_rule(self, binding_type: str, **args):
"""Finds rule by binding type and args"""
try:
rules = self._rules[binding_type]
return next(rule for rule in rules if rule.suitable(**args))
except (KeyError, StopIteration):
return None | How would you implement a function in Python 3 that
finds rule by binding type and args | As a python code expert, you are capable of creating scripts from specifications. |
Factory method to create expression target | Explain what the following Python 3 code does
def get_expression_target(expression: Expression, expr_vars: InheritedDict) -> BindingTarget:
'''Factory method to create expression target'''
root = expression.get_object_tree()
if len(root.children) != 1 or not PROPERTY_EXPRESSION_REGEX.fullmatch(expression.co... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def on_change(self, value):
'''Calles modifier on instance with passed value'''
self._modifier(self.inst, self.prop, value) | Can you create a Python 3 function that
calls the modifier on instance with passed value | You are a Python code architect, reviewing and designing scalable and efficient code |
Add and parse the arguments for the script. | Explain what the following Python 3 code does
def args():
parser = argparse.ArgumentParser(description='Run the Furious Examples.')
parser.add_argument('--gae-sdk-path', metavar='S', dest="gae_lib_path",
default="/usr/local/google_appengine",
help='path to the GA... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets up the sys. path for the proper
. | Here you have a function in Python 3, explain what it does
def setup(options):
sys.path.insert(0, options.gae_lib_path)
from dev_appserver import fix_sys_path
fix_sys_path() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run the passed in url of the example using GAE s rpc runner. | Can you generate the documentation for the following Python 3 function
def run(options):
from google.appengine.tools import appengine_rpc
from google.appengine.tools import appcfg
source = 'furious'
# use the same user agent that GAE uses in appcfg
user_agent = appcfg.GetUserAgent()
# Since w... | You are a Python code architect, reviewing and designing scalable and efficient code |
Enable and disable SNMP communityon the device | Explain what the following Python 3 code does
def discover(self):
details = self.autoload_flow.execute_flow(self.resource_config.supported_os,
self.resource_config.shell_name,
self.resource_config.family,
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns True if querypart_name with value is set. | Here you have a function in Python 3, explain what it does
def has(self, querypart_name, value=None):
querypart = self._queryparts.get(querypart_name)
if not querypart:
return False
if not querypart.is_set:
return False
if value:
return querypart.has(v... | You are a Python code analyst, evaluating scripts for potential improvements. |
def execute(self, parameters: dict = None):
"""Executes expression with passed parameters and returns result"""
try:
parameters = {} if parameters is None else parameters
return eval(self._compiled_code, parameters, {})
except:
info = exc_info()
er... | Write a Python 3 function that can
execute expression with passed parameters and returns result | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is called by the aborting_function function in the module that is not in the context of a process. | Can you tell what is the following Python 3 function doing
def aborting_function():
import random
logging.info('In aborting_function')
if random.random() < .5:
from furious.errors import AbortAndRestart
logging.info('Getting ready to restart')
# Raise AbortAndRestart like an Exce... | As a Python code composer, you craft elegant and concise scripts. |
def strip_ansi(state):
"""Remove ANSI escape codes from student result."""
stu_res = _strip_ansi(state.student_result)
return state.to_child(student_result = stu_res) | How would you implement a function in Python 3 that
removes ANSI escape codes from student result. | You are a Python code analyst, evaluating scripts for potential improvements. |
Check whether the student code contains text. | Here you have a function in Python 3, explain what it does
def has_code(state, text, incorrect_msg="The checker expected to find `{{text}}` in your command.", fixed=False):
stu_code = state.student_code
# either simple text matching or regex test
res = text in stu_code if fixed else re.search(text, stu_co... | As a python code expert, you are capable of creating scripts from specifications. |
Check whether student output contains specific text. | Can you generate the documentation for the following Python 3 function
def has_output(state,
text,
incorrect_msg="The checker expected to find {{'' if fixed else 'the pattern '}}`{{text}}` in the output of your command.",
fixed=False,
strip_ansi=True):
"""... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check whether the student is in the expected working directory. | Explain what the following Python 3 code does
def has_cwd(state, dir, incorrect_msg="Your current working directory should be `{{dir}}`. Use `cd {{dir}}` to navigate there."):
expr = "[[ $PWD == '{}' ]]".format(dir)
_msg = state.build_message(incorrect_msg, fmt_kwargs={ 'dir': dir })
has_expr_exit_code(stat... | As a Python code analyst, you investigate and solve complex coding mysteries |
def heartbeat(self, status_info):
'''
Update service status, indicating "up"-ness.
Args:
status_info (dict): a dictionary representing the status of the
service
`status_info` must have at least the fields 'role', 'load', and
'ttl'. Some additional fields... | Can you implement a function in Python 3 that
updates the status of the service with the given status_info. | As a Python code composer, you craft elegant and concise scripts. |
Remove the service with id from the service registry. | Make a summary of the following Python 3 code
def unregister(self, id):
'''
Remove the service with id `id` from the service registry.
'''
result = self.rr.table(self.table).get(id).delete().run()
if result != {
'deleted':1, 'errors':0,'inserted':0,
... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a unique service with only one instance for a given role and candidate. | Make a summary of the following Python 3 code
def unique_service(self, role, candidate=None):
'''
Retrieve a unique service, possibly setting or heartbeating it first.
A "unique service" is a service with only one instance for a given
role. Uniqueness is enforced by using the role name ... | As a python code expert, you are capable of creating scripts from specifications. |
def healthy_services(self, role=None):
'''
Look up healthy services in the registry.
A service is considered healthy if its 'last_heartbeat' was less than
'ttl' seconds ago
Args:
role (str, optional): role name
Returns:
If `role` is supplied, re... | Implement a function in Python 3 to
return a list of healthy services for the given role. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def new(batch_size=None, **options):
"""Get a new furious context and add it to the registry. If a batch size is
specified, use an AutoContext which inserts tasks in batches as they are
added to the context.
"""
if batch_size:
new_context = AutoContext(batch_size=batch_size, **options)
... | How would you code a function in Python 3 to
get a new furious context and add it to the registry. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a reference to the currently executing Async job object or None if not in an Async job. | Make a summary of the following Python 3 code
def get_current_async():
local_context = _local.get_local_context()
if local_context._executing_async:
return local_context._executing_async[-1]
raise errors.NotInContextError('Not in an _ExecutionContext.') | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_current_context():
"""Return a reference to the current Context object.
"""
local_context = _local.get_local_context()
if local_context.registry:
return local_context.registry[-1]
raise errors.NotInContextError('Not in a Context.') | Create a Python 3 function to
return a reference to the current Context object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_token_string(self, action=None):
"""Generate a hash of the given token contents that can be verified.
:param action:
A string representing the action that the generated hash is valid
for. This string is usually a URL.
:returns:
A string containin... | How would you code a function in Python 3 to
generate a base64 encoded version of the given XSRFToken. | You are a Python code analyst, evaluating scripts for potential improvements. |
Verify the given token string. | Given the following Python 3 function, write the documentation
def verify_token_string(self,
token_string,
action=None,
timeout=None,
current_time=None):
"""Generate a hash of the given token contents... | You are a Python code generator, capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.