output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def check(conn, command, exit=False, timeout=None, **kw):
"""
Execute a remote command with ``subprocess.Popen`` but report back the
results in a tuple with three items: stdout, stderr, and exit status.
This helper function *does not* provide any logging as it is the caller's
responsibility to do s... | Write a Python 3 script for
executing a remote command and return the output of the command. | You are a Python code analyst, evaluating scripts for potential improvements. |
def up_down_by_arrival(*filters, local_dir=".",
remote_dir=DEFAULT_REMOTE_DIR):
"""Monitors a local directory and a remote FlashAir directory and
generates sets of new files to be uploaded or downloaded.
Sets to upload are generated in a tuple
like (Direction.up, {...}), while dow... | Implement a function in Python 3 to
monitor a local directory and a remote FlashAir directory and generates sets of new files to be uploaded or downloaded. Sets to upload are generated in a tuple like (Direction.up, {...}), while download sets to download are generated in a tuple like (Direction.down, {...}). The gener... | You are a Python code architect, reviewing and designing scalable and efficient code |
def up_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR):
"""Monitors a local directory and
generates sets of new files to be uploaded to FlashAir.
Sets to upload are generated in a tuple like (Direction.up, {...}).
The generator yields before each upload actually takes place."""
lo... | Create a Python 3 function for
monitoring a local directory and generates sets of new files to be uploaded to FlashAir. | You are a Python code analyst, evaluating scripts for potential improvements. |
def down_by_arrival(*filters, local_dir=".", remote_dir=DEFAULT_REMOTE_DIR):
"""Monitors a remote FlashAir directory and generates sets of
new files to be downloaded from FlashAir.
Sets to download are generated in a tuple like (Direction.down, {...}).
The generator yields AFTER each download actually t... | Can you create a Python 3 function that
monitors a remote FlashAir directory and generates sets of new files to be downloaded from FlashAir. Sets to download are generated in a tuple like (Direction.down, {...}). The generator yields AFTER each download actually takes place. | As a Python code analyst, you investigate and solve complex coding mysteries |
Attempt to stream a remote file into a local file object and removes the local file if it s interrupted by any error | Here you have a function in Python 3, explain what it does
def _write_file_safely(local_path, fileinfo, response):
try:
_write_file(local_path, fileinfo, response)
except BaseException as e:
logger.warning("{} interrupted writing {} -- "
"cleaning up partial file".format(
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _upload_file_safely(fileinfo, remote_dir):
"""attempts to upload a local file to FlashAir,
tries to remove the remote file if interrupted by any error"""
try:
upload.upload_file(fileinfo.path, remote_dir=remote_dir)
except BaseException as e:
logger.warning("{} interrupted writing {}... | Write a Python 3 function that can
attempt to upload a local file to FlashAir and attempts to remove the remote file if interrupted by any error | As a Python code analyst, you investigate and solve complex coding mysteries |
Sends a rsync request to the specified hosts. | Explain what the following Python 3 code does
def rsync(hosts, source, destination, logger=None, sudo=False):
logger = logger or basic_remote_logger()
sync = _RSync(source, logger=logger)
# setup_targets
if not isinstance(hosts, list):
hosts = [hosts]
for host in hosts:
conn = Conn... | You are a Python code analyst, evaluating scripts for potential improvements. |
def map_single_axis(low, high, dead_zone, hot_zone, value):
"""
Apply dead and hot zones before mapping a value to a range. The dead and hot zones are both expressed as the
proportion of the axis range which should be regarded as 0.0 or 1.0 (or -1.0 depending on cardinality) respectively,
so for example... | How would you code a function in Python 3 to
map a single value to a range of dead and hot zones. | You are a Python code generator, capable of creating scripts from specifications. |
def map_dual_axis(low, high, centre, dead_zone, hot_zone, value):
"""
Map an axis with a central dead zone and hot zones at each end to a range from -1.0 to 1.0. This in effect uses two
calls to map_single_axis, choosing whether to use centre and low, or centre and high as the low and high values in
tha... | How would you code a function in Python 3 to
map a value to a range from - 1. 0 to 1. 0. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def register_button_handler(self, button_handler, button_sname: str):
"""
Register a handler function which will be called when a button is pressed
:param button_handler:
A function which will be called when any of the specified buttons are pressed. The
function is calle... | Create a Python 3 function for
registering a function which will be called when a button is pressed. | You are a Python code analyst, evaluating scripts for potential improvements. |
Called when an absolute axis event is received from evdev. | Make a summary of the following Python 3 code
def axis_updated(self, event: InputEvent, prefix=None):
if prefix is not None:
axis = self.axes_by_code.get(prefix + str(event.code))
else:
axis = self.axes_by_code.get(event.code)
if axis is not None:
axis.receive... | As a python code expert, you are capable of creating scripts from specifications. |
Sets the centre points for each axis to the current value for that axis. | Here you have a function in Python 3, explain what it does
def set_axis_centres(self, *args):
for axis in self.axes_by_code.values():
if isinstance(axis, CentredAxis):
axis.centre = axis.value | As a Python code composer, you craft elegant and concise scripts. |
Convert the input value from evdev to a 0. 0 to 1. 0 range. | Make a summary of the following Python 3 code
def _input_to_raw_value(self, value: int) -> float:
return (float(value) - self.min_raw_value) / self.max_raw_value | As a Python code translator, you convert algorithms and pseudocode into Python. |
def value(self) -> float:
"""
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) at the extreme position of
the trigger or the edge of the hot zone, if defined as other than... | Can you implement a function in Python 3 that
returns the value of the key entry in the specified axis. | You are a Python code analyst, evaluating scripts for potential improvements. |
def receive_device_value(self, raw_value: int):
"""
Set a new value, called from within the joystick implementation class when parsing the event queue.
:param raw_value: the raw value from the joystick hardware
:internal:
"""
new_value = self._input_to_raw_value(raw_val... | Can you implement a function in Python 3 that
sets a new value from the hardware joystick implementation class when parsing the event queue. | As a Python code composer, you craft elegant and concise scripts. |
def value(self) -> float:
"""
Get a centre-compensated, scaled, value for the axis, taking any dead-zone into account. The value will
scale from 0.0 at the edge of the dead-zone to 1.0 (positive) or -1.0 (negative) at the extreme position of
the controller or the edge of the hot zone, if... | Can you create a Python 3 function that
returns the value of the cluster entry. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set a new value from the hardware joystick implementation class when parsing the event queue. | Make a summary of the following Python 3 code
def receive_device_value(self, raw_value: int):
new_value = self._input_to_raw_value(raw_value)
self.__value = new_value
if new_value > self.max:
self.max = new_value
elif new_value < self.min:
self.min = new_value | You are a Python code analyst, evaluating scripts for potential improvements. |
def button_pressed(self, key_code, prefix=None):
"""
Called from the controller classes to update the state of this button manager when a button is pressed.
:internal:
:param key_code:
The code specified when populating Button instances
:param prefix:
Ap... | Implement a function in Python 3 to
call by the controller classes to update the state of this button manager when a button is pressed. | You are a Python code generator, capable of creating scripts from specifications. |
Called by the controller classes to update the state of this button manager when a button is released. | Can you generate a brief explanation for the following Python 3 code
def button_released(self, key_code, prefix=None):
if prefix is not None:
state = self.buttons_by_code.get(prefix + str(key_code))
else:
state = self.buttons_by_code.get(key_code)
if state is not None:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns the set of Buttons which have been pressed since this call was last made clearing it as we do. | Here you have a function in Python 3, explain what it does
def check_presses(self):
pressed = []
for button, state in self.buttons.items():
if state.was_pressed_since_last_check:
pressed.append(button)
state.was_pressed_since_last_check = False
self.__... | You are a Python code architect, reviewing and designing scalable and efficient code |
def held(self, sname):
"""
Determines whether a button is currently held, identifying it by standard name
:param sname:
The standard name of the button
:return:
None if the button is not held down, or is not available, otherwise the number of seconds as a floatin... | Create a Python 3 function for
determining whether a button is currently held by standard name. | You are a Python code architect, reviewing and designing scalable and efficient code |
Register a handler function which will be called when a button is pressed. | How would you explain what the following Python 3 function does
def register_button_handler(self, button_handler, buttons):
if not isinstance(buttons, list):
buttons = [buttons]
for button in buttons:
state = self.buttons.get(button)
if state is not None:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get wrapped function.
:rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] | How would you explain what the following Python 3 function does
def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]:
return self.__func | You are a Python code generator, capable of creating scripts from specifications. |
This is a function decorator that returns a function that can be used to wrap the function. | Explain what the following Python 3 code does
def _get_function_wrapper(
self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
) -> typing.Callable[..., typing.Any]:
"""Here should be constructed and returned real decorator.
:param func: Wrapped function... | You are a Python code analyst, evaluating scripts for potential improvements. |
Await result if coroutine was returned. | Given the following Python 3 function, write the documentation
def _await_if_required(
target: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
) -> typing.Callable[..., typing.Any]:
"""Await result if coroutine was returned."""
@functools.wraps(target)
... | As a python code expert, you are capable of creating scripts from specifications. |
def unique_name(device: InputDevice) -> str:
"""
Construct a unique name for the device based on, in order if available, the uniq ID, the phys ID and
finally a concatenation of vendor, product, version and filename.
:param device:
An InputDevice instance to query
:return:
A string c... | Can you write a function in Python 3 where it
constructs a unique name for the input device. | As a Python code composer, you craft elegant and concise scripts. |
def find_matching_controllers(*requirements, **kwargs) -> [ControllerDiscovery]:
"""
Find a sequence of controllers which match the supplied requirements, or raise an error if no such controllers
exist.
:param requirements:
Zero or more ControllerRequirement instances defining the requirements ... | Create a Python 3 function for
finding a sequence of controllers which satisfy the supplied requirements. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def find_all_controllers(**kwargs) -> [ControllerDiscovery]:
"""
:return:
A list of :class:`~approxeng.input.controllers.ControllerDiscovery` instances corresponding to controllers
attached to this host, ordered by the ordering on ControllerDiscovery. Any controllers found will be
constr... | Can you create a Python 3 function that
finds all controllers attached to this host and populate the registry with the controllers that are registered with the given kwargs. | You are a Python code architect, reviewing and designing scalable and efficient code |
Simple test function which prints out all devices found by evdev
| Can you generate the documentation for the following Python 3 function
def print_devices():
def device_verbose_info(device: InputDevice) -> {}:
"""
Gather and format as much info as possible about the supplied InputDevice. Used mostly for debugging at this point.
:param device:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns True if the supplied ControllerDiscovery matches this requirement False otherwise. | Here you have a function in Python 3, explain what it does
def accept(self, discovery: ControllerDiscovery):
if self.require_class is not None and not isinstance(discovery.controller, self.require_class):
return False
if self.snames is not None:
all_controls = discovery.controlle... | As a python code expert, you are capable of creating scripts from specifications. |
Takes a dictionary of Config. key and Config. value and returns a dictionary of processed keys and values to be used in the FlashAir s config. cz | Can you tell what is the following Python 3 function doing
def config(param_map, mastercode=DEFAULT_MASTERCODE):
pmap = {Config.mastercode: mastercode}
pmap.update(param_map)
processed_params = dict(_process_params(pmap))
return processed_params | As a python code expert, you are capable of creating scripts from specifications. |
Posts a param_map created with config to
the FlashAir config. cgi entrypoint | Can you generate a brief explanation for the following Python 3 code
def post(param_map, url=URL):
prepped_request = _prep_post(url=url, **param_map)
return cgi.send(prepped_request) | You are a Python code architect, reviewing and designing scalable and efficient code |
Validates that the given time is within the allowed time range. | Can you tell what is the following Python 3 function doing
def _validate_timeout(seconds: float):
val = int(seconds * 1000)
assert 60000 <= val <= 4294967294, "Bad value: {}".format(val)
return val | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse_datetime(datetime_input):
"""The arrow library is sadly not good enough to parse
certain date strings. It even gives unexpected results for partial
date strings such as '2015-01' or just '2015', which I think
should be seen as 'the first moment of 2014'.
This function should overcome those... | Create a Python 3 function for
parsing a date string into a tuple of date and time values. | You are a Python code analyst, evaluating scripts for potential improvements. |
Set the LED on the DS3 controller. | Here you have a function in Python 3, explain what it does
def set_led(self, led_number, led_value):
if 1 > led_number > 4:
return
write_led_value(hw_id=self.device_unique_name, led_name='sony{}'.format(led_number), value=led_value) | You are a Python code analyst, evaluating scripts for potential improvements. |
Mix a pair of joystick axes returning a pair of wheel speeds. | Given the following Python 3 function, write the documentation
def mixer(yaw, throttle, max_power=100):
left = throttle + yaw
right = throttle - yaw
scale = float(max_power) / max(1, abs(left), abs(right))
return int(left * scale), int(right * scale) | You are a Python code architect, reviewing and designing scalable and efficient code |
def admin_command(sudo, command):
"""
If sudo is needed, make sure the command is prepended
correctly, otherwise return the command as it came.
:param sudo: A boolean representing the intention of having a sudo command
(or not)
:param command: A list of the actual command to execute... | Write a Python 3 function that can
return the command to be executed by the admin | As a Python code composer, you craft elegant and concise scripts. |
def scan_system():
"""
Scans /sys/class/leds looking for entries, then examining their .../device/uevent file to obtain unique hardware
IDs corresponding to the associated hardware. This then allows us to associate InputDevice based controllers with
sets of zero or more LEDs. The result is a dict from h... | Write a Python 3 script to
scan the system for all LEDs and returns a dict of name to filename. | As a Python code analyst, you investigate and solve complex coding mysteries |
Bind a set of controllers to a set of InputDevice instances. | Can you generate the documentation for the following Python 3 function
def bind_controllers(*discoveries, print_events=False):
discoveries = list(discoveries)
class SelectThread(Thread):
def __init__(self):
Thread.__init__(self, name='evdev select thread')
self.daemon = True
... | As a python code expert, you are capable of creating scripts from specifications. |
Encode a mtime float as a 32 - bit FAT time | Can you generate the documentation for the following Python 3 function
def _encode_time(mtime: float):
dt = arrow.get(mtime)
dt = dt.to("local")
date_val = ((dt.year - 1980) << 9) | (dt.month << 5) | dt.day
secs = dt.second + dt.microsecond / 10**6
time_val = (dt.hour << 11) | (dt.minute << 5) | mat... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def threadpooled(
func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
*,
loop_getter: None = None,
loop_getter_need_context: bool = False,
) -> typing.Callable[..., "concurrent.futures.Future[typing.Any]"]:
"""Overload: function callable, no loop getter.""" | Create a Python 3 function for
overloading function callable with loop getter. | You are a Python code analyst, evaluating scripts for potential improvements. |
Overload function callable loop getter available. | Can you tell what is the following Python 3 function doing
def threadpooled(
func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
*,
loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
loop_getter_need_context: bool = Fa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def threadpooled(
func: None = None,
*,
loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None,
loop_getter_need_context: bool = False,
) -> ThreadPooled:
"""Overload: No function.""" | Can you create a Python 3 function that
overloads : No function. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def threadpooled( # noqa: F811
func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None,
*,
loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None,
loop_getter_need_context: bool = False,
) -... | Implement a function in Python 3 to
post function to ThreadPoolExecutor. | As a Python code composer, you craft elegant and concise scripts. |
Create and configure the ThreadPoolExecutor. | Can you generate a brief explanation for the following Python 3 code
def configure(cls: typing.Type["ThreadPooled"], max_workers: typing.Optional[int] = None) -> None:
if isinstance(cls.__executor, ThreadPoolExecutor):
if cls.__executor.max_workers == max_workers:
return
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def executor(self) -> "ThreadPoolExecutor":
"""Executor instance.
:rtype: ThreadPoolExecutor
"""
if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown:
self.configure()
return self.__executor | How would you code a function in Python 3 to
return the ThreadPoolExecutor instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the loop getter function for the given base namespace. | Can you generate the documentation for the following Python 3 function
def loop_getter(
self
) -> typing.Optional[typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop]]:
"""Loop getter.
:rtype: typing.Union[None, typing.Callable[..., asyncio.AbstractEventL... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get event loop in decorator class. | Here you have a function in Python 3, explain what it does
def _get_loop(self, *args: typing.Any, **kwargs: typing.Any) -> typing.Optional[asyncio.AbstractEventLoop]:
if callable(self.loop_getter):
if self.loop_getter_need_context:
return self.loop_getter(*args, **kwargs) # pylint: ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def needs_ssh(hostname, _socket=None):
"""
Obtains remote hostname of the socket and cuts off the domain part
of its FQDN.
"""
if hostname.lower() in ['localhost', '127.0.0.1', '127.0.1.1']:
return False
_socket = _socket or socket
fqdn = _socket.getfqdn()
if hostname == fqdn:
... | Create a Python 3 function to
return True if the given hostname needs SSH. | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_python_executable(conn):
"""
Try to determine the remote Python version so that it can be used
when executing. Avoids the problem of different Python versions, or distros
that do not use ``python`` but do ``python3``
"""
# executables in order of preference:
executables = ['python3',... | Write a Python 3 function that can
try to determine the remote Python executable and return it. | As a python code expert, you are capable of creating scripts from specifications. |
Detects if the user is a sudo | Can you tell what is the following Python 3 function doing
def _detect_sudo(self, _execnet=None):
exc = _execnet or execnet
gw = exc.makegateway(
self._make_connection_string(self.hostname, use_sudo=False)
)
channel = gw.remote_exec(
'import getpass; channel.send... | As a python code expert, you are capable of creating scripts from specifications. |
Allows remote execution of a local module. | Can you generate a brief explanation for the following Python 3 code
def import_module(self, module):
if self.remote_import_system is not None:
if self.remote_import_system == 'json':
self.remote_module = JsonModuleExecute(self, module, self.logger)
else:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(name, fallback='ssh'):
"""
Retrieve the matching backend class from a string. If no backend can be
matched, it raises an error.
>>> get('ssh')
<class 'remoto.backends.BaseConnection'>
>>> get()
<class 'remoto.backends.BaseConnection'>
>>> get('non-existent')
<class 'remoto.b... | Implement a Python 3 function for
retrieving the matching backend class from a string. | As a Python code analyst, you investigate and solve complex coding mysteries |
def config(env=DEFAULT_ENV, default='locmem://'):
"""Returns configured CACHES dictionary from CACHE_URL"""
config = {}
s = os.environ.get(env, default)
if s:
config = parse(s)
return config | Create a Python 3 function to
return configured CACHES dictionary from CACHE_URL | You are a Python code analyst, evaluating scripts for potential improvements. |
def parse(url):
"""Parses a cache URL."""
config = {}
url = urlparse.urlparse(url)
# Handle python 2.6 broken url parsing
path, query = url.path, url.query
if '?' in path and query == '':
path, query = path.split('?', 1)
cache_args = dict([(key.upper(), ';'.join(val)) for key, val ... | Can you create a Python 3 function that
parses a cache URL. | As a python code expert, you are capable of creating scripts from specifications. |
def memory_changed(url=URL):
"""Returns True if memory has been written to, False otherwise"""
response = _get(Operation.memory_changed, url)
try:
return int(response.text) == 1
except ValueError:
raise IOError("Likely no FlashAir connection, "
"memory changed CGI c... | Can you implement a function in Python 3 that
returns True if memory has been written to False otherwise | As a Python code composer, you craft elegant and concise scripts. |
Translate a string into a new language. | How would you explain what the following Python 3 function does
def do_translate(parser, token):
bits = token.split_contents()
if len(bits) < 2:
raise TemplateSyntaxError("'%s' takes at least one argument" % bits[0])
message_string = parser.compile_filter(bits[1])
remaining = bits[2:]
noop ... | As a Python code analyst, you investigate and solve complex coding mysteries |
A function that returns an async task. | How would you explain what the following Python 3 function does
def asynciotask(
func: None = None,
*,
loop_getter: typing.Union[
typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop
] = asyncio.get_event_loop,
loop_getter_need_context: bool = False,
) -> AsyncIOTask:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Decorator to wrap function in future and return. | Can you generate a brief explanation for the following Python 3 code
def asynciotask( # noqa: F811
func: typing.Optional[typing.Callable[..., "typing.Awaitable[typing.Any]"]] = None,
*,
loop_getter: typing.Union[
typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop
] = asy... | You are a Python code generator, capable of creating scripts from specifications. |
def get_loop(self, *args, **kwargs): # type: (typing.Any, typing.Any) -> asyncio.AbstractEventLoop
"""Get event loop in decorator class."""
if callable(self.loop_getter):
if self.loop_getter_need_context:
return self.loop_getter(*args, **kwargs) # pylint: disable=not-callab... | Write a Python 3 function that can
get event loop in decorator class. | As a python code expert, you are capable of creating scripts from specifications. |
This is a function decorator which returns a function which will produce asyncio. Task on call with function called inside it
Taxonomy. | Explain what the following Python 3 code does
def _get_function_wrapper(
self, func: typing.Callable[..., "typing.Awaitable[typing.Any]"]
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:
"""Here should be constructed and returned real decorator.
:param func: Wrapped function
:... | You are a Python code architect, reviewing and designing scalable and efficient code |
def threaded(
name: typing.Callable[..., typing.Any], daemon: bool = False, started: bool = False
) -> typing.Callable[..., threading.Thread]:
"""Overload: Call decorator without arguments.""" | Write a Python 3 script to
overload Call decorator without arguments. | You are a Python code architect, reviewing and designing scalable and efficient code |
def threaded( # noqa: F811
name: typing.Optional[typing.Union[str, typing.Callable[..., typing.Any]]] = None,
daemon: bool = False,
started: bool = False,
) -> typing.Union[Threaded, typing.Callable[..., threading.Thread]]:
"""Run function in separate thread.
:param name: New thread name.
... | Write a Python 3 function that can
run function in separate thread. :param name: New thread name. If callable: use as wrapped function. If none: use wrapped function name. :type name: typing.Union[None, str, typing.Callable] :param daemon: Daemonize thread. :type daemon: bool :param started: Return started thread :type... | As a Python code analyst, you investigate and solve complex coding mysteries |
This is a function decorator that returns a thread that will be started when the function is called. | Can you generate a brief explanation for the following Python 3 code
def _get_function_wrapper(
self, func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]
) -> typing.Callable[..., threading.Thread]:
"""Here should be constructed and returned real decorator.
... | As a python code expert, you are capable of creating scripts from specifications. |
Set the issuer of the object. | Given the following Python 3 function, write the documentation
def issuer(self, value):
is_oscrypto = isinstance(value, asymmetric.Certificate)
if not is_oscrypto and not isinstance(value, x509.Certificate):
raise TypeError(_pretty_message(
'''
issuer must be... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the key hash algorithm. | Explain what the following Python 3 code does
def key_hash_algo(self, value):
if value not in set(['sha1', 'sha256']):
raise ValueError(_pretty_message(
'''
hash_algo must be one of "sha1", "sha256", not %s
''',
repr(value)
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the nonce of the object. | How would you explain what the following Python 3 function does
def nonce(self, value):
if not isinstance(value, bool):
raise TypeError(_pretty_message(
'''
nonce must be a boolean, not %s
''',
_type_name(value)
))
... | As a python code expert, you are capable of creating scripts from specifications. |
Sets the value for an extension using a fully constructed ASN. 1 Value object. | Can you generate the documentation for the following Python 3 function
def set_extension(self, name, value):
if isinstance(name, str_cls):
request_extension_oids = set([
'service_locator',
'1.3.6.1.5.5.7.48.1.7'
])
tbs_request_extension_oids =... | You are a Python code analyst, evaluating scripts for potential improvements. |
Builds the OCSP request object. | Make a summary of the following Python 3 code
def build(self, requestor_private_key=None, requestor_certificate=None, other_certificates=None):
def _make_extension(name, value):
return {
'extn_id': name,
'critical': False,
'extn_value': value
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the response status of the OCSP response. | Can you generate the documentation for the following Python 3 function
def response_status(self, value):
if not isinstance(value, str_cls):
raise TypeError(_pretty_message(
'''
response_status must be a unicode string, not %s
''',
_typ... | You are a Python code generator, capable of creating scripts from specifications. |
def certificate(self, value):
"""
An asn1crypto.x509.Certificate or oscrypto.asymmetric.Certificate object
of the certificate the response is about.
"""
if value is not None:
is_oscrypto = isinstance(value, asymmetric.Certificate)
if not is_oscrypto and n... | How would you implement a function in Python 3 that
sets the certificate of the response. | As a python code expert, you are capable of creating scripts from specifications. |
Sets the certificate status of the certificate. | Make a summary of the following Python 3 code
def certificate_status(self, value):
if value is not None:
if not isinstance(value, str_cls):
raise TypeError(_pretty_message(
'''
certificate_status must be a unicode string, not %s
... | You are a Python code generator, capable of creating scripts from specifications. |
def revocation_date(self, value):
"""
A datetime.datetime object of when the certificate was revoked, if the
status is not "good" or "unknown".
"""
if value is not None and not isinstance(value, datetime):
raise TypeError(_pretty_message(
'''
... | How would you code a function in Python 3 to
set the revocation date of the certificate. | As a Python code composer, you craft elegant and concise scripts. |
def certificate_issuer(self, value):
"""
An asn1crypto.x509.Certificate object of the issuer of the certificate.
This should only be set if the OCSP responder is not the issuer of
the certificate, but instead a special certificate only for OCSP
responses.
"""
if ... | Create a Python 3 function for
setting the certificate issuer of the OCSP response. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Set the _this_update field of the object. | How would you explain what the following Python 3 function does
def this_update(self, value):
if not isinstance(value, datetime):
raise TypeError(_pretty_message(
'''
this_update must be an instance of datetime.datetime, not %s
''',
_t... | You are a Python code analyst, evaluating scripts for potential improvements. |
def next_update(self, value):
"""
A datetime.datetime object of when the response may next change. This
should only be set if responses are cached. If responses are generated
fresh on every request, this should not be set.
"""
if not isinstance(value, datetime):
... | Write a Python 3 script to
set the next update date for this entry. | You are a Python code architect, reviewing and designing scalable and efficient code |
Sets the value for an extension using a fully constructed ASN. 1 Value object. | Make a summary of the following Python 3 code
def set_extension(self, name, value):
if isinstance(name, str_cls):
response_data_extension_oids = set([
'nonce',
'extended_revoke',
'1.3.6.1.5.5.7.48.1.2',
'1.3.6.1.5.5.7.48.1.9'
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def build(self, responder_private_key=None, responder_certificate=None):
"""
Validates the request information, constructs the ASN.1 structure and
signs it.
The responder_private_key and responder_certificate parameters are only
required if the response_status is "successful".
... | Create a Python 3 function for
building the OCSP response object. | As a Python code analyst, you investigate and solve complex coding mysteries |
def make_openid_request(arq, keys, issuer, request_object_signing_alg, recv):
"""
Construct the JWT to be passed by value (the request parameter) or by
reference (request_uri).
The request will be signed
:param arq: The Authorization request
:param keys: Keys to use for signing/encrypting. A Ke... | Create a Python 3 function to
build a OpenID request from an Authorization request. | You are a Python code architect, reviewing and designing scalable and efficient code |
Verify that the request and response are valid. | Here you have a function in Python 3, explain what it does
def verify(self, **kwargs):
super(AuthorizationRequest, self).verify(**kwargs)
clear_verified_claims(self)
args = {}
for arg in ["keyjar", "opponent_id", "sender", "alg", "encalg",
"encenc"]:
try... | As a Python code composer, you craft elegant and concise scripts. |
def verify(self, **kwargs):
"""
Implementations MUST either return both a Client Configuration Endpoint
and a Registration Access Token or neither of them.
:param kwargs:
:return: True if the message is OK otherwise False
"""
super(RegistrationResponse, self).veri... | Write a Python 3 function that can
verify that the message is OK. | As a Python code analyst, you investigate and solve complex coding mysteries |
Return a string representation of the current time in a while. | Can you tell what is the following Python 3 function doing
def in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0, time_format=TIME_FORMAT):
"""
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param... | You are a Python code architect, reviewing and designing scalable and efficient code |
True if point datetime specification is before now | Can you generate a brief explanation for the following Python 3 code
def before(point):
if not point:
return True
if isinstance(point, str):
point = str_to_time(point)
elif isinstance(point, int):
point = time.gmtime(point)
return time.gmtime() < point | As a Python code translator, you convert algorithms and pseudocode into Python. |
def later_than(after, before):
""" True if then is later or equal to that """
if isinstance(after, str):
after = str_to_time(after)
elif isinstance(after, int):
after = time.gmtime(after)
if isinstance(before, str):
before = str_to_time(before)
elif isinstance(before, int):
... | Can you implement a function in Python 3 that
trues if after is later or equal to that | As a Python code analyst, you investigate and solve complex coding mysteries |
def epoch_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0):
"""
Return the number of seconds since epoch a while from now.
:param days:
:param seconds:
:param microseconds:
:param milliseconds:
:param minutes:
:param hours:
... | How would you implement a function in Python 3 that
returns the number of seconds since epoch a while from now. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def set_defaults(self):
"""
Based on specification set a parameters value to the default value.
"""
for key, val in self.c_default.items():
self._dict[key] = val | Implement a function in Python 3 to
set the default values of the parameters. | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a string using the application / x - www - form - urlencoded format of the resource. | Here you have a function in Python 3, explain what it does
def to_urlencoded(self, lev=0):
_spec = self.c_param
if not self.lax:
for attribute, (_, req, _ser, _, na) in _spec.items():
if req and attribute not in self._dict:
raise MissingRequiredAttribute(... | You are a Python code analyst, evaluating scripts for potential improvements. |
Serialize this instance to another representation. | Explain what the following Python 3 code does
def serialize(self, method="urlencoded", lev=0, **kwargs):
return getattr(self, "to_%s" % method)(lev=lev, **kwargs) | As a Python code analyst, you investigate and solve complex coding mysteries |
Deserialize from an external representation to an internal representation. | Here you have a function in Python 3, explain what it does
def deserialize(self, info, method="urlencoded", **kwargs):
try:
func = getattr(self, "from_%s" % method)
except AttributeError:
raise FormatError("Unknown serialization method (%s)" % method)
else:
re... | As a python code expert, you are capable of creating scripts from specifications. |
This method creates a new instance of the class instance from a urlencoded string. | Given the following Python 3 function, write the documentation
def from_urlencoded(self, urlencoded, **kwargs):
# parse_qs returns a dictionary with keys and values. The values are
# always lists even if there is only one value in the list.
# keys only appears once.
if isinstance(urlen... | As a python code expert, you are capable of creating scripts from specifications. |
def to_dict(self, lev=0):
"""
Return a dictionary representation of the class
:return: A dict
"""
_spec = self.c_param
_res = {}
lev += 1
for key, val in self._dict.items():
try:
(_, req, _ser, _, null_allowed) = _spec[str(ke... | Write a Python 3 script for
returning a dictionary representation of the class Taxonomy. | As a Python code analyst, you investigate and solve complex coding mysteries |
def from_dict(self, dictionary, **kwargs):
"""
Direct translation, so the value for one key might be a list or a
single value.
:param dictionary: The info
:return: A class instance or raise an exception on error
"""
_spec = self.c_param
for key, val in ... | How would you implement a function in Python 3 that
directs translation, so the value for one key might be a list or a single value. :param dictionary: The info :return: A class instance or raise an exception on error | As a python code expert, you are capable of creating scripts from specifications. |
def _add_value(self, skey, vtyp, key, val, _deser, null_allowed):
"""
Main method for adding a value to the instance. Does all the
checking on type of value and if among allowed values.
:param skey: string version of the key
:param vtyp: Type of value
:param key... | Write a Python 3 script for
adding a value to the instance. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Serialize the content of this object into a JSON string. | Can you generate a brief explanation for the following Python 3 code
def to_json(self, lev=0, indent=None):
if lev:
return self.to_dict(lev + 1)
else:
return json.dumps(self.to_dict(1), indent=indent) | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_json(self, txt, **kwargs):
"""
Convert from a JSON string to an instance of this class.
:param txt: The JSON string (a ``str``, ``bytes`` or ``bytearray``
instance containing a JSON document)
:param kwargs: extra keyword arguments
:return: The instan... | Implement a Python 3 function for
converting from a JSON string to an instance of this class. | You are a Python code generator, capable of creating scripts from specifications. |
Create a signed JWT representation of the class instance | Can you generate a brief explanation for the following Python 3 code
def to_jwt(self, key=None, algorithm="", lev=0, lifetime=0):
_jws = JWS(self.to_json(lev), alg=algorithm)
return _jws.sign_compact(key) | As a Python code composer, you craft elegant and concise scripts. |
def from_jwt(self, txt, keyjar, verify=True, **kwargs):
"""
Given a signed and/or encrypted JWT, verify its correctness and then
create a class instance from the content.
:param txt: The JWT
:param key: keys that might be used to decrypt and/or verify the
signature o... | Implement a function in Python 3 to
give a signed and or encrypted JWT create a new instance of the class instance. | As a python code expert, you are capable of creating scripts from specifications. |
def verify(self, **kwargs):
"""
Make sure all the required values are there and that the values are
of the correct type
"""
_spec = self.c_param
try:
_allowed = self.c_allowed_values
except KeyError:
_allowed = {}
for (attribute, (... | Can you write a function in Python 3 where it
verifies that all the required values are there and that the values are of the correct type. | You are a Python code generator, capable of creating scripts from specifications. |
def request(self, location, fragment_enc=False):
"""
Given a URL this method will add a fragment, a query part or extend
a query part if it already exists with the information in this instance.
:param location: A URL
:param fragment_enc: Whether the information should b... | Can you create a Python 3 function that
gives a URL this method will add a fragment, a query part or extend a query part if it already exists with the information in this instance. :param location: A URL :param fragment_enc: Whether the information should be placed in a fragment (True) or in a query part (False) :retur... | As a python code expert, you are capable of creating scripts from specifications. |
def extra(self):
"""
Return the extra parameters that this instance. Extra meaning those
that are not listed in the c_params specification.
:return: The key,value pairs for keys that are not in the c_params
specification,
"""
return dict([(key, val) f... | Write a Python 3 function for
returning the extra parameters that this instance is not listed in the c_params specification. | You are a Python code architect, reviewing and designing scalable and efficient code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.