Instruction:
Write a Python 3 script to
scan the system for all LEDs and returns a dict of name to filename.

Response:
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 hardware address to a dict of name to filename, where the name
    is the name of the LED and the filename is the brightness control to which writing a value changes the LED state.

    At the same time, scans /sys/class/power_supply looking for battery entries and analysing them in the same way.

    Hardware IDs are, in order of preference, the HID_UNIQ address (corresponding to the physical MAC of an attached
    bluetooth or similar HID device), or the PHYS corresponding to other devices. This is the same logic as used in the
    evdev based scanning to group together input nodes for composite controllers (i.e. ones with motion sensors as well
    as physical axes). It is intended to produce the same results, so the LEDs for e.g. a PS4 controller will be keyed
    on the same physical address as that returned by :func:`approxeng.input.controllers.unique_name` for all the
    InputDevice instances associated with a given controller.

    :return:
        A dict containing available LEDs, keyed on physical device ID
    """

    def find_device_hardware_id(uevent_file_path):
        hid_uniq = None
        phys = None
        for line in open(uevent_file_path, 'r').read().split('\n'):
            parts = line.split('=')
            if len(parts) == 2:
                name, value = parts
                value = value.replace('"', '')
                if name == 'HID_UNIQ' and value:
                    hid_uniq = value
                elif name == 'PHYS' and value:
                    phys = value.split('/')[0]
        if hid_uniq:
            return hid_uniq
        elif phys:
            return phys
        return None

    leds = {}
    for sub in ['/sys/class/leds/' + sub_dir for sub_dir in listdir('/sys/class/leds')]:
        led_name = sub.split(':')[-1]
        write_path = sub + '/brightness'
        device_id = find_device_hardware_id(sub + '/device/uevent')
        if device_id:
            if device_id not in leds:
                leds[device_id] = {}
            leds[device_id][led_name] = write_path

    power = {}
    for sub in ['/sys/class/power_supply/' + sub_dir for sub_dir in listdir('/sys/class/power_supply')]:
        read_path = sub + '/capacity'
        device_id = find_device_hardware_id(sub + '/device/uevent')
        if device_id:
            power[device_id] = read_path

    return {'leds': leds,
            'power': power}


Instruction:
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
            self.running = True

            self.device_to_controller_discovery = {}
            for discovery in discoveries:
                for d in discovery.devices:
                    self.device_to_controller_discovery[d.fn] = discovery
            self.all_devices = reduce(lambda x, y: x + y, [discovery.devices for discovery in discoveries])

        def run(self):

            for discovery in discoveries:
                discovery.controller.device_unique_name = discovery.name

            while self.running:
                try:
                    r, w, x = select(self.all_devices, [], [], 0.5)
                    for fd in r:
                        active_device = fd
                        controller_discovery = self.device_to_controller_discovery[active_device.fn]
                        controller = controller_discovery.controller
                        controller_devices = controller_discovery.devices
                        prefix = None
                        if controller.node_mappings is not None and len(controller_devices) > 1:
                            try:
                                prefix = controller.node_mappings[active_device.name]
                            except KeyError:
                                pass
                        for event in active_device.read():
                            if print_events:
                                print(event)
                            if event.type == EV_ABS or event.type == EV_REL:
                                controller.axes.axis_updated(event, prefix=prefix)
                            elif event.type == EV_KEY:
                                # Button event
                                if event.value == 1:
                                    # Button down
                                    controller.buttons.button_pressed(event.code, prefix=prefix)
                                elif event.value == 0:
                                    # Button up
                                    controller.buttons.button_released(event.code, prefix=prefix)
                except Exception as e:
                    self.stop(e)

        def stop(self, exception=None):

            for discovery in discoveries:
                discovery.controller.device_unique_name = None
                discovery.controller.exception = exception

            self.running = False

    polling_thread = SelectThread()

    # Force an update of the LED and battery system cache
    sys.scan_cache(force_update=True)

    for device in polling_thread.all_devices:
        device.grab()

    def unbind():
        polling_thread.stop()
        for dev in polling_thread.all_devices:
            try:
                dev.ungrab()
            except IOError:
                pass

    polling_thread.start()

    return unbind

Response: Bind a set of controllers to a set of InputDevice instances.


Instruction:
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) | math.floor(secs / 2)
    return (date_val << 16) | time_val

Response: Encode a mtime float as a 32 - bit FAT time


Instruction:
Create a Python 3 function for
overloading function callable with loop getter.

Response:
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."""


Instruction:
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 = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:
    """Overload: function callable, loop getter available."""

Response: Overload function callable loop getter available.


Instruction:
Can you create a Python 3 function that
overloads : No function.

Response:
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."""


Instruction:
Implement a function in Python 3 to
post function to ThreadPoolExecutor.

Response:
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,
) -> typing.Union[
    ThreadPooled,
    typing.Callable[..., "typing.Union[concurrent.futures.Future[typing.Any], typing.Awaitable[typing.Any]]"],
]:
    """Post function to ThreadPoolExecutor.

    :param func: function to wrap
    :type func: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]]
    :param loop_getter: Method to get event loop, if wrap in asyncio task
    :type loop_getter: typing.Union[
                           None,
                           typing.Callable[..., asyncio.AbstractEventLoop],
                           asyncio.AbstractEventLoop
                       ]
    :param loop_getter_need_context: Loop getter requires function context
    :type loop_getter_need_context: bool
    :return: ThreadPooled instance, if called as function or argumented decorator, else callable wrapper
    :rtype: typing.Union[ThreadPooled, typing.Callable[..., typing.Union[concurrent.futures.Future, typing.Awaitable]]]
    """
    if func is None:
        return ThreadPooled(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context)
    return ThreadPooled(  # type: ignore
        func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context
    )(func)


Instruction:
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
            cls.__executor.shutdown()

        cls.__executor = ThreadPoolExecutor(max_workers=max_workers)

Response: Create and configure the ThreadPoolExecutor.


Instruction:
How would you code a function in Python 3 to
return the ThreadPoolExecutor instance.

Response:
def executor(self) -> "ThreadPoolExecutor":
        """Executor instance.

        :rtype: ThreadPoolExecutor
        """
        if not isinstance(self.__executor, ThreadPoolExecutor) or self.__executor.is_shutdown:
            self.configure()
        return self.__executor


Instruction:
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.AbstractEventLoop], asyncio.AbstractEventLoop]
        """
        return self.__loop_getter

Response: Return the loop getter function for the given base namespace.


Instruction:
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: disable=not-callable
            return self.loop_getter()  # pylint: disable=not-callable
        return self.loop_getter

Response: Get event loop in decorator class.


Instruction:
Create a Python 3 function to
return True if the given hostname needs SSH.

Response:
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:
        return False
    local_hostname = _socket.gethostname()
    local_short_hostname = local_hostname.split('.')[0]
    if local_hostname == hostname or local_short_hostname == hostname:
        return False
    return True


Instruction:
Write a Python 3 function that can
try to determine the remote Python executable and return it.

Response:
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', 'python', 'python2.7']
    for executable in executables:
        conn.logger.debug('trying to determine remote python executable with %s' % executable)
        out, err, code = check(conn, ['which', executable])
        if code:
            conn.logger.warning('skipping %s, was not found in path' % executable)
        else:
            try:
                return out[0].strip()
            except IndexError:
                conn.logger.warning('could not parse stdout: %s' % out)

    # if all fails, we just return whatever the main connection had
    conn.logger.info('Falling back to using interpreter: %s' % conn.interpreter)
    return conn.interpreter


Instruction:
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(getpass.getuser())'
        )

        result = channel.receive()
        gw.exit()

        if result == 'root':
            return False
        self.logger.debug('connection detected need for sudo')
        return True

Response: Detects if the user is a sudo


Instruction:
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:
                self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger)
        else:
            self.remote_module = LegacyModuleExecute(self.gateway, module, self.logger)
        return self.remote_module

Response: Allows remote execution of a local module.


Instruction:
Implement a Python 3 function for
retrieving the matching backend class from a string.

Response:
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.backends.BaseConnection'>
    >>> get('non-existent', 'openshift')
    <class 'remoto.backends.openshift.OpenshiftConnection'>
    """
    mapping = {
        'ssh': ssh.SshConnection,
        'oc': openshift.OpenshiftConnection,
        'openshift': openshift.OpenshiftConnection,
        'kubernetes': kubernetes.KubernetesConnection,
        'k8s': kubernetes.KubernetesConnection,
        'local': local.LocalConnection,
        'popen': local.LocalConnection,
        'localhost': local.LocalConnection,
        'docker': docker.DockerConnection,
        'podman': podman.PodmanConnection,
    }
    if not name:
        # fallsback to just plain local/ssh
        name = 'ssh'

    name = name.strip().lower()
    connection_class = mapping.get(name)
    if not connection_class:
        logger.warning('no connection backend found for: "%s"' % name)
        if fallback:
            logger.info('falling back to "%s"' % fallback)
            # this assumes that ``fallback`` is a valid mapping name
            return mapping.get(fallback)
    return connection_class


Instruction:
Create a Python 3 function to
return configured CACHES dictionary from CACHE_URL

Response:
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


Instruction:
Can you create a Python 3 function that
parses a cache URL.

Response:
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 in
                       urlparse.parse_qs(query).items()])

    # Update with environment configuration.
    backend = BACKENDS.get(url.scheme)
    if not backend:
        raise Exception('Unknown backend: "{0}"'.format(url.scheme))

    config['BACKEND'] = BACKENDS[url.scheme]

    redis_options = {}
    if url.scheme == 'hiredis':
        redis_options['PARSER_CLASS'] = 'redis.connection.HiredisParser'

    # File based
    if not url.netloc:
        if url.scheme in ('memcached', 'pymemcached', 'djangopylibmc'):
            config['LOCATION'] = 'unix:' + path

        elif url.scheme in ('redis', 'hiredis'):
            match = re.match(r'.+?(?P<db>\d+)', path)
            if match:
                db = match.group('db')
                path = path[:path.rfind('/')]
            else:
                db = '0'
            config['LOCATION'] = 'unix:%s:%s' % (path, db)
        else:
            config['LOCATION'] = path
    # URL based
    else:
        # Handle multiple hosts
        config['LOCATION'] = ';'.join(url.netloc.split(','))

        if url.scheme in ('redis', 'hiredis'):
            if url.password:
                redis_options['PASSWORD'] = url.password
            # Specifying the database is optional, use db 0 if not specified.
            db = path[1:] or '0'
            port = url.port if url.port else 6379
            config['LOCATION'] = "redis://%s:%s/%s" % (url.hostname, port, db)

    if redis_options:
        config.setdefault('OPTIONS', {}).update(redis_options)

    if url.scheme == 'uwsgicache':
        config['LOCATION'] = config.get('LOCATION', 'default') or 'default'

    # Pop special options from cache_args
    # https://docs.djangoproject.com/en/1.10/topics/cache/#cache-arguments
    options = {}
    for key in ['MAX_ENTRIES', 'CULL_FREQUENCY']:
        val = cache_args.pop(key, None)
        if val is not None:
            options[key] = int(val)
    if options:
        config.setdefault('OPTIONS', {}).update(options)

    config.update(cache_args)

    return config


Instruction:
Can you implement a function in Python 3 that
returns True if memory has been written to False otherwise

Response:
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 command failed")


Instruction:
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 = False
    asvar = None
    message_context = None
    seen = set()
    invalid_context = {'as', 'noop'}

    while remaining:
        option = remaining.pop(0)
        if option in seen:
            raise TemplateSyntaxError(
                "The '%s' option was specified more than once." % option,
            )
        elif option == 'noop':
            noop = True
        elif option == 'context':
            try:
                value = remaining.pop(0)
            except IndexError:
                msg = "No argument provided to the '%s' tag for the context option." % bits[0]
                six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
            if value in invalid_context:
                raise TemplateSyntaxError(
                    "Invalid argument '%s' provided to the '%s' tag for the context option" % (value, bits[0]),
                )
            message_context = parser.compile_filter(value)
        elif option == 'as':
            try:
                value = remaining.pop(0)
            except IndexError:
                msg = "No argument provided to the '%s' tag for the as option." % bits[0]
                six.reraise(TemplateSyntaxError, TemplateSyntaxError(msg), sys.exc_info()[2])
            asvar = value
        else:
            raise TemplateSyntaxError(
                "Unknown argument for '%s' tag: '%s'. The only options "
                "available are 'noop', 'context' \"xxx\", and 'as VAR'." % (
                    bits[0], option,
                )
            )
        seen.add(option)

    if phrase_settings.PHRASE_ENABLED:
        return PhraseTranslateNode(message_string, noop, asvar, message_context)
    else:
        return TranslateNode(message_string, noop, asvar, message_context)

Response: Translate a string into a new language.


Instruction:
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:
    """Overload: no function."""

Response: A function that returns an async task.


Instruction:
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
    ] = asyncio.get_event_loop,
    loop_getter_need_context: bool = False,
) -> typing.Union[AsyncIOTask, typing.Callable[..., "asyncio.Task[typing.Any]"]]:
    """Wrap function in future and return.

    :param func: Function to wrap
    :type func: typing.Optional[typing.Callable[..., typing.Awaitable]]
    :param loop_getter: Method to get event loop, if wrap in asyncio task
    :type loop_getter: typing.Union[
                           typing.Callable[..., asyncio.AbstractEventLoop],
                           asyncio.AbstractEventLoop
                       ]
    :param loop_getter_need_context: Loop getter requires function context
    :type loop_getter_need_context: bool
    :return: AsyncIOTask instance, if called as function or argumented decorator, else callable wrapper
    :rtype: typing.Union[AsyncIOTask, typing.Callable[..., asyncio.Task]]
    """
    if func is None:
        return AsyncIOTask(func=func, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context)
    return AsyncIOTask(  # type: ignore
        func=None, loop_getter=loop_getter, loop_getter_need_context=loop_getter_need_context
    )(func)

Response: Decorator to wrap function in future and return.


Instruction:
Write a Python 3 function that can
get event loop in decorator class.

Response:
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-callable
            return self.loop_getter()  # pylint: disable=not-callable
        return self.loop_getter


Instruction:
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
        :type func: typing.Callable[..., typing.Awaitable]
        :return: wrapper, which will produce asyncio.Task on call with function called inside it
        :rtype: typing.Callable[..., asyncio.Task]
        """
        # noinspection PyMissingOrEmptyDocstring
        @functools.wraps(func)  # pylint: disable=missing-docstring
        def wrapper(*args, **kwargs):  # type: (typing.Any, typing.Any) -> asyncio.Task[typing.Any]
            loop = self.get_loop(*args, **kwargs)
            return loop.create_task(func(*args, **kwargs))

        return wrapper

Response:
This is a function decorator which returns a function which will produce asyncio. Task on call with function called inside it
Taxonomy.


Instruction:
Write a Python 3 script to
overload Call decorator without arguments.

Response:
def threaded(
    name: typing.Callable[..., typing.Any], daemon: bool = False, started: bool = False
) -> typing.Callable[..., threading.Thread]:
    """Overload: Call decorator without arguments."""


Instruction:
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 started: bool :return: Threaded instance, if called as function or argumented decorator, else callable wraper :rtype: typing.Union[Threaded, typing.Callable[..., threading.Thread]]

Response:
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.
                 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 started: bool
    :return: Threaded instance, if called as function or argumented decorator, else callable wraper
    :rtype: typing.Union[Threaded, typing.Callable[..., threading.Thread]]
    """
    if callable(name):
        func, name = (name, "Threaded: " + getattr(name, "__name__", str(hash(name))))
        return Threaded(name=name, daemon=daemon, started=started)(func)  # type: ignore
    return Threaded(name=name, daemon=daemon, started=started)


Instruction:
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.

        :param func: Wrapped function
        :type func: typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]
        :return: wrapped function
        :rtype: typing.Callable[..., threading.Thread]
        """
        prepared: typing.Callable[..., typing.Any] = self._await_if_required(func)
        name: typing.Optional[str] = self.name
        if name is None:
            name = "Threaded: " + getattr(func, "__name__", str(hash(func)))

        # noinspection PyMissingOrEmptyDocstring
        @functools.wraps(prepared)  # pylint: disable=missing-docstring
        def wrapper(*args, **kwargs):  # type: (typing.Any, typing.Any) -> threading.Thread
            thread = threading.Thread(target=prepared, name=name, args=args, kwargs=kwargs, daemon=self.daemon)
            if self.started:
                thread.start()
            return thread

        return wrapper

Response: This is a function decorator that returns a thread that will be started when the function is called.


Instruction:
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 an instance of asn1crypto.x509.Certificate or
                oscrypto.asymmetric.Certificate, not %s
                ''',
                _type_name(value)
            ))

        if is_oscrypto:
            value = value.asn1

        self._issuer = value

Response: Set the issuer of the object.


Instruction:
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)
            ))

        self._key_hash_algo = value

Response: Sets the key hash algorithm.


Instruction:
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)
            ))

        self._nonce = value

Response: Set the nonce of the object.


Instruction:
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 = set([
                'nonce',
                'acceptable_responses',
                'preferred_signature_algorithms',
                '1.3.6.1.5.5.7.48.1.2',
                '1.3.6.1.5.5.7.48.1.4',
                '1.3.6.1.5.5.7.48.1.8'
            ])

            if name in request_extension_oids:
                name = ocsp.RequestExtensionId(name)

            elif name in tbs_request_extension_oids:
                name = ocsp.TBSRequestExtensionId(name)

            else:
                raise ValueError(_pretty_message(
                    '''
                    name must be a unicode string from
                    asn1crypto.ocsp.TBSRequestExtensionId or
                    asn1crypto.ocsp.RequestExtensionId, not %s
                    ''',
                    repr(name)
                ))

        if isinstance(name, ocsp.RequestExtensionId):
            extension = ocsp.RequestExtension({'extn_id': name})

        elif isinstance(name, ocsp.TBSRequestExtensionId):
            extension = ocsp.TBSRequestExtension({'extn_id': name})

        else:
            raise TypeError(_pretty_message(
                '''
                name must be a unicode string or an instance of
                asn1crypto.ocsp.TBSRequestExtensionId or
                asn1crypto.ocsp.RequestExtensionId, not %s
                ''',
                _type_name(name)
            ))

        # We use native here to convert OIDs to meaningful names
        name = extension['extn_id'].native
        spec = extension.spec('extn_value')

        if not isinstance(value, spec) and value is not None:
            raise TypeError(_pretty_message(
                '''
                value must be an instance of %s, not %s
                ''',
                _type_name(spec),
                _type_name(value)
            ))

        if isinstance(extension, ocsp.TBSRequestExtension):
            extn_dict = self._tbs_request_extensions
        else:
            extn_dict = self._request_extensions

        if value is None:
            if name in extn_dict:
                del extn_dict[name]
        else:
            extn_dict[name] = value

Response: Sets the value for an extension using a fully constructed ASN. 1 Value object.


Instruction:
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
            }

        tbs_request_extensions = []
        request_extensions = []
        has_nonce = False

        for name, value in self._tbs_request_extensions.items():
            if name == 'nonce':
                has_nonce = True
            tbs_request_extensions.append(_make_extension(name, value))
        if self._nonce and not has_nonce:
            tbs_request_extensions.append(
                _make_extension('nonce', util.rand_bytes(16))
            )

        if not tbs_request_extensions:
            tbs_request_extensions = None

        for name, value in self._request_extensions.items():
            request_extensions.append(_make_extension(name, value))

        if not request_extensions:
            request_extensions = None

        tbs_request = ocsp.TBSRequest({
            'request_list': [
                {
                    'req_cert': {
                        'hash_algorithm': {
                            'algorithm': self._key_hash_algo
                        },
                        'issuer_name_hash': getattr(self._certificate.issuer, self._key_hash_algo),
                        'issuer_key_hash': getattr(self._issuer.public_key, self._key_hash_algo),
                        'serial_number': self._certificate.serial_number,
                    },
                    'single_request_extensions': request_extensions
                }
            ],
            'request_extensions': tbs_request_extensions
        })
        signature = None

        if requestor_private_key or requestor_certificate or other_certificates:
            is_oscrypto = isinstance(requestor_private_key, asymmetric.PrivateKey)
            if not isinstance(requestor_private_key, keys.PrivateKeyInfo) and not is_oscrypto:
                raise TypeError(_pretty_message(
                    '''
                    requestor_private_key must be an instance of
                    asn1crypto.keys.PrivateKeyInfo or
                    oscrypto.asymmetric.PrivateKey, not %s
                    ''',
                    _type_name(requestor_private_key)
                ))

            cert_is_oscrypto = isinstance(requestor_certificate, asymmetric.Certificate)
            if not isinstance(requestor_certificate, x509.Certificate) and not cert_is_oscrypto:
                raise TypeError(_pretty_message(
                    '''
                    requestor_certificate must be an instance of
                    asn1crypto.x509.Certificate or
                    oscrypto.asymmetric.Certificate, not %s
                    ''',
                    _type_name(requestor_certificate)
                ))

            if other_certificates is not None and not isinstance(other_certificates, list):
                raise TypeError(_pretty_message(
                    '''
                    other_certificates must be a list of
                    asn1crypto.x509.Certificate or
                    oscrypto.asymmetric.Certificate objects, not %s
                    ''',
                    _type_name(other_certificates)
                ))

            if cert_is_oscrypto:
                requestor_certificate = requestor_certificate.asn1

            tbs_request['requestor_name'] = x509.GeneralName(
                name='directory_name',
                value=requestor_certificate.subject
            )

            certificates = [requestor_certificate]

            for other_certificate in other_certificates:
                other_cert_is_oscrypto = isinstance(other_certificate, asymmetric.Certificate)
                if not isinstance(other_certificate, x509.Certificate) and not other_cert_is_oscrypto:
                    raise TypeError(_pretty_message(
                        '''
                        other_certificate must be an instance of
                        asn1crypto.x509.Certificate or
                        oscrypto.asymmetric.Certificate, not %s
                        ''',
                        _type_name(other_certificate)
                    ))
                if other_cert_is_oscrypto:
                    other_certificate = other_certificate.asn1
                certificates.append(other_certificate)

            signature_algo = requestor_private_key.algorithm
            if signature_algo == 'ec':
                signature_algo = 'ecdsa'

            signature_algorithm_id = '%s_%s' % (self._hash_algo, signature_algo)

            if requestor_private_key.algorithm == 'rsa':
                sign_func = asymmetric.rsa_pkcs1v15_sign
            elif requestor_private_key.algorithm == 'dsa':
                sign_func = asymmetric.dsa_sign
            elif requestor_private_key.algorithm == 'ec':
                sign_func = asymmetric.ecdsa_sign

            if not is_oscrypto:
                requestor_private_key = asymmetric.load_private_key(requestor_private_key)
            signature_bytes = sign_func(requestor_private_key, tbs_request.dump(), self._hash_algo)

            signature = ocsp.Signature({
                'signature_algorithm': {'algorithm': signature_algorithm_id},
                'signature': signature_bytes,
                'certs': certificates
            })

        return ocsp.OCSPRequest({
            'tbs_request': tbs_request,
            'optional_signature': signature
        })

Response: Builds the OCSP request object.


Instruction:
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
                ''',
                _type_name(value)
            ))

        valid_response_statuses = set([
            'successful',
            'malformed_request',
            'internal_error',
            'try_later',
            'sign_required',
            'unauthorized'
        ])
        if value not in valid_response_statuses:
            raise ValueError(_pretty_message(
                '''
                response_status must be one of "successful",
                "malformed_request", "internal_error", "try_later",
                "sign_required", "unauthorized", not %s
                ''',
                repr(value)
            ))

        self._response_status = value

Response: Sets the response status of the OCSP response.


Instruction:
How would you implement a function in Python 3 that
sets the certificate of the response.

Response:
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 not isinstance(value, x509.Certificate):
                raise TypeError(_pretty_message(
                    '''
                    certificate must be an instance of asn1crypto.x509.Certificate
                    or oscrypto.asymmetric.Certificate, not %s
                    ''',
                    _type_name(value)
                ))

            if is_oscrypto:
                value = value.asn1

        self._certificate = value


Instruction:
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
                    ''',
                    _type_name(value)
                ))

            valid_certificate_statuses = set([
                'good',
                'revoked',
                'key_compromise',
                'ca_compromise',
                'affiliation_changed',
                'superseded',
                'cessation_of_operation',
                'certificate_hold',
                'remove_from_crl',
                'privilege_withdrawn',
                'unknown',
            ])
            if value not in valid_certificate_statuses:
                raise ValueError(_pretty_message(
                    '''
                    certificate_status must be one of "good", "revoked", "key_compromise",
                    "ca_compromise", "affiliation_changed", "superseded",
                    "cessation_of_operation", "certificate_hold", "remove_from_crl",
                    "privilege_withdrawn", "unknown" not %s
                    ''',
                    repr(value)
                ))

        self._certificate_status = value

Response: Sets the certificate status of the certificate.


Instruction:
How would you code a function in Python 3 to
set the revocation date of the certificate.

Response:
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(
                '''
                revocation_date must be an instance of datetime.datetime, not %s
                ''',
                _type_name(value)
            ))

        self._revocation_date = value


Instruction:
Create a Python 3 function for
setting the certificate issuer of the OCSP response.

Response:
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 value is not None:
            is_oscrypto = isinstance(value, asymmetric.Certificate)
            if not is_oscrypto and not isinstance(value, x509.Certificate):
                raise TypeError(_pretty_message(
                    '''
                    certificate_issuer must be an instance of
                    asn1crypto.x509.Certificate or
                    oscrypto.asymmetric.Certificate, not %s
                    ''',
                    _type_name(value)
                ))

            if is_oscrypto:
                value = value.asn1

        self._certificate_issuer = value


Instruction:
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
                ''',
                _type_name(value)
            ))

        self._this_update = value

Response: Set the _this_update field of the object.


Instruction:
Write a Python 3 script to
set the next update date for this entry.

Response:
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):
            raise TypeError(_pretty_message(
                '''
                next_update must be an instance of datetime.datetime, not %s
                ''',
                _type_name(value)
            ))

        self._next_update = value


Instruction:
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'
            ])

            single_response_extension_oids = set([
                'crl',
                'archive_cutoff',
                'crl_reason',
                'invalidity_date',
                'certificate_issuer',
                '1.3.6.1.5.5.7.48.1.3',
                '1.3.6.1.5.5.7.48.1.6',
                '2.5.29.21',
                '2.5.29.24',
                '2.5.29.29'
            ])

            if name in response_data_extension_oids:
                name = ocsp.ResponseDataExtensionId(name)

            elif name in single_response_extension_oids:
                name = ocsp.SingleResponseExtensionId(name)

            else:
                raise ValueError(_pretty_message(
                    '''
                    name must be a unicode string from
                    asn1crypto.ocsp.ResponseDataExtensionId or
                    asn1crypto.ocsp.SingleResponseExtensionId, not %s
                    ''',
                    repr(name)
                ))

        if isinstance(name, ocsp.ResponseDataExtensionId):
            extension = ocsp.ResponseDataExtension({'extn_id': name})

        elif isinstance(name, ocsp.SingleResponseExtensionId):
            extension = ocsp.SingleResponseExtension({'extn_id': name})

        else:
            raise TypeError(_pretty_message(
                '''
                name must be a unicode string or an instance of
                asn1crypto.ocsp.SingleResponseExtensionId or
                asn1crypto.ocsp.ResponseDataExtensionId, not %s
                ''',
                _type_name(name)
            ))

        # We use native here to convert OIDs to meaningful names
        name = extension['extn_id'].native
        spec = extension.spec('extn_value')

        if name == 'nonce':
            raise ValueError(_pretty_message(
                '''
                The nonce value should be set via the .nonce attribute, not the
                .set_extension() method
                '''
            ))

        if name == 'crl_reason':
            raise ValueError(_pretty_message(
                '''
                The crl_reason value should be set via the certificate_status
                parameter of the OCSPResponseBuilder() constructor, not the
                .set_extension() method
                '''
            ))

        if name == 'certificate_issuer':
            raise ValueError(_pretty_message(
                '''
                The certificate_issuer value should be set via the
                .certificate_issuer attribute, not the .set_extension() method
                '''
            ))

        if not isinstance(value, spec) and value is not None:
            raise TypeError(_pretty_message(
                '''
                value must be an instance of %s, not %s
                ''',
                _type_name(spec),
                _type_name(value)
            ))

        if isinstance(extension, ocsp.ResponseDataExtension):
            extn_dict = self._response_data_extensions
        else:
            extn_dict = self._single_response_extensions

        if value is None:
            if name in extn_dict:
                del extn_dict[name]
        else:
            extn_dict[name] = value

Response: Sets the value for an extension using a fully constructed ASN. 1 Value object.


Instruction:
Create a Python 3 function for
building the OCSP response object.

Response:
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".

        :param responder_private_key:
            An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey
            object for the private key to sign the response with

        :param responder_certificate:
            An asn1crypto.x509.Certificate or oscrypto.asymmetric.Certificate
            object of the certificate associated with the private key

        :return:
            An asn1crypto.ocsp.OCSPResponse object of the response
        """

        if self._response_status != 'successful':
            return ocsp.OCSPResponse({
                'response_status': self._response_status
            })

        is_oscrypto = isinstance(responder_private_key, asymmetric.PrivateKey)
        if not isinstance(responder_private_key, keys.PrivateKeyInfo) and not is_oscrypto:
            raise TypeError(_pretty_message(
                '''
                responder_private_key must be an instance of
                asn1crypto.keys.PrivateKeyInfo or
                oscrypto.asymmetric.PrivateKey, not %s
                ''',
                _type_name(responder_private_key)
            ))

        cert_is_oscrypto = isinstance(responder_certificate, asymmetric.Certificate)
        if not isinstance(responder_certificate, x509.Certificate) and not cert_is_oscrypto:
            raise TypeError(_pretty_message(
                '''
                responder_certificate must be an instance of
                asn1crypto.x509.Certificate or
                oscrypto.asymmetric.Certificate, not %s
                ''',
                _type_name(responder_certificate)
            ))

        if cert_is_oscrypto:
            responder_certificate = responder_certificate.asn1

        if self._certificate is None:
            raise ValueError(_pretty_message(
                '''
                certificate must be set if the response_status is
                "successful"
                '''
            ))
        if self._certificate_status is None:
            raise ValueError(_pretty_message(
                '''
                certificate_status must be set if the response_status is
                "successful"
                '''
            ))

        def _make_extension(name, value):
            return {
                'extn_id': name,
                'critical': False,
                'extn_value': value
            }

        response_data_extensions = []
        single_response_extensions = []

        for name, value in self._response_data_extensions.items():
            response_data_extensions.append(_make_extension(name, value))
        if self._nonce:
            response_data_extensions.append(
                _make_extension('nonce', self._nonce)
            )

        if not response_data_extensions:
            response_data_extensions = None

        for name, value in self._single_response_extensions.items():
            single_response_extensions.append(_make_extension(name, value))

        if self._certificate_issuer:
            single_response_extensions.append(
                _make_extension(
                    'certificate_issuer',
                    [
                        x509.GeneralName(
                            name='directory_name',
                            value=self._certificate_issuer.subject
                        )
                    ]
                )
            )

        if not single_response_extensions:
            single_response_extensions = None

        responder_key_hash = getattr(responder_certificate.public_key, self._key_hash_algo)

        if self._certificate_status == 'good':
            cert_status = ocsp.CertStatus(
                name='good',
                value=core.Null()
            )
        elif self._certificate_status == 'unknown':
            cert_status = ocsp.CertStatus(
                name='unknown',
                value=core.Null()
            )
        else:
            status = self._certificate_status
            reason = status if status != 'revoked' else 'unspecified'
            cert_status = ocsp.CertStatus(
                name='revoked',
                value={
                    'revocation_time': self._revocation_date,
                    'revocation_reason': reason,
                }
            )

        issuer = self._certificate_issuer if self._certificate_issuer else responder_certificate
        if issuer.subject != self._certificate.issuer:
            raise ValueError(_pretty_message(
                '''
                responder_certificate does not appear to be the issuer for
                the certificate. Perhaps set the .certificate_issuer attribute?
                '''
            ))

        produced_at = datetime.now(timezone.utc)

        if self._this_update is None:
            self._this_update = produced_at

        if self._next_update is None:
            self._next_update = self._this_update + timedelta(days=7)

        response_data = ocsp.ResponseData({
            'responder_id': ocsp.ResponderId(name='by_key', value=responder_key_hash),
            'produced_at': produced_at,
            'responses': [
                {
                    'cert_id': {
                        'hash_algorithm': {
                            'algorithm': self._key_hash_algo
                        },
                        'issuer_name_hash': getattr(self._certificate.issuer, self._key_hash_algo),
                        'issuer_key_hash': getattr(issuer.public_key, self._key_hash_algo),
                        'serial_number': self._certificate.serial_number,
                    },
                    'cert_status': cert_status,
                    'this_update': self._this_update,
                    'next_update': self._next_update,
                    'single_extensions': single_response_extensions
                }
            ],
            'response_extensions': response_data_extensions
        })

        signature_algo = responder_private_key.algorithm
        if signature_algo == 'ec':
            signature_algo = 'ecdsa'

        signature_algorithm_id = '%s_%s' % (self._hash_algo, signature_algo)

        if responder_private_key.algorithm == 'rsa':
            sign_func = asymmetric.rsa_pkcs1v15_sign
        elif responder_private_key.algorithm == 'dsa':
            sign_func = asymmetric.dsa_sign
        elif responder_private_key.algorithm == 'ec':
            sign_func = asymmetric.ecdsa_sign

        if not is_oscrypto:
            responder_private_key = asymmetric.load_private_key(responder_private_key)
        signature_bytes = sign_func(responder_private_key, response_data.dump(), self._hash_algo)

        certs = None
        if self._certificate_issuer:
            certs = [responder_certificate]

        return ocsp.OCSPResponse({
            'response_status': self._response_status,
            'response_bytes': {
                'response_type': 'basic_ocsp_response',
                'response': {
                    'tbs_response_data': response_data,
                    'signature_algorithm': {'algorithm': signature_algorithm_id},
                    'signature': signature_bytes,
                    'certs': certs
                }
            }
        })


Instruction:
Create a Python 3 function to
build a OpenID request from an Authorization request.

Response:
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 KeyJar instance
    :param issuer: Who is signing this JSON Web Token
    :param request_object_signing_alg: Which signing algorithm to use
    :param recv: The intended receiver of the request
    :return: JWT encoded OpenID request
    """

    _jwt = JWT(key_jar=keys, iss=issuer, sign_alg=request_object_signing_alg)
    return _jwt.pack(arq.to_dict(), owner=issuer, recv=recv)


Instruction:
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:
                args[arg] = kwargs[arg]
            except KeyError:
                pass

        if "opponent_id" not in kwargs:
            args["opponent_id"] = self["client_id"]

        if "request" in self:
            if isinstance(self["request"], str):
                # Try to decode the JWT, checks the signature
                oidr = OpenIDRequest().from_jwt(str(self["request"]), **args)

                # check if something is change in the original message
                for key, val in oidr.items():
                    if key in self:
                        if self[key] != val:
                            # log but otherwise ignore
                            logger.warning('{} != {}'.format(self[key], val))

                # remove all claims
                _keys = list(self.keys())
                for key in _keys:
                    if key not in oidr:
                        del self[key]

                self.update(oidr)

                # replace the JWT with the parsed and verified instance
                self[verified_claim_name("request")] = oidr

        if "id_token_hint" in self:
            if isinstance(self["id_token_hint"], str):
                idt = IdToken().from_jwt(str(self["id_token_hint"]), **args)
                self["verified_id_token_hint"] = idt

        if "response_type" not in self:
            raise MissingRequiredAttribute("response_type missing", self)

        _rt = self["response_type"]
        if "id_token" in _rt:
            if "nonce" not in self:
                raise MissingRequiredAttribute("Nonce missing", self)
            else:
                try:
                    if self['nonce'] != kwargs['nonce']:
                        raise ValueError(
                            'Nonce in id_token not matching nonce in authz '
                            'request')
                except KeyError:
                    pass

        if "openid" not in self.get("scope", []):
            raise MissingRequiredValue("openid not in scope", self)

        if "offline_access" in self.get("scope", []):
            if "prompt" not in self or "consent" not in self["prompt"]:
                raise MissingRequiredValue("consent in prompt", self)

        if "prompt" in self:
            if "none" in self["prompt"] and len(self["prompt"]) > 1:
                raise InvalidRequest("prompt none combined with other value",
                                     self)

        return True

Response: Verify that the request and response are valid.


Instruction:
Write a Python 3 function that can
verify that the message is OK.

Response:
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).verify(**kwargs)

        has_reg_uri = "registration_client_uri" in self
        has_reg_at = "registration_access_token" in self
        if has_reg_uri != has_reg_at:
            raise VerificationError((
                "Only one of registration_client_uri"
                " and registration_access_token present"), self)

        return True


Instruction:
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 hours:
    :param weeks:
    :param time_format:
    :return: Formatet string
    """
    if not time_format:
        time_format = TIME_FORMAT

    return time_in_a_while(days, seconds, microseconds, milliseconds,
                           minutes, hours, weeks).strftime(time_format)

Response: Return a string representation of the current time in a while.


Instruction:
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

Response: True if point datetime specification is before now


Instruction:
Can you implement a function in Python 3 that
trues if after is later or equal to that

Response:
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):
        before = time.gmtime(before)

    return after >= before


Instruction:
How would you implement a function in Python 3 that
returns the number of seconds since epoch a while from now.

Response:
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:
    :param weeks:
    :return: Seconds since epoch (1970-01-01)
    """

    dt = time_in_a_while(days, seconds, microseconds, milliseconds, minutes,
                         hours, weeks)
    return int((dt - datetime(1970, 1, 1)).total_seconds())


Instruction:
Implement a function in Python 3 to
set the default values of the parameters.

Response:
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


Instruction:
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("%s" % attribute,
                                                   "%s" % self)

        params = []

        for key, val in self._dict.items():
            try:
                (_, req, _ser, _, null_allowed) = _spec[key]
            except KeyError:  # extra attribute
                try:
                    _key, lang = key.split("#")
                    (_, req, _ser, _deser, null_allowed) = _spec[_key]
                except (ValueError, KeyError):
                    try:
                        (_, req, _ser, _, null_allowed) = _spec['*']
                    except KeyError:
                        _ser = None
                        null_allowed = False

            if val is None and null_allowed is False:
                continue
            elif isinstance(val, str):
                # Should I allow parameters with "" as value ???
                params.append((key, val.encode("utf-8")))
            elif isinstance(val, list):
                if _ser:
                    params.append((key, str(_ser(val, sformat="urlencoded",
                                                 lev=lev))))
                else:
                    for item in val:
                        params.append((key, str(item).encode('utf-8')))
            elif isinstance(val, Message):
                try:
                    _val = json.dumps(_ser(val, sformat="dict", lev=lev + 1))
                    params.append((key, _val))
                except TypeError:
                    params.append((key, val))
            elif val is None:
                params.append((key, val))
            else:
                try:
                    params.append((key, _ser(val, lev=lev)))
                except Exception:
                    params.append((key, str(val)))

        try:
            return urlencode(params)
        except UnicodeEncodeError:
            _val = []
            for k, v in params:
                try:
                    _val.append((k, v.encode("utf-8")))
                except TypeError:
                    _val.append((k, v))
            return urlencode(_val)

Response: Creates a string using the application / x - www - form - urlencoded format of the resource.


Instruction:
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)

Response: Serialize this instance to another representation.


Instruction:
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:
            return func(info, **kwargs)

Response: Deserialize from an external representation to an internal representation.


Instruction:
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(urlencoded, str):
            pass
        elif isinstance(urlencoded, list):
            urlencoded = urlencoded[0]

        _spec = self.c_param

        _info = parse_qs(urlencoded)
        if len(urlencoded) and _info == {}:
            raise FormatError('Wrong format')

        for key, val in _info.items():
            try:
                (typ, _, _, _deser, null_allowed) = _spec[key]
            except KeyError:
                try:
                    _key, lang = key.split("#")
                    (typ, _, _, _deser, null_allowed) = _spec[_key]
                except (ValueError, KeyError):
                    try:
                        (typ, _, _, _deser, null_allowed) = _spec['*']
                    except KeyError:
                        if len(val) == 1:
                            val = val[0]

                        self._dict[key] = val
                        continue

            if isinstance(typ, list):
                if _deser:
                    self._dict[key] = _deser(val[0], "urlencoded")
                else:
                    self._dict[key] = val
            else:  # must be single value
                if len(val) == 1:
                    if _deser:
                        self._dict[key] = _deser(val[0], "urlencoded")
                    elif isinstance(val[0], typ):
                        self._dict[key] = val[0]
                    else:
                        self._dict[key] = val[0]
                else:
                    raise TooManyValues('{}'.format(key))

        return self

Response: This method creates a new instance of the class instance from a urlencoded string.


Instruction:
Write a Python 3 script for
returning a dictionary representation of the class Taxonomy.

Response:
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(key)]
            except KeyError:
                try:
                    _key, lang = key.split("#")
                    (_, req, _ser, _, null_allowed) = _spec[_key]
                except (ValueError, KeyError):
                    try:
                        (_, req, _ser, _, null_allowed) = _spec['*']
                    except KeyError:
                        _ser = None

            if _ser:
                val = _ser(val, "dict", lev)

            if isinstance(val, Message):
                _res[key] = val.to_dict(lev + 1)
            elif isinstance(val, list) and isinstance(
                    next(iter(val or []), None), Message):
                _res[key] = [v.to_dict(lev) for v in val]
            else:
                _res[key] = val

        return _res


Instruction:
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

Response:
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 dictionary.items():
            # Earlier versions of python don't like unicode strings as
            # variable names
            if val == "" or val == [""]:
                continue

            skey = str(key)
            try:
                (vtyp, req, _, _deser, null_allowed) = _spec[key]
            except KeyError:
                # might be a parameter with a lang tag
                try:
                    _key, lang = skey.split("#")
                except ValueError:
                    try:
                        (vtyp, _, _, _deser, null_allowed) = _spec['*']
                        if val is None:
                            self._dict[key] = val
                            continue
                    except KeyError:
                        self._dict[key] = val
                        continue
                else:
                    try:
                        (vtyp, req, _, _deser, null_allowed) = _spec[_key]
                    except KeyError:
                        try:
                            (vtyp, _, _, _deser, null_allowed) = _spec['*']
                            if val is None:
                                self._dict[key] = val
                                continue
                        except KeyError:
                            self._dict[key] = val
                            continue

            self._add_value(skey, vtyp, key, val, _deser, null_allowed)
        return self


Instruction:
Write a Python 3 script for
adding a value to the instance.

Response:
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: original representation of the key
        :param val: The value to add
        :param _deser: A deserializer for this value type
        :param null_allowed: Whether null is an allowed value for this key
        """

        if isinstance(val, list):
            if (len(val) == 0 or val[0] is None) and null_allowed is False:
                return

        if isinstance(vtyp, tuple):
            vtyp = vtyp[0]

        if isinstance(vtyp, list):
            vtype = vtyp[0]
            if isinstance(val, vtype):
                if issubclass(vtype, Message):
                    self._dict[skey] = [val]
                elif _deser:
                    try:
                        self._dict[skey] = _deser(val, sformat="urlencoded")
                    except Exception as exc:
                        raise DecodeError(ERRTXT % (key, exc))
                else:
                    setattr(self, skey, [val])
            elif isinstance(val, list):
                if _deser:
                    try:
                        val = _deser(val, sformat="dict")
                    except Exception as exc:
                        raise DecodeError(ERRTXT % (key, exc))

                if issubclass(vtype, Message):
                    try:
                        _val = []
                        for v in val:
                            _val.append(vtype(**dict([(str(x), y) for x, y
                                                      in v.items()])))
                        val = _val
                    except Exception as exc:
                        raise DecodeError(ERRTXT % (key, exc))
                else:
                    for v in val:
                        if not isinstance(v, vtype):
                            raise DecodeError(
                                ERRTXT % (key, "type != %s (%s)" % (
                                    vtype, type(v))))

                self._dict[skey] = val
            elif isinstance(val, dict):
                try:
                    val = _deser(val, sformat="dict")
                except Exception as exc:
                    raise DecodeError(ERRTXT % (key, exc))
                else:
                    self._dict[skey] = val
            else:
                raise DecodeError(ERRTXT % (key, "type != %s" % vtype))
        else:
            if val is None:
                self._dict[skey] = None
            elif isinstance(val, bool):
                if vtyp is bool:
                    self._dict[skey] = val
                else:
                    raise ValueError(
                        '"{}", wrong type of value for "{}"'.format(val, skey))
            elif isinstance(val, vtyp):  # Not necessary to do anything
                self._dict[skey] = val
            else:
                if _deser:
                    try:
                        val = _deser(val, sformat="dict")
                    except Exception as exc:
                        raise DecodeError(ERRTXT % (key, exc))
                    else:
                        # if isinstance(val, str):
                        #     self._dict[skey] = val
                        # elif isinstance(val, list):
                        #     if len(val) == 1:
                        #         self._dict[skey] = val[0]
                        #     elif not len(val):
                        #         pass
                        #     else:
                        #         raise TooManyValues(key)
                        # else:
                        self._dict[skey] = val
                elif vtyp is int:
                    try:
                        self._dict[skey] = int(val)
                    except (ValueError, TypeError):
                        raise ValueError(
                            '"{}", wrong type of value for "{}"'.format(val,
                                                                        skey))
                elif vtyp is bool:
                    raise ValueError(
                        '"{}", wrong type of value for "{}"'.format(val, skey))
                elif vtyp != type(val):
                    if vtyp == Message:
                        if type(val) == dict or isinstance(val, str):
                            self._dict[skey] = val
                        else:
                            raise ValueError(
                                '"{}", wrong type of value for "{}"'.format(
                                    val, skey))
                    else:
                        raise ValueError(
                            '"{}", wrong type of value for "{}"'.format(val,
                                                                        skey))


Instruction:
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)

Response: Serialize the content of this object into a JSON string.


Instruction:
Implement a Python 3 function for
converting from a JSON string to an instance of this class.

Response:
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 instantiated instance
        """
        _dict = json.loads(txt)
        return self.from_dict(_dict)


Instruction:
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)

Response: Create a signed JWT representation of the class instance


Instruction:
Implement a function in Python 3 to
give a signed and or encrypted JWT create a new instance of the class instance.

Response:
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 of the JWT
        :param verify: Whether the signature should be verified or not
        :param keyjar: A KeyJar that might contain the necessary key.
        :param kwargs: Extra key word arguments
        :return: A class instance
        """

        algarg = {}
        if 'encalg' in kwargs:
            algarg['alg'] = kwargs['encalg']
        if 'encenc' in kwargs:
            algarg['enc'] = kwargs['encenc']
        _decryptor = jwe_factory(txt, **algarg)

        if _decryptor:
            logger.debug("JWE headers: {}".format(_decryptor.jwt.headers))

            dkeys = keyjar.get_decrypt_key(owner="")

            logger.debug('Decrypt class: {}'.format(_decryptor.__class__))
            _res = _decryptor.decrypt(txt, dkeys)
            logger.debug('decrypted message:{}'.format(_res))
            if isinstance(_res, tuple):
                txt = as_unicode(_res[0])
            elif isinstance(_res, list) and len(_res) == 2:
                txt = as_unicode(_res[0])
            else:
                txt = as_unicode(_res)
            self.jwe_header = _decryptor.jwt.headers

        try:
            _verifier = jws_factory(txt, alg=kwargs['sigalg'])
        except:
            _verifier = jws_factory(txt)

        if _verifier:
            try:
                _jwt = _verifier.jwt
                jso = _jwt.payload()
                _header = _jwt.headers

                key = []

                # if "sender" in kwargs:
                #     key.extend(keyjar.get_verify_key(owner=kwargs["sender"]))

                logger.debug("Raw JSON: {}".format(jso))
                logger.debug("JWS header: {}".format(_header))
                if _header["alg"] == "none":
                    pass
                elif verify:
                    if keyjar:
                        key.extend(keyjar.get_jwt_verify_keys(_jwt, **kwargs))

                    if "alg" in _header and _header["alg"] != "none":
                        if not key:
                            raise MissingSigningKey(
                                "alg=%s" % _header["alg"])

                    logger.debug("Found signing key.")
                    try:
                        _verifier.verify_compact(txt, key)
                    except NoSuitableSigningKeys:
                        if keyjar:
                            update_keyjar(keyjar)
                            key = keyjar.get_jwt_verify_keys(_jwt, **kwargs)
                            _verifier.verify_compact(txt, key)
            except Exception:
                raise
            else:
                self.jws_header = _jwt.headers
        else:
            jso = json.loads(txt)

        self.jwt = txt
        return self.from_dict(jso)


Instruction:
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.

Response:
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, (typ, required, _, _, na)) in _spec.items():
            if attribute == "*":
                continue

            try:
                val = self._dict[attribute]
            except KeyError:
                if required:
                    raise MissingRequiredAttribute("%s" % attribute)
                continue
            else:
                if typ == bool:
                    pass
                elif not val:
                    if required:
                        raise MissingRequiredAttribute("%s" % attribute)
                    continue

            try:
                _allowed_val = _allowed[attribute]
            except KeyError:
                pass
            else:
                if not self._type_check(typ, _allowed_val, val, na):
                    raise NotAllowedValue(val)

        return True


Instruction:
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) :return: The extended URL

Response:
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 be placed in a
            fragment (True) or in a query part (False)
        :return: The extended URL
        """
        _l = as_unicode(location)
        _qp = as_unicode(self.to_urlencoded())
        if fragment_enc:
            return "%s#%s" % (_l, _qp)
        else:
            if "?" in location:
                return "%s&%s" % (_l, _qp)
            else:
                return "%s?%s" % (_l, _qp)


Instruction:
Write a Python 3 function for
returning the extra parameters that this instance is not listed in the c_params specification.

Response:
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) for key, val in
                     self._dict.items() if key not in self.c_param])


Instruction:
Can you create a Python 3 function that
updates the information in this instance.

Response:
def update(self, item, **kwargs):
        """
        Update the information in this instance.

        :param item: a dictionary or a Message instance
        """
        if isinstance(item, dict):
            self._dict.update(item)
        elif isinstance(item, Message):
            for key, val in item.items():
                self._dict[key] = val
        else:
            raise ValueError("Can't update message using: '%s'" % (item,))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def to_jwe(self, keys, enc, alg, lev=0):

        _jwe = JWE(self.to_json(lev), alg=alg, enc=enc)
        return _jwe.encrypt(keys)

Response: This method will take the information in this instance and then encrypt it with the given keys.


Instruction:
Can you generate the documentation for the following Python 3 function
def from_jwe(self, msg, keys):

        jwe = JWE()
        _res = jwe.decrypt(msg, keys)
        return self.from_json(_res.decode())

Response:
Decrypt an encrypted JWT and load the JSON object that was the body
            of the JWT into this object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def weed(self):
        _ext = [k for k in self._dict.keys() if k not in self.c_param]
        for k in _ext:
            del self._dict[k]

Response: Remove all key value pairs that are not standard


Instruction:
Write a Python 3 script for
removing parameters that have no value.

Response:
def rm_blanks(self):
        """
        Get rid of parameters that has no value.
        """
        _blanks = [k for k in self._dict.keys() if not self._dict[k]]
        for key in _blanks:
            del self._dict[key]


Instruction:
Can you create a Python 3 function that
cleans up the path specification so it looks like something I could use.

Response:
def proper_path(path):
    """
    Clean up the path specification so it looks like something I could use.
    "./" <path> "/"
    """
    if path.startswith("./"):
        pass
    elif path.startswith("/"):
        path = ".%s" % path
    elif path.startswith("."):
        while path.startswith("."):
            path = path[1:]
        if path.startswith("/"):
            path = ".%s" % path
    else:
        path = "./%s" % path

    if not path.endswith("/"):
        path += "/"

    return path


Instruction:
Can you generate the documentation for the following Python 3 function
def ansi(color, text):
    code = COLOR_CODES[color]
    return '\033[1;{0}m{1}{2}'.format(code, text, RESET_TERM)

Response: Wrap text in an ansi escape sequence


Instruction:
Explain what the following Python 3 code does
def require_flush(fun):

    @wraps(fun)
    def ensure_flushed(service, *args, **kwargs):
        if service.app_state.needs_db_flush:
            session = db.session()
            if not session._flushing and any(
                isinstance(m, (RoleAssignment, SecurityAudit))
                for models in (session.new, session.dirty, session.deleted)
                for m in models
            ):
                session.flush()
            service.app_state.needs_db_flush = False

        return fun(service, *args, **kwargs)

    return ensure_flushed

Response:
Decorator for methods that need to query security.
    It ensures all security related operations are flushed to DB.


Instruction:
Write a Python 3 function that can
query for a : class:`PermissionAssignment` using the given session and permission role and object.

Response:
def query_pa_no_flush(session, permission, role, obj):
    """Query for a :class:`PermissionAssignment` using `session` without any
    `flush()`.

    It works by looking in session `new`, `dirty` and `deleted`, and issuing a
    query with no autoflush.

    .. note::

        This function is used by `add_permission` and `delete_permission` to allow
        to add/remove the same assignment twice without issuing any flush. Since
        :class:`Entity` creates its initial permissions in during
        :sqlalchemy:`sqlalchemy.orm.events.SessionEvents.after_attach`, it might be
        problematic to issue a flush when entity is not yet ready to be flushed
        (missing required attributes for example).
    """
    to_visit = [session.deleted, session.dirty, session.new]
    with session.no_autoflush:
        # no_autoflush is required to visit PERMISSIONS_ATTR without emitting a
        # flush()
        if obj:
            to_visit.append(getattr(obj, PERMISSIONS_ATTR))

        permissions = (
            p for p in chain(*to_visit) if isinstance(p, PermissionAssignment)
        )

        for instance in permissions:
            if (
                instance.permission == permission
                and instance.role == role
                and instance.object == obj
            ):
                return instance

        # Last chance: perform a filtered query. If obj is not None, sometimes
        # getattr(obj, PERMISSIONS_ATTR) has objects not present in session
        # not in this query (maybe in a parent session transaction `new`?).
        if obj is not None and obj.id is None:
            obj = None

        return (
            session.query(PermissionAssignment)
            .filter(
                PermissionAssignment.permission == permission,
                PermissionAssignment.role == role,
                PermissionAssignment.object == obj,
            )
            .first()
        )


Instruction:
How would you code a function in Python 3 to
return the current user or SYSTEM user.

Response:
def _current_user_manager(self, session=None):
        """Return the current user, or SYSTEM user."""
        if session is None:
            session = db.session()

        try:
            user = g.user
        except Exception:
            return session.query(User).get(0)

        if sa.orm.object_session(user) is not session:
            # this can happen when called from a celery task during development
            # (with CELERY_ALWAYS_EAGER=True): the task SA session is not
            # app.db.session, and we should not attach this object to
            # the other session, because it can make weird, hard-to-debug
            # errors related to session.identity_map.
            return session.query(User).get(user.id)
        else:
            return user


Instruction:
Can you write a function in Python 3 where it
gets all the roles attached to a given principal on a given object.

Response:
def get_roles(self, principal, object=None, no_group_roles=False):
        """Get all the roles attached to given `principal`, on a given
        `object`.

        :param principal: a :class:`User` or :class:`Group`

        :param object: an :class:`Entity`

        :param no_group_roles: If `True`, return only direct roles, not roles
        acquired through group membership.
        """
        assert principal
        if hasattr(principal, "is_anonymous") and principal.is_anonymous:
            return [AnonymousRole]

        query = db.session.query(RoleAssignment.role)
        if isinstance(principal, Group):
            filter_principal = RoleAssignment.group == principal
        else:
            filter_principal = RoleAssignment.user == principal
            if not no_group_roles:
                groups = [g.id for g in principal.groups]
                if groups:
                    filter_principal |= RoleAssignment.group_id.in_(groups)

        query = query.filter(filter_principal)

        if object is not None:
            assert isinstance(object, Entity)

        query = query.filter(RoleAssignment.object == object)
        roles = {i[0] for i in query.all()}

        if object is not None:
            for attr, role in (("creator", Creator), ("owner", Owner)):
                if getattr(object, attr) == principal:
                    roles.add(role)
        return list(roles)


Instruction:
Can you generate the documentation for the following Python 3 function
def get_principals(
        self, role, anonymous=True, users=True, groups=True, object=None, as_list=True
    ):
        """Return all users which are assigned given role."""
        if not isinstance(role, Role):
            role = Role(role)
        assert role
        assert users or groups
        query = RoleAssignment.query.filter_by(role=role)

        if not anonymous:
            query = query.filter(RoleAssignment.anonymous == False)
        if not users:
            query = query.filter(RoleAssignment.user == None)
        elif not groups:
            query = query.filter(RoleAssignment.group == None)

        query = query.filter(RoleAssignment.object == object)
        principals = {(ra.user or ra.group) for ra in query.all()}

        if object is not None and role in (Creator, Owner):
            p = object.creator if role == Creator else object.owner
            if p:
                principals.add(p)

        if not as_list:
            return principals

        return list(principals)

Response: Return all users which are assigned given role.


Instruction:
Write a Python 3 function that can
fill role cache for the given principal.

Response:
def _fill_role_cache(self, principal, overwrite=False):
        """Fill role cache for `principal` (User or Group), in order to avoid
        too many queries when checking role access with 'has_role'.

        Return role_cache of `principal`
        """
        if not self.app_state.use_cache:
            return None

        if not self._has_role_cache(principal) or overwrite:
            self._set_role_cache(principal, self._all_roles(principal))
        return self._role_cache(principal)


Instruction:
How would you code a function in Python 3 to
fill role cache for principals in order to avoid too many queries when checking role access with has_role.

Response:
def _fill_role_cache_batch(self, principals, overwrite=False):
        """Fill role cache for `principals` (Users and/or Groups), in order to
        avoid too many queries when checking role access with 'has_role'."""
        if not self.app_state.use_cache:
            return

        query = db.session.query(RoleAssignment)
        users = {u for u in principals if isinstance(u, User)}
        groups = {g for g in principals if isinstance(g, Group)}
        groups |= {g for u in users for g in u.groups}

        if not overwrite:
            users = {u for u in users if not self._has_role_cache(u)}
            groups = {g for g in groups if not self._has_role_cache(g)}

        if not (users or groups):
            return

        # ensure principals processed here will have role cache. Thus users or
        # groups without any role will have an empty role cache, to avoid
        # unneeded individual DB query when calling self._fill_role_cache(p).
        for p in chain(users, groups):
            self._set_role_cache(p, {})

        filter_cond = []
        if users:
            filter_cond.append(RoleAssignment.user_id.in_(u.id for u in users))
        if groups:
            filter_cond.append(RoleAssignment.group_id.in_(g.id for g in groups))

        query = query.filter(sql.or_(*filter_cond))
        ra_users = {}
        ra_groups = {}
        for ra in query.all():
            if ra.user:
                all_roles = ra_users.setdefault(ra.user, {})
            else:
                all_roles = ra_groups.setdefault(ra.group, {})

            object_key = (
                f"{ra.object.entity_type}:{ra.object_id:d}"
                if ra.object is not None
                else None
            )
            all_roles.setdefault(object_key, set()).add(ra.role)

        for group, all_roles in ra_groups.items():
            self._set_role_cache(group, all_roles)

        for user, all_roles in ra_users.items():
            for gr in user.groups:
                group_roles = self._fill_role_cache(gr)
                for object_key, roles in group_roles.items():
                    obj_roles = all_roles.setdefault(object_key, set())
                    obj_roles |= roles

            self._set_role_cache(user, all_roles)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def has_role(self, principal, role, object=None):
        if not principal:
            return False

        principal = unwrap(principal)
        if not self.running:
            return True

        if isinstance(role, (Role, (str,))):
            role = (role,)

        # admin & manager always have role
        valid_roles = frozenset((Admin, Manager) + tuple(role))

        if AnonymousRole in valid_roles:
            # everybody has the role 'Anonymous'
            return True

        if (
            Authenticated in valid_roles
            and isinstance(principal, User)
            and not principal.is_anonymous
        ):
            return True

        if principal is AnonymousRole or (
            hasattr(principal, "is_anonymous") and principal.is_anonymous
        ):
            # anonymous user, and anonymous role isn't in valid_roles
            return False

        # root always have any role
        if isinstance(principal, User) and principal.id == 0:
            return True

        if object:
            assert isinstance(object, Entity)
            object_key = "{}:{}".format(object.object_type, str(object.id))
            if Creator in role:
                if object.creator == principal:
                    return True
            if Owner in role:
                if object.owner == principal:
                    return True

        else:
            object_key = None

        all_roles = (
            self._fill_role_cache(principal)
            if self.app_state.use_cache
            else self._all_roles(principal)
        )
        roles = set()
        roles |= all_roles.get(None, set())
        roles |= all_roles.get(object_key, set())
        return len(valid_roles & roles) > 0

Response: Returns True if the user has the specified role.


Instruction:
How would you implement a function in Python 3 that
grants role to user.

Response:
def grant_role(self, principal, role, obj=None):
        """Grant `role` to `user` (either globally, if `obj` is None, or on the
        specific `obj`)."""
        assert principal
        principal = unwrap(principal)
        session = object_session(obj) if obj is not None else db.session
        manager = self._current_user_manager(session=session)
        args = {
            "role": role,
            "object": obj,
            "anonymous": False,
            "user": None,
            "group": None,
        }

        if principal is AnonymousRole or (
            hasattr(principal, "is_anonymous") and principal.is_anonymous
        ):
            args["anonymous"] = True
        elif isinstance(principal, User):
            args["user"] = principal
        else:
            args["group"] = principal

        query = session.query(RoleAssignment)
        if query.filter_by(**args).limit(1).count():
            # role already granted, nothing to do
            return

        # same as above but in current, not yet flushed objects in session. We
        # cannot call flush() in grant_role() since this method may be called a
        # great number of times in the same transaction, and sqlalchemy limits
        # to 100 flushes before triggering a warning
        for ra in (
            o
            for models in (session.new, session.dirty)
            for o in models
            if isinstance(o, RoleAssignment)
        ):
            if all(getattr(ra, attr) == val for attr, val in args.items()):
                return

        ra = RoleAssignment(**args)
        session.add(ra)
        audit = SecurityAudit(manager=manager, op=SecurityAudit.GRANT, **args)
        if obj is not None:
            audit.object_id = obj.id
            audit.object_type = obj.entity_type
            object_name = ""
            for attr_name in ("name", "path", "__path_before_delete"):
                if hasattr(obj, attr_name):
                    object_name = getattr(obj, attr_name)
            audit.object_name = object_name

        session.add(audit)
        self._needs_flush()

        if hasattr(principal, "__roles_cache__"):
            del principal.__roles_cache__