Instruction:
How would you explain what the following Python 3 function does
def emitResetAxisSignal(self, axisNumber):
        assert axisNumber in (VALID_AXES_NUMBERS), \
            "Axis Nr should be one of {}, got {}".format(VALID_AXES_NUMBERS, axisNumber)

        # Hide 'auto-scale (A)' button
        logger.debug("ArgosPgPlotItem.autoBtnClicked, mode:{}".format(self.autoBtn.mode))
        if self.autoBtn.mode == 'auto':
            self.autoBtn.hide()
        else:
            # Does this occur?
            msg = "Unexpected autobutton mode: {}".format(self.autoBtn.mode)
            if DEBUGGING:
                raise ValueError(msg)
            else:
                logger.warn(msg)

        logger.debug("Emitting sigAxisReset({}) for {!r}".format(axisNumber, self))
        self.sigAxisReset.emit(axisNumber)

Response:
Emits the sigResetAxis with the axisNumber as parameter
           .


Instruction:
Can you generate the documentation for the following Python 3 function
def merge(local, base, remote, check_modified=False):
    base_local = diff.diff(base, local, check_modified=check_modified)
    base_remote = diff.diff(base, remote, check_modified=check_modified)
    merge = diff.diff(base_local, base_remote)
    return merge

Response: Generates a merged unmerged version of the two items on the local branch and the remote branch.


Instruction:
Explain what the following Python 3 code does
def notebook_merge(local, base, remote, check_modified=False):

    local_cells = get_cells(local)
    base_cells = get_cells(base)
    remote_cells = get_cells(remote)

    rows = []
    current_row = []
    empty_cell = lambda: {
        'cell_type': 'code',
        'language': 'python',
        'outputs': [],
        'prompt_number': 1,
        'text': ['Placeholder'],
        'metadata': {'state': 'empty'}
    }

    diff_of_diffs = merge(local_cells, base_cells, remote_cells)

    # For each item in the higher-order diff, create a "row" that
    # corresponds to a row in the NBDiff interface. A row contains:
    # | LOCAL | BASE | REMOTE |

    for item in diff_of_diffs:
        state = item['state']
        cell = copy.deepcopy(diff_result_to_cell(item['value']))
        if state == 'deleted':
            # This change is between base and local branches.
            # It can be an addition or a deletion.
            if cell['metadata']['state'] == 'unchanged':
                # This side doesn't have the change; wait
                # until we encounter the change to create the row.
                continue
            cell['metadata']['side'] = 'local'
            remote_cell = empty_cell()
            remote_cell['metadata']['side'] = 'remote'
            if cell['metadata']['state'] == 'deleted' \
                    or cell['metadata']['state'] == 'unchanged':
                base_cell = copy.deepcopy(cell)
            else:
                base_cell = empty_cell()
            base_cell['metadata']['side'] = 'base'
            # This change is on the right.
            current_row = [
                cell,
                base_cell,
                remote_cell,
            ]
        elif state == 'added':
            # This change is between base and remote branches.
            # It can be an addition or a deletion.
            cell['metadata']['side'] = 'remote'
            if cell['metadata']['state'] == 'unchanged':
                # This side doesn't have the change; wait
                # until we encounter the change to create the row.
                continue
            if cell['metadata']['state'] == 'deleted':
                base_cell = copy.deepcopy(cell)
                base_cell['metadata']['state'] = 'unchanged'
                local_cell = copy.deepcopy(cell)
                local_cell['metadata']['state'] = 'unchanged'
            else:
                base_cell = empty_cell()
                local_cell = empty_cell()
            base_cell['metadata']['side'] = 'base'
            local_cell['metadata']['side'] = 'local'
            current_row = [
                local_cell,
                base_cell,
                cell,
            ]
        elif state == 'unchanged':
            # The same item occurs between base-local and base-remote.
            # This happens if both branches made the same change, whether
            # that is an addition or deletion. If neither branches
            # changed a given cell, that cell shows up here too.
            cell1 = copy.deepcopy(cell)
            cell3 = copy.deepcopy(cell)
            if cell['metadata']['state'] == 'deleted' \
                    or cell['metadata']['state'] == 'unchanged':
                # If the change is a deletion, the cell-to-be-deleted
                # should in the base as 'unchanged'. The user will
                # choose to make it deleted.
                cell2 = copy.deepcopy(cell)
                cell2['metadata']['state'] = 'unchanged'
            else:
                # If the change is an addition, it should not
                # show in the base; the user must add it to the merged version.
                cell2 = empty_cell()
            cell1['metadata']['side'] = 'local'
            cell2['metadata']['side'] = 'base'
            cell3['metadata']['side'] = 'remote'
            current_row = [
                cell1,
                cell2,
                cell3,
            ]

        rows.append(current_row)

    # Chain all rows together; create a flat array from the nested array.
    # Use the base notebook's notebook-level metadata (title, version, etc.)

    result_notebook = local
    if len(result_notebook['worksheets']) == 0:
        result_notebook['worksheets'] = [nbformat.new_worksheet()]

    new_cell_array = list(it.chain.from_iterable(rows))
    result_notebook['worksheets'][0]['cells'] = new_cell_array

    result_notebook['metadata']['nbdiff-type'] = 'merge'

    return result_notebook

Response: This function takes two dicts of local and base and remote branches and returns a single notebook containing merge metadata.


Instruction:
How would you code a function in Python 3 to
parse a notebook. ipynb file.

Response:
def parse(self, json_data):
        """Parse a notebook .ipynb file.

        Parameters
        ----------
        json_data : file
            A file handle for an .ipynb file.

        Returns
        -------
        nb : An IPython Notebook data structure.
        """
        data = current.read(json_data, 'ipynb')
        json_data.close()
        return data


Instruction:
Create a Python 3 function to
unify two notebooks into a single notebook with diff metadata.

Response:
def notebook_diff(nb1, nb2, check_modified=True):
    """Unify two notebooks into a single notebook with diff metadata.

    The result of this function is a valid notebook that can be loaded
    by the IPython Notebook front-end. This function adds additional
    cell metadata that the front-end Javascript uses to render the diffs.

    Parameters
    ----------
    nb1 : dict
        An IPython Notebook to use as the baseline version.
    nb2 : dict
        An IPython Notebook to compare against the baseline.
    check_modified : bool
        Whether or not to detect cell modification.

    Returns
    -------
    nb : A valid notebook containing diff metadata.
    """
    nb1_cells = nb1['worksheets'][0]['cells']
    nb2_cells = nb2['worksheets'][0]['cells']

    diffed_nb = cells_diff(nb1_cells, nb2_cells, check_modified=check_modified)
    line_diffs = diff_modified_items(diffed_nb)

    cell_list = list()
    for i, item in enumerate(diffed_nb):
        cell = diff_result_to_cell(item)
        if i in line_diffs:
            cell['metadata']['extra-diff-data'] = line_diffs[i]
        cell_list.append(cell)

    nb1['worksheets'][0]['cells'] = cell_list
    nb1['metadata']['nbdiff-type'] = 'diff'

    return nb1


Instruction:
Can you generate a brief explanation for the following Python 3 code
def words_diff(before_words, after_words):
    '''Diff the words in two strings.

    This is intended for use in diffing prose and other forms of text
    where line breaks have little semantic value.

    Parameters
    ----------
    before_words : str
        A string to be used as the baseline version.
    after_words : str
        A string to be compared against the baseline.

    Returns
    -------
    diff_result : A list of dictionaries containing diff information.
    '''
    before_comps = before_words.split()
    after_comps = after_words.split()

    diff_result = diff(
        before_comps,
        after_comps
    )
    return diff_result

Response: Diff the words in two strings.


Instruction:
Can you generate the documentation for the following Python 3 function
def equal(self, line1, line2):
        '''
        return true if exactly equal or if equal but modified,
        otherwise return false
        return type: BooleanPlus
        '''

        eqLine = line1 == line2
        if eqLine:
            return BooleanPlus(True, False)
        else:
            unchanged_count = self.count_similar_words(line1, line2)
            similarity_percent = (
                (2.0 * unchanged_count) /
                (len(line1.split()) + len(line2.split()))
            )
            if similarity_percent >= 0.50:
                return BooleanPlus(True, True)
            return BooleanPlus(False, False)

Response: Return True if line1 == line2 False otherwise


Instruction:
Can you generate the documentation for the following Python 3 function
def compare_cells(self, cell1, cell2):
        '''
        return true if exactly equal or if equal but modified,
        otherwise return false
        return type: BooleanPlus
        '''
        eqlanguage = cell1["language"] == cell2["language"]
        eqinput = cell1["input"] == cell2["input"]
        eqoutputs = self.equaloutputs(cell1["outputs"], cell2["outputs"])

        if eqlanguage and eqinput and eqoutputs:
            return BooleanPlus(True, False)
        elif not self.check_modified:
            return BooleanPlus(False, False)

        input1 = u"".join(cell1['input'])
        input2 = u"".join(cell2['input'])
        similarity_percent = Levenshtein.ratio(input1, input2)
        if similarity_percent >= 0.65:
            return BooleanPlus(True, True)
        return BooleanPlus(False, False)

Response:
return true if exactly equal or if equal but modified,
        otherwise return false
        return type: BooleanPlus


Instruction:
Here you have a function in Python 3, explain what it does
def run_application(component: Union[Component, Dict[str, Any]], *, event_loop_policy: str = None,
                    max_threads: int = None, logging: Union[Dict[str, Any], int, None] = INFO,
                    start_timeout: Union[int, float, None] = 10):
    """
    Configure logging and start the given root component in the default asyncio event loop.

    Assuming the root component was started successfully, the event loop will continue running
    until the process is terminated.

    Initializes the logging system first based on the value of ``logging``:
      * If the value is a dictionary, it is passed to :func:`logging.config.dictConfig` as
        argument.
      * If the value is an integer, it is passed to :func:`logging.basicConfig` as the logging
        level.
      * If the value is ``None``, logging setup is skipped entirely.

    By default, the logging system is initialized using :func:`~logging.basicConfig` using the
    ``INFO`` logging level.

    The default executor in the event loop is replaced with a new
    :class:`~concurrent.futures.ThreadPoolExecutor` where the maximum number of threads is set to
    the value of ``max_threads`` or, if omitted, the default value of
    :class:`~concurrent.futures.ThreadPoolExecutor`.

    :param component: the root component (either a component instance or a configuration dictionary
        where the special ``type`` key is either a component class or a ``module:varname``
        reference to one)
    :param event_loop_policy: entry point name (from the ``asphalt.core.event_loop_policies``
        namespace) of an alternate event loop policy (or a module:varname reference to one)
    :param max_threads: the maximum number of worker threads in the default thread pool executor
        (the default value depends on the event loop implementation)
    :param logging: a logging configuration dictionary, :ref:`logging level <python:levels>` or
        ``None``
    :param start_timeout: seconds to wait for the root component (and its subcomponents) to start
        up before giving up (``None`` = wait forever)

    """
    assert check_argument_types()

    # Configure the logging system
    if isinstance(logging, dict):
        dictConfig(logging)
    elif isinstance(logging, int):
        basicConfig(level=logging)

    # Inform the user whether -O or PYTHONOPTIMIZE was set when Python was launched
    logger = getLogger(__name__)
    logger.info('Running in %s mode', 'development' if __debug__ else 'production')

    # Switch to an alternate event loop policy if one was provided
    if event_loop_policy:
        create_policy = policies.resolve(event_loop_policy)
        policy = create_policy()
        asyncio.set_event_loop_policy(policy)
        logger.info('Switched event loop policy to %s', qualified_name(policy))

    # Assign a new default executor with the given max worker thread limit if one was provided
    event_loop = asyncio.get_event_loop()
    if max_threads is not None:
        event_loop.set_default_executor(ThreadPoolExecutor(max_threads))
        logger.info('Installed a new thread pool executor with max_workers=%d', max_threads)

    # Instantiate the root component if a dict was given
    if isinstance(component, dict):
        component = cast(Component, component_types.create_object(**component))

    logger.info('Starting application')
    context = Context()
    exception = None  # type: Optional[BaseException]
    exit_code = 0

    # Start the root component
    try:
        coro = asyncio.wait_for(component.start(context), start_timeout, loop=event_loop)
        event_loop.run_until_complete(coro)
    except asyncio.TimeoutError as e:
        exception = e
        logger.error('Timeout waiting for the root component to start')
        exit_code = 1
    except Exception as e:
        exception = e
        logger.exception('Error during application startup')
        exit_code = 1
    else:
        logger.info('Application started')

        # Add a signal handler to gracefully deal with SIGTERM
        try:
            event_loop.add_signal_handler(signal.SIGTERM, sigterm_handler, logger, event_loop)
        except NotImplementedError:
            pass  # Windows does not support signals very well

        # Finally, run the event loop until the process is terminated or Ctrl+C is pressed
        try:
            event_loop.run_forever()
        except KeyboardInterrupt:
            pass
        except SystemExit as e:
            exit_code = e.code

    # Close the root context
    logger.info('Stopping application')
    event_loop.run_until_complete(context.close(exception))

    # Shut down leftover async generators (requires Python 3.6+)
    try:
        event_loop.run_until_complete(event_loop.shutdown_asyncgens())
    except (AttributeError, NotImplementedError):
        pass

    # Finally, close the event loop itself
    event_loop.close()
    logger.info('Application stopped')

    # Shut down the logging system
    shutdown()

    if exit_code:
        sys.exit(exit_code)

Response: Runs the given root component in the event loop.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def executor(func_or_executor: Union[Executor, str, Callable[..., T_Retval]]) -> \
        Union[WrappedCallable, Callable[..., WrappedCallable]]:
    """
    Decorate a function to run in an executor.

    If no executor (or ``None``) is given, the current event loop's default executor is used.
    Otherwise, the argument must be a PEP 3148 compliant thread pool executor or the name of an
    :class:`~concurrent.futures.Executor` instance.

    If a decorated callable is called in a worker thread, the executor argument is ignored and the
    wrapped function is called directly.

    Callables wrapped with this decorator must be used with ``await`` when called in the event loop
    thread.

    Example use with the default executor (``None``)::

        @executor
        def this_runs_in_threadpool(ctx):
           return do_something_cpu_intensive()

        async def request_handler(ctx):
            result = await this_runs_in_threadpool(ctx)

    With a named :class:`~concurrent.futures.Executor` resource::

        @executor('special_ops')
        def this_runs_in_threadpool(ctx):
           return do_something_cpu_intensive()

        async def request_handler(ctx):
            result = await this_runs_in_threadpool(ctx)

    :param func_or_executor: either a callable (when used as a decorator), an executor instance or
        the name of an :class:`~concurrent.futures.Executor` resource

    """
    def outer(func: Callable[..., T_Retval],
              executor: Union[Executor, str] = None) -> Callable[..., Awaitable[T_Retval]]:
        def wrapper(*args, **kwargs):
            try:
                loop = get_event_loop()
            except RuntimeError:
                # Event loop not available -- we're in a worker thread
                return func(*args, **kwargs)

            # Resolve the executor resource name to an Executor instance
            if isinstance(executor, str):
                try:
                    ctx = next(obj for obj in args[:2] if isinstance(obj, Context))
                except StopIteration:
                    raise RuntimeError('the callable needs to be called with a Context as the '
                                       'first or second positional argument')

                _executor = ctx.require_resource(Executor, executor)
            else:
                _executor = executor

            callback = partial(func, *args, **kwargs)
            return loop.run_in_executor(_executor, callback)

        assert check_argument_types()
        assert not inspect.iscoroutinefunction(func), \
            'Cannot wrap coroutine functions to be run in an executor'
        return wraps(func)(wrapper)

    if isinstance(func_or_executor, (str, Executor)):
        return partial(outer, executor=func_or_executor)
    else:
        return outer(func_or_executor)

Response: Decorator to wrap a function to run in an executor.


Instruction:
Can you implement a function in Python 3 that
returns the qualified name for the given object.

Response:
def qualified_name(obj) -> str:
    """
    Return the qualified name (e.g. package.module.Type) for the given object.

    If ``obj`` is not a class, the returned name will match its type instead.

    """
    if not isclass(obj):
        obj = type(obj)

    if obj.__module__ == 'builtins':
        return obj.__name__
    else:
        return '{}.{}'.format(obj.__module__, obj.__qualname__)


Instruction:
How would you implement a function in Python 3 that
returns the qualified name for the given callable.

Response:
def callable_name(func: Callable) -> str:
    """Return the qualified name (e.g. package.module.func) for the given callable."""
    if func.__module__ == 'builtins':
        return func.__name__
    else:
        return '{}.{}'.format(func.__module__, func.__qualname__)


Instruction:
Explain what the following Python 3 code does
def merge_config(original: Optional[Dict[str, Any]],
                 overrides: Optional[Dict[str, Any]]) -> Dict[str, Any]:
    """
    Return a copy of the ``original`` configuration dictionary, with overrides from ``overrides``
    applied.

    This similar to what :meth:`dict.update` does, but when a dictionary is about to be
    replaced with another dictionary, it instead merges the contents.

    If a key in ``overrides`` is a dotted path (ie. ``foo.bar.baz: value``), it is assumed to be a
    shorthand for ``foo: {bar: {baz: value}}``.

    :param original: a configuration dictionary (or ``None``)
    :param overrides: a dictionary containing overriding values to the configuration (or ``None``)
    :return: the merge result

    """
    assert check_argument_types()
    copied = original.copy() if original else {}
    if overrides:
        for key, value in overrides.items():
            if '.' in key:
                key, rest = key.split('.', 1)
                value = {rest: value}

            orig_value = copied.get(key)
            if isinstance(orig_value, dict) and isinstance(value, dict):
                copied[key] = merge_config(orig_value, value)
            else:
                copied[key] = value

    return copied

Response: Returns a copy of original with overrides applied.


Instruction:
Implement a Python 3 function for
resolving a reference to an entry point or a variable in a module.

Response:
def resolve(self, obj):
        """
        Resolve a reference to an entry point or a variable in a module.

        If ``obj`` is a ``module:varname`` reference to an object, :func:`resolve_reference` is
        used to resolve it. If it is a string of any other kind, the named entry point is loaded
        from this container's namespace. Otherwise, ``obj`` is returned as is.

        :param obj: an entry point identifier, an object reference or an arbitrary object
        :return: the loaded entry point, resolved object or the unchanged input value
        :raises LookupError: if ``obj`` was a string but the named entry point was not found

        """
        if not isinstance(obj, str):
            return obj
        if ':' in obj:
            return resolve_reference(obj)

        value = self._entrypoints.get(obj)
        if value is None:
            raise LookupError('no such entry point in {}: {}'.format(self.namespace, obj))

        if isinstance(value, EntryPoint):
            value = self._entrypoints[obj] = value.load()

        return value


Instruction:
Here you have a function in Python 3, explain what it does
def create_object(self, type: Union[type, str], **constructor_kwargs):
        assert check_argument_types()
        assert self.base_class, 'base class has not been defined'
        plugin_class = self.resolve(type)
        if not issubclass(plugin_class, self.base_class):
            raise TypeError('{} is not a subclass of {}'.format(
                qualified_name(plugin_class), qualified_name(self.base_class)))

        return plugin_class(**constructor_kwargs)

Response: Instantiate a plugin object of the specified type.


Instruction:
Can you implement a function in Python 3 that
loads all entry points in this namespace and return the resulting objects as a list.

Response:
def all(self) -> List[Any]:
        """
        Load all entry points (if not already loaded) in this namespace and return the resulting
        objects as a list.

        """
        values = []
        for name, value in self._entrypoints.items():
            if isinstance(value, EntryPoint):
                value = self._entrypoints[name] = value.load()

            values.append(value)

        return values


Instruction:
Can you implement a function in Python 3 that
adds a child component to the entry point.

Response:
def add_component(self, alias: str, type: Union[str, type] = None, **config):
        """
        Add a child component.

        This will instantiate a component class, as specified by the ``type`` argument.

        If the second argument is omitted, the value of ``alias`` is used as its value.

        The locally given configuration can be overridden by component configuration parameters
        supplied to the constructor (via the ``components`` argument).

        When configuration values are provided both as keyword arguments to this method and
        component configuration through the ``components`` constructor argument, the configurations
        are merged together using :func:`~asphalt.core.util.merge_config` in a way that the
        configuration values from the ``components`` argument override the keyword arguments to
        this method.

        :param alias: a name for the component instance, unique within this container
        :param type: entry point name or :class:`Component` subclass or a ``module:varname``
            reference to one
        :param config: keyword arguments passed to the component's constructor

        """
        assert check_argument_types()
        if not isinstance(alias, str) or not alias:
            raise TypeError('component_alias must be a nonempty string')
        if alias in self.child_components:
            raise ValueError('there is already a child component named "{}"'.format(alias))

        config['type'] = type or alias

        # Allow the external configuration to override the constructor arguments
        override_config = self.component_configs.get(alias) or {}
        config = merge_config(config, override_config)

        component = component_types.create_object(**config)
        self.child_components[alias] = component


Instruction:
Can you create a Python 3 function that
starts the child components.

Response:
async def start(self, ctx: Context):
        """
        Create child components that have been configured but not yet created and then calls their
        :meth:`~Component.start` methods in separate tasks and waits until they have completed.

        """
        for alias in self.component_configs:
            if alias not in self.child_components:
                self.add_component(alias)

        tasks = [component.start(ctx) for component in self.child_components.values()]
        if tasks:
            await asyncio.gather(*tasks)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def executor(arg: Union[Executor, str, Callable] = None):
    def outer_wrapper(func: Callable):
        @wraps(func)
        def inner_wrapper(*args, **kwargs):
            try:
                ctx = next(arg for arg in args[:2] if isinstance(arg, Context))
            except StopIteration:
                raise RuntimeError('the first positional argument to {}() has to be a Context '
                                   'instance'.format(callable_name(func))) from None

            executor = ctx.require_resource(Executor, resource_name)
            return asyncio_extras.call_in_executor(func, *args, executor=executor, **kwargs)

        return inner_wrapper

    if isinstance(arg, str):
        resource_name = arg
        return outer_wrapper

    return asyncio_extras.threadpool(arg)

Response: Decorator that returns a function that runs in an executor instance.


Instruction:
Explain what the following Python 3 code does
def context_teardown(func: Callable):
    @wraps(func)
    async def wrapper(*args, **kwargs) -> None:
        async def teardown_callback(exception: Optional[Exception]):
            try:
                await generator.asend(exception)
            except StopAsyncIteration:
                pass
            finally:
                await generator.aclose()

        try:
            ctx = next(arg for arg in args[:2] if isinstance(arg, Context))
        except StopIteration:
            raise RuntimeError('the first positional argument to {}() has to be a Context '
                               'instance'.format(callable_name(func))) from None

        generator = func(*args, **kwargs)
        try:
            await generator.asend(None)
        except StopAsyncIteration:
            pass
        except BaseException:
            await generator.aclose()
            raise
        else:
            ctx.add_teardown_callback(teardown_callback, True)

    if iscoroutinefunction(func):
        func = async_generator(func)
    elif not isasyncgenfunction(func):
        raise TypeError('{} must be an async generator function'.format(callable_name(func)))

    return wrapper

Response: A decorator that executes the rest of the function at context teardown.


Instruction:
Explain what the following Python 3 code does
def context_chain(self) -> List['Context']:
        contexts = []
        ctx = self  # type: Optional[Context]
        while ctx is not None:
            contexts.append(ctx)
            ctx = ctx.parent

        return contexts

Response: Return a list of contexts starting from this one its parent and so on.


Instruction:
Create a Python 3 function for
adding a callback to be called when this context closes.

Response:
def add_teardown_callback(self, callback: Callable, pass_exception: bool = False) -> None:
        """
        Add a callback to be called when this context closes.

        This is intended for cleanup of resources, and the list of callbacks is processed in the
        reverse order in which they were added, so the last added callback will be called first.

        The callback may return an awaitable. If it does, the awaitable is awaited on before
        calling any further callbacks.

        :param callback: a callable that is called with either no arguments or with the exception
            that ended this context, based on the value of ``pass_exception``
        :param pass_exception: ``True`` to pass the callback the exception that ended this context
            (or ``None`` if the context ended cleanly)

        """
        assert check_argument_types()
        self._check_closed()
        self._teardown_callbacks.append((callback, pass_exception))


Instruction:
Can you tell what is the following Python 3 function doing
async def close(self, exception: BaseException = None) -> None:
        self._check_closed()
        self._closed = True

        exceptions = []
        for callback, pass_exception in reversed(self._teardown_callbacks):
            try:
                retval = callback(exception) if pass_exception else callback()
                if isawaitable(retval):
                    await retval
            except Exception as e:
                exceptions.append(e)

        del self._teardown_callbacks
        if exceptions:
            raise TeardownError(exceptions)

Response: Closes this context and call any necessary resource teardown callbacks.


Instruction:
Explain what the following Python 3 code does
def add_resource(self, value, name: str = 'default', context_attr: str = None,
                     types: Union[type, Sequence[type]] = ()) -> None:
        """
        Add a resource to this context.

        This will cause a ``resource_added`` event to be dispatched.

        :param value: the actual resource value
        :param name: name of this resource (unique among all its registered types within a single
            context)
        :param context_attr: name of the context attribute this resource will be accessible as
        :param types: type(s) to register the resource as (omit to use the type of ``value``)
        :raises asphalt.core.context.ResourceConflict: if the resource conflicts with an existing
            one in any way

        """
        assert check_argument_types()
        self._check_closed()
        if isinstance(types, type):
            types = (types,)
        elif not types:
            types = (type(value),)

        if value is None:
            raise ValueError('"value" must not be None')
        if not resource_name_re.fullmatch(name):
            raise ValueError('"name" must be a nonempty string consisting only of alphanumeric '
                             'characters and underscores')
        if context_attr and getattr_static(self, context_attr, None) is not None:
            raise ResourceConflict('this context already has an attribute {!r}'.format(
                context_attr))
        for resource_type in types:
            if (resource_type, name) in self._resources:
                raise ResourceConflict(
                    'this context already contains a resource of type {} using the name {!r}'.
                    format(qualified_name(resource_type), name))

        resource = ResourceContainer(value, tuple(types), name, context_attr, False)
        for type_ in resource.types:
            self._resources[(type_, name)] = resource

        if context_attr:
            setattr(self, context_attr, value)

        # Notify listeners that a new resource has been made available
        self.resource_added.dispatch(types, name, False)

Response: Add a resource to the current context.


Instruction:
How would you code a function in Python 3 to
add a resource factory to the current context.

Response:
def add_resource_factory(self, factory_callback: factory_callback_type,
                             types: Union[type, Sequence[Type]], name: str = 'default',
                             context_attr: str = None) -> None:
        """
        Add a resource factory to this context.

        This will cause a ``resource_added`` event to be dispatched.

        A resource factory is a callable that generates a "contextual" resource when it is
        requested by either using any of the methods :meth:`get_resource`, :meth:`require_resource`
        or :meth:`request_resource` or its context attribute is accessed.

        When a new resource is created in this manner, it is always bound to the context through
        it was requested, regardless of where in the chain the factory itself was added to.

        :param factory_callback: a (non-coroutine) callable that takes a context instance as
            argument and returns the created resource object
        :param types: one or more types to register the generated resource as on the target context
        :param name: name of the resource that will be created in the target context
        :param context_attr: name of the context attribute the created resource will be accessible
            as
        :raises asphalt.core.context.ResourceConflict: if there is an existing resource factory for
            the given type/name combinations or the given context variable

        """
        assert check_argument_types()
        self._check_closed()
        if not resource_name_re.fullmatch(name):
            raise ValueError('"name" must be a nonempty string consisting only of alphanumeric '
                             'characters and underscores')
        if iscoroutinefunction(factory_callback):
            raise TypeError('"factory_callback" must not be a coroutine function')
        if not types:
            raise ValueError('"types" must not be empty')

        if isinstance(types, type):
            resource_types = (types,)  # type: Tuple[type, ...]
        else:
            resource_types = tuple(types)

        # Check for a conflicting context attribute
        if context_attr in self._resource_factories_by_context_attr:
            raise ResourceConflict(
                'this context already contains a resource factory for the context attribute {!r}'.
                format(context_attr))

        # Check for conflicts with existing resource factories
        for type_ in resource_types:
            if (type_, name) in self._resource_factories:
                raise ResourceConflict('this context already contains a resource factory for the '
                                       'type {}'.format(qualified_name(type_)))

        # Add the resource factory to the appropriate lookup tables
        resource = ResourceContainer(factory_callback, resource_types, name, context_attr, True)
        for type_ in resource_types:
            self._resource_factories[(type_, name)] = resource

        if context_attr:
            self._resource_factories_by_context_attr[context_attr] = resource

        # Notify listeners that a new resource has been made available
        self.resource_added.dispatch(resource_types, name, True)


Instruction:
Write a Python 3 function for
looking up a resource in the chain of contexts and return the value or None if none was available.

Response:
def get_resource(self, type: Type[T_Resource], name: str = 'default') -> Optional[T_Resource]:
        """
        Look up a resource in the chain of contexts.

        :param type: type of the requested resource
        :param name: name of the requested resource
        :return: the requested resource, or ``None`` if none was available

        """
        assert check_argument_types()
        self._check_closed()
        key = (type, name)

        # First check if there's already a matching resource in this context
        resource = self._resources.get(key)
        if resource is not None:
            return resource.value_or_factory

        # Next, check if there's a resource factory available on the context chain
        resource = next((ctx._resource_factories[key] for ctx in self.context_chain
                         if key in ctx._resource_factories), None)
        if resource is not None:
            return resource.generate_value(self)

        # Finally, check parents for a matching resource
        return next((ctx._resources[key].value_or_factory for ctx in self.context_chain
                     if key in ctx._resources), None)


Instruction:
Make a summary of the following Python 3 code
def get_resources(self, type: Type[T_Resource]) -> Set[T_Resource]:
        assert check_argument_types()

        # Collect all the matching resources from this context
        resources = {container.name: container.value_or_factory
                     for container in self._resources.values()
                     if not container.is_factory and type in container.types
                     }  # type: Dict[str, T_Resource]

        # Next, find all matching resource factories in the context chain and generate resources
        resources.update({container.name: container.generate_value(self)
                          for ctx in self.context_chain
                          for container in ctx._resources.values()
                          if container.is_factory and type in container.types
                          and container.name not in resources})

        # Finally, add the resource values from the parent contexts
        resources.update({container.name: container.value_or_factory
                          for ctx in self.context_chain[1:]
                          for container in ctx._resources.values()
                          if not container.is_factory and type in container.types
                          and container.name not in resources})

        return set(resources.values())

Response: Retrieve all the resources of the given type in this context and its parents.


Instruction:
Create a Python 3 function to
return the requested resource in the chain of contexts.

Response:
def require_resource(self, type: Type[T_Resource], name: str = 'default') -> T_Resource:
        """
        Look up a resource in the chain of contexts and raise an exception if it is not found.

        This is like :meth:`get_resource` except that instead of returning ``None`` when a resource
        is not found, it will raise :exc:`~asphalt.core.context.ResourceNotFound`.

        :param type: type of the requested resource
        :param name: name of the requested resource
        :return: the requested resource
        :raises asphalt.core.context.ResourceNotFound: if a resource of the given type and name was
            not found

        """
        resource = self.get_resource(type, name)
        if resource is None:
            raise ResourceNotFound(type, name)

        return resource


Instruction:
Can you write a function in Python 3 where it
requests a resource from the chain of contexts.

Response:
async def request_resource(self, type: Type[T_Resource], name: str = 'default') -> T_Resource:
        """
        Look up a resource in the chain of contexts.

        This is like :meth:`get_resource` except that if the resource is not already available, it
        will wait for one to become available.

        :param type: type of the requested resource
        :param name: name of the requested resource
        :return: the requested resource

        """
        # First try to locate an existing resource in this context and its parents
        value = self.get_resource(type, name)
        if value is not None:
            return value

        # Wait until a matching resource or resource factory is available
        signals = [ctx.resource_added for ctx in self.context_chain]
        await wait_event(
            signals, lambda event: event.resource_name == name and type in event.resource_types)
        return self.require_resource(type, name)


Instruction:
Make a summary of the following Python 3 code
def call_async(self, func: Callable, *args, **kwargs):
        return asyncio_extras.call_async(self.loop, func, *args, **kwargs)

Response: Call the given callable in the event loop thread.


Instruction:
Write a Python 3 script for
calling the given callable in an executor.

Response:
def call_in_executor(self, func: Callable, *args, executor: Union[Executor, str] = None,
                         **kwargs) -> Awaitable:
        """
        Call the given callable in an executor.

        :param func: the callable to call
        :param args: positional arguments to call the callable with
        :param executor: either an :class:`~concurrent.futures.Executor` instance, the resource
            name of one or ``None`` to use the event loop's default executor
        :param kwargs: keyword arguments to call the callable with
        :return: an awaitable that resolves to the return value of the call

        """
        assert check_argument_types()
        if isinstance(executor, str):
            executor = self.require_resource(Executor, executor)

        return asyncio_extras.call_in_executor(func, *args, executor=executor, **kwargs)


Instruction:
Here you have a function in Python 3, explain what it does
def threadpool(self, executor: Union[Executor, str] = None):
        assert check_argument_types()
        if isinstance(executor, str):
            executor = self.require_resource(Executor, executor)

        return asyncio_extras.threadpool(executor)

Response: Returns an asynchronous context manager that runs the block in a thread pool.


Instruction:
How would you code a function in Python 3 to
return an async generator that yields events from the given signals.

Response:
def stream_events(signals: Sequence[Signal], filter: Callable[[T_Event], bool] = None, *,
                  max_queue_size: int = 0) -> AsyncIterator[T_Event]:
    """
    Return an async generator that yields events from the given signals.

    Only events that pass the filter callable (if one has been given) are returned.
    If no filter function was given, all events are yielded from the generator.

    :param signals: the signals to get events from
    :param filter: a callable that takes an event object as an argument and returns ``True`` if
        the event should pass, ``False`` if not
    :param max_queue_size: maximum size of the queue, after which it will start to drop events

    """
    @async_generator
    async def streamer():
        try:
            while True:
                event = await queue.get()
                if filter is None or filter(event):
                    await yield_(event)
        finally:
            cleanup()

    def cleanup():
        nonlocal queue
        if queue is not None:
            for signal in signals:
                signal.disconnect(queue.put_nowait)

            queue = None

    assert check_argument_types()
    queue = Queue(max_queue_size)  # type: Queue[T_Event]
    for signal in signals:
        signal.connect(queue.put_nowait)

    gen = [streamer()]  # this is to allow the reference count to drop to 0
    weakref.finalize(gen[0], cleanup)
    return gen.pop()


Instruction:
Can you generate a brief explanation for the following Python 3 code
async def wait_event(signals: Sequence['Signal[T_Event]'],
                     filter: Callable[[T_Event], bool] = None) -> T_Event:
    """
    Wait until any of the given signals dispatches an event that satisfies the filter (if any).

    If no filter has been given, the first event dispatched from the signal is returned.

    :param signals: the signals to get events from
    :param filter: a callable that takes an event object as an argument and returns ``True`` if
        the event should pass, ``False`` if not
    :return: the event that was dispatched

    """
    if sys.version_info >= (3, 5, 3):
        assert check_argument_types()

    async with aclosing(stream_events(signals, filter)) as events:
        return await events.asend(None)

Response: Wait until any of the given signals dispatches an event.


Instruction:
Write a Python 3 function for
connecting a callback to this signal.

Response:
def connect(self, callback: Callable[[T_Event], Any]) -> Callable[[T_Event], Any]:
        """
        Connect a callback to this signal.

        Each callable can only be connected once. Duplicate registrations are ignored.

        If you need to pass extra arguments to the callback, you can use :func:`functools.partial`
        to wrap the callable.

        :param callback: a callable that will receive an event object as its only argument.
        :return: the value of ``callback`` argument

        """
        assert check_argument_types()
        if self.listeners is None:
            self.listeners = []
        if callback not in self.listeners:
            self.listeners.append(callback)

        return callback


Instruction:
Make a summary of the following Python 3 code
def disconnect(self, callback: Callable) -> None:
        assert check_argument_types()
        try:
            if self.listeners is not None:
                self.listeners.remove(callback)
        except ValueError:
            pass

Response: Disconnects the given callback from the current object.


Instruction:
Can you create a Python 3 function that
dispatches the given event object to all listeners and returns a Future that resolves with True if all the callbacks have been called.

Response:
def dispatch_raw(self, event: Event) -> Awaitable[bool]:
        """
        Dispatch the given event object to all listeners.

        Creates a new task in which all listener callbacks are called with the given event as
        the only argument. Coroutine callbacks are converted to their own respective tasks and
        waited for concurrently.

        Before the dispatching is done, a snapshot of the listeners is taken and the event is only
        dispatched to those listeners, so adding a listener between the call to this method and the
        actual dispatching will only affect future calls to this method.

        :param event: the event object to dispatch
        :returns: an awaitable that completes when all the callbacks have been called (and any
            awaitables waited on) and resolves to ``True`` if there were no exceptions raised by
            the callbacks, ``False`` otherwise

        """
        async def do_dispatch() -> None:
            awaitables = []
            all_successful = True
            for callback in listeners:
                try:
                    retval = callback(event)
                except Exception:
                    logger.exception('Uncaught exception in event listener')
                    all_successful = False
                else:
                    if isawaitable(retval):
                        awaitables.append(retval)

            # For any callbacks that returned awaitables, wait for their completion and log any
            # exceptions they raised
            if awaitables:
                done, _ = await wait(awaitables, loop=loop)
                for f in done:
                    exc = f.exception()
                    if exc is not None:
                        all_successful = False
                        logger.error('Uncaught exception in event listener', exc_info=exc)

            if not future.cancelled():
                future.set_result(all_successful)

        if not isinstance(event, self.event_class):
            raise TypeError('event must be of type {}'.format(qualified_name(self.event_class)))

        loop = get_event_loop()
        future = loop.create_future()
        if self.listeners:
            listeners = list(self.listeners)
            loop.create_task(do_dispatch())
        else:
            future.set_result(True)

        return future


Instruction:
Given the following Python 3 function, write the documentation
def dispatch(self, *args, **kwargs) -> Awaitable[bool]:
        event = self.event_class(self.source(), cast(str, self.topic), *args, **kwargs)
        return self.dispatch_raw(event)

Response: Create and dispatch an event.


Instruction:
How would you explain what the following Python 3 function does
def wait_event(self, filter: Callable[[T_Event], bool] = None) -> Awaitable[T_Event]:
        return wait_event([self], filter)

Response: Shortcut for calling wait_event with this signal in the first argument.


Instruction:
Can you implement a function in Python 3 that
handles characters seen when in an escape sequence.

Response:
def _escape_sequence(self, char):
        """
        Handle characters seen when in an escape sequence. Most non-vt52
        commands start with a left-bracket after the escape and then a
        stream of parameters and a command.
        """

        num = ord(char)
        if char == "[":
            self.state = "escape-lb"
        elif char == "(":
            self.state = "charset-g0"
        elif char == ")":
            self.state = "charset-g1"
        elif num in self.escape:
            self.dispatch(self.escape[num])
            self.state = "stream"
        elif self.fail_on_unknown_esc:
            raise StreamProcessError("Unexpected character '%c' == '0x%02x'" % (char, ord(char)))


Instruction:
Implement a function in Python 3 to
handle the end of an escape sequence.

Response:
def _end_escape_sequence(self, char):
        """
        Handle the end of an escape sequence. The final character in an escape
        sequence is the command to execute, which corresponds to the event that
        is dispatched here.
        """

        num = ord(char)
        if num in self.sequence:
            self.dispatch(self.sequence[num], *self.params)
        self.state = "stream"
        self.current_param = ""
        self.params = []


Instruction:
Can you tell what is the following Python 3 function doing
def _escape_parameters(self, char):

        if char == ";":
            self.params.append(int(self.current_param))
            self.current_param = ""
        elif char == "?":
            self.state = "mode"
        elif not char.isdigit():
            if len(self.current_param) > 0:
                self.params.append(int(self.current_param))

            # If we're in parameter parsing mode, but we see a non-numeric
            # value, it must be the end of the control sequence.
            self._end_escape_sequence(char)
        else:
            self.current_param += char

Response: Parse the parameters in an escape sequence.


Instruction:
Write a Python 3 script to
process a character when in the stream state.

Response:
def _stream(self, char):
        """
        Process a character when in the
        default 'stream' state.
        """

        num = ord(char)
        if num in self.basic:
            self.dispatch(self.basic[num])
        elif num == ctrl.ESC:
            self.state = "escape"
        elif num == 0x00:
            # nulls are just ignored.
            pass
        else:
            self.dispatch("print", char)


Instruction:
Can you create a Python 3 function that
consumes a single character and advance the state as necessary.

Response:
def consume(self, char):
        """
        Consume a single character and advance the state as necessary.
        """

        if self.state == "stream":
            self._stream(char)
        elif self.state == "escape":
            self._escape_sequence(char)
        elif self.state == "escape-lb":
            self._escape_parameters(char)
        elif self.state == "mode":
            self._mode(char)
        elif self.state == "charset-g0":
            self._charset_g0(char)
        elif self.state == "charset-g1":
            self._charset_g1(char)


Instruction:
Can you implement a function in Python 3 that
consumes a string of and advance the state as necessary.

Response:
def process(self, chars):
        """
        Consume a string of  and advance the state as necessary.
        """

        while len(chars) > 0:
            self.consume(chars[0])
            chars = chars[1:]


Instruction:
Can you tell what is the following Python 3 function doing
def add_event_listener(self, event, function):

        if event not in self.listeners:
            self.listeners[event] = []

        self.listeners[event].append(function)

Response: Add an event listener function to be invoked when a particular event occurs.


Instruction:
Write a Python 3 script to
dispatch an event to the related objects.

Response:
def dispatch(self, event, *args):
        """
        Dispatch an event where `args` is a tuple of the arguments to send to
        any callbacks. If any callback throws an exception, the subsequent
        callbacks will be aborted.
        """

        for callback in self.listeners.get(event, []):
            if len(args) > 0:
                callback(*args)
            else:
                callback()


Instruction:
How would you code a function in Python 3 to
attach this screen to a events that processes commands and dispatches events.

Response:
def attach(self, events):
        """
        Attach this screen to a events that processes commands and dispatches
        events. Sets up the appropriate event handlers so that the screen will
        update itself automatically as the events processes data.
        """

        if events is not None:
            events.add_event_listener("print", self._print)
            events.add_event_listener("backspace", self._backspace)
            events.add_event_listener("tab", self._tab)
            events.add_event_listener("linefeed", self._linefeed)
            events.add_event_listener("reverse-linefeed",
                                      self._reverse_linefeed)
            events.add_event_listener("carriage-return", self._carriage_return)
            events.add_event_listener("index", self._index)
            events.add_event_listener("reverse-index", self._reverse_index)
            events.add_event_listener("store-cursor", self._save_cursor)
            events.add_event_listener("restore-cursor", self._restore_cursor)
            events.add_event_listener("cursor-up", self._cursor_up)
            events.add_event_listener("cursor-down", self._cursor_down)
            events.add_event_listener("cursor-right", self._cursor_forward)
            events.add_event_listener("cursor-left", self._cursor_back)
            events.add_event_listener("cursor-move", self._cursor_position)
            events.add_event_listener("erase-in-line", self._erase_in_line)
            events.add_event_listener("erase-in-display",
                                      self._erase_in_display)
            events.add_event_listener("delete-characters",
                                      self._delete_character)
            events.add_event_listener("insert-lines", self._insert_line)
            events.add_event_listener("delete-lines", self._delete_line)
            events.add_event_listener("select-graphic-rendition",
                                      self._select_graphic_rendition)
            events.add_event_listener("charset-g0", self._charset_g0)
            events.add_event_listener("charset-g1", self._charset_g1)
            events.add_event_listener("shift-in", self._shift_in)
            events.add_event_listener("shift-out", self._shift_out)
            events.add_event_listener("bell", self._bell)


Instruction:
Can you generate the documentation for the following Python 3 function
def resize(self, shape):
        rows, cols = shape

        # Honestly though, you can't trust anyone these days...
        assert(rows > 0 and cols > 0)

        # First resize the rows
        if self.size[0] < rows:
            # If the current display size is shorter than the requested screen
            # size, then add rows to the bottom. Note that the old column size
            # is used here so these new rows will get expanded/contracted as
            # necessary by the column resize when it happens next.
            self.display += [u" " * self.size[1]] * (rows - self.size[0])
            self.attributes += [[self.default_attributes] * self.size[1]] * \
                    (rows - self.size[0])
        elif self.size[0] > rows:
            # If the current display size is taller than the requested display,
            # then take rows off the top.
            self.display = self.display[self.size[0]-rows:]
            self.attributes = self.attributes[self.size[0]-rows:]

        # Next, of course, resize the columns.
        if self.size[1] < cols:
            # If the current display size is thinner than the requested size,
            # expand each row to be the new size.
            self.display = \
                [row + (u" " * (cols - self.size[1])) for row in self.display]
            self.attributes = \
                [row + ([self.default_attributes] * (cols - self.size[1])) for row in self.attributes]
        elif self.size[1] > cols:
            # If the current display size is fatter than the requested size,
            # then trim each row from the right to be the new size.
            self.display = [row[:cols-self.size[1]] for row in self.display]
            self.attributes = [row[:cols-self.size[1]] for row in self.attributes]

        self.size = (rows, cols)
        return self.size

Response:
Resize the screen. If the requested screen size has more rows than the
        existing screen, rows will be added at the bottom. If the requested
        size has less rows than the existing screen rows will be clipped at the
        top of the screen.

        Similarly if the existing screen has less columns than the requested
        size, columns will be added at the right, and it it has more, columns
        will be clipped at the right.


Instruction:
Make a summary of the following Python 3 code
def _print(self, char):

        # Don't make bugs where we try to print a screen.
        assert len(char) == 1

        try:
            try:
                # Python 3
                char = self.decoder(bytes(char, self.encoding))[0]
            except TypeError:
                # Python 2.x
                char = self.decoder(char)[0]

        except UnicodeDecodeError:
            char = "?"

        if self.current_charset == "g0" and self.g0 is not None:
            char = char.translate(self.g0)
        elif self.current_charset == "g1" and self.g1 is not None:
            char = char.translate(self.g1)

        row = self.display[self.y]
        self.display[self.y] = row[:self.x] + char + row[self.x+1:]

        attrs = self.attributes[self.y]
        self.attributes[self.y] = attrs[:self.x] + [self.cursor_attributes] + \
                attrs[self.x+1:]

        self.x += 1

        if self.x >= self.size[1]:
            # If this was the last column in a row, move the cursor to the
            # next row.
            self._linefeed()

Response: Print a character at the current cursor position and advance the cursor.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _index(self):

        if self.y + 1 >= self.size[0]:
            # If the cursor is currently on the last row, then spawn another
            # and scroll down (removing the top row).
            self.display = self.display[1:] + [u" " * self.size[1]]
        else:
            # If the cursor is anywhere else, then just move it to the
            # next line.
            self.y += 1

Response: Move the cursor down one row in the same column.


Instruction:
Write a Python 3 function for
moving the cursor up one row in the same column.

Response:
def _reverse_index(self):
        """
        Move the cursor up one row in the same column. If the cursor is at the
        first row, create a new row at the top.
        """
        if self.y == 0:
            # If the cursor is currently at the first row, then scroll the
            # screen up.
            self.display = [u" " * self.size[1]] + self.display[:-1]
        else:
            # If the cursor is anywhere other than the first row than just move
            # it up by one row.
            self.y -= 1


Instruction:
Write a Python 3 script for
returning the x value of the next available tabstop.

Response:
def _next_tab_stop(self):
        """
        Return the x value of the next available tabstop or the x value of the
        margin if there are no more tabstops.
        """

        for stop in sorted(self.tabstops):
            if self.x < stop:
                return stop
        return self.size[1] - 1


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _restore_cursor(self):

        if len(self.cursor_save_stack):
            self.x, self.y = self.cursor_save_stack.pop()

Response: Restores the current cursor position.


Instruction:
Can you generate the documentation for the following Python 3 function
def _insert_line(self, count=1):
        trimmed = self.display[:self.y+1] + \
                  [u" " * self.size[1]] * count + \
                  self.display[self.y+1:self.y+count+1]
        self.display = trimmed[:self.size[0]]

Response: Insert count lines at cursor.


Instruction:
Write a Python 3 script to
delete count lines starting at cursor and moves up of the screen.

Response:
def _delete_line(self, count=1):
        """
        Deletes count lines, starting at line with cursor. As lines are
        deleted, lines displayed below cursor move up. Lines added to bottom of
        screen have spaces with same character attributes as last line moved
        up.
        """
        self.display = self.display[:self.y] + \
                       self.display[self.y+1:]
        self.display.append([u" " * self.size[1]] * count)
        self.attributes = self.attributes[:self.y] + \
                       self.attributes[self.y+1:]
        last_attributes = self.attributes[-1]
        for _ in xrange(count):
            self.attributes.append(copy(last_attributes))


Instruction:
Write a Python 3 function that can
delete count characters starting with the character at cursor position.

Response:
def _delete_character(self, count=1):
        """
        Deletes count characters, starting with the character at cursor
        position. When a character is deleted, all characters to the right
        of cursor move left.
        """

        # First resize the text display
        row = self.display[self.y]
        count = min(count, self.size[1] - self.x)
        row = row[:self.x] + row[self.x+count:] + u" " * count
        self.display[self.y] = row

        # Then resize the attribute array too
        attrs = self.attributes[self.y]
        attrs = attrs[:self.x] + attrs[self.x+count:] + [self.default_attributes] * count
        self.attributes[self.y] = attrs


Instruction:
Can you generate the documentation for the following Python 3 function
def _erase_in_line(self, type_of=0):

        row = self.display[self.y]
        attrs = self.attributes[self.y]
        if type_of == 0:
            # Erase from the cursor to the end of line, including the cursor
            row = row[:self.x] + u" " * (self.size[1] - self.x)
            attrs = attrs[:self.x] + [self.default_attributes] * (self.size[1] - self.x)
        elif type_of == 1:
            # Erase from the beginning of the line to the cursor, including it
            row = u" " * (self.x+1) + row[self.x+1:]
            attrs = [self.default_attributes] * (self.x+1) + attrs[self.x+1:]
        elif type_of == 2:
            # Erase the entire line.
            row = u" " * self.size[1]
            attrs = [self.default_attributes] * self.size[1]

        self.display[self.y] = row
        self.attributes[self.y] = attrs

Response: Erases the line in a specific way.


Instruction:
How would you code a function in Python 3 to
move cursor right count columns. Cursor stops at right margin.

Response:
def _cursor_forward(self, count=1):
        """
        Moves cursor right count columns. Cursor stops at right margin.
        """
        self.x = min(self.size[1] - 1, self.x + count)


Instruction:
Write a Python 3 script for
setting the cursor to a specific row and column.

Response:
def _cursor_position(self, row=0, column=0):
        """
        Set the cursor to a specific row and column.

        Obnoxiously row/column is 1 based, instead of zero based, so we need
        to compensate. I know I've created bugs in here somehow.
        Confoundingly, inputs of 0 are still acceptable, and should move to
        the beginning of the row/column as if they were 1. *sigh*
        """

        if row == 0:
            row = 1
        if column == 0:
            column = 1

        self.y = min(row - 1, self.size[0] - 1)
        self.x = min(column - 1, self.size[1] - 1)


Instruction:
Explain what the following Python 3 code does
def _text_attr(self, attr):
        attr = text[attr]
        if attr == "reset":
            self.cursor_attributes = self.default_attributes
        elif attr == "underline-off":
            self.cursor_attributes = self._remove_text_attr("underline")
        elif attr == "blink-off":
            self.cursor_attributes = self._remove_text_attr("blink")
        elif attr == "reverse-off":
            self.cursor_attributes = self._remove_text_attr("reverse")
        else:
            self.cursor_attributes = self._add_text_attr(attr)

Response: Given a text attribute set the current cursor appropriately.


Instruction:
Explain what the following Python 3 code does
def _color_attr(self, ground, attr):
        attr = colors[ground][attr]
        attrs = self.cursor_attributes
        if ground == "foreground":
            self.cursor_attributes = (attrs[0], attr, attrs[2])
        elif ground == "background":
            self.cursor_attributes = (attrs[0], attrs[1], attr)

Response: Given a color attribute set the current cursor appropriately.


Instruction:
Write a Python 3 script to
set the current cursor attributes appropriately.

Response:
def _set_attr(self, attr):
        """
        Given some text attribute, set the current cursor attributes
        appropriately.
        """
        if attr in text:
            self._text_attr(attr)
        elif attr in colors["foreground"]:
            self._color_attr("foreground", attr)
        elif attr in colors["background"]:
            self._color_attr("background", attr)


Instruction:
Make a summary of the following Python 3 code
def _select_graphic_rendition(self, *attrs):

        if len(attrs) == 0:
            # No arguments means that we're really trying to do a reset.
            attrs = [0]

        for attr in attrs:
            self._set_attr(attr)

Response: Select the current text attribute.


Instruction:
Write a Python 3 function for
returning the : class : ~flatdict. FlatDict as a dict

Response:
def as_dict(self):
        """Return the :class:`~flatdict.FlatDict` as a :class:`dict`

        :rtype: dict

        """
        out = dict({})
        for key in self.keys():
            if self._has_delimiter(key):
                pk, ck = key.split(self._delimiter, 1)
                if self._has_delimiter(ck):
                    ck = ck.split(self._delimiter, 1)[0]
                if isinstance(self._values[pk], FlatDict) and pk not in out:
                    out[pk] = dict()
                if isinstance(self._values[pk][ck], FlatDict):
                    out[pk][ck] = self._values[pk][ck].as_dict()
                else:
                    out[pk][ck] = self._values[pk][ck]
            else:
                out[key] = self._values[key]
        return out


Instruction:
Given the following Python 3 function, write the documentation
def keys(self):
        keys = []
        for key, value in self._values.items():
            if isinstance(value, (FlatDict, dict)):
                nested = [self._delimiter.join([key, k]) for k in value.keys()]
                keys += nested if nested else [key]
            else:
                keys.append(key)
        return sorted(keys)

Response: Return a copy of the flat dictionary s list of keys.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pop(self, key, default=NO_DEFAULT):
        if key not in self and default != NO_DEFAULT:
            return default
        value = self[key]
        self.__delitem__(key)
        return value

Response: Removes the key from the flat dictionary and returns its value. If default is given the key is returned. If default is given the value is returned.


Instruction:
Given the following Python 3 function, write the documentation
def set_delimiter(self, delimiter):
        for key in self.keys():
            if delimiter in key:
                raise ValueError('Key {!r} collides with delimiter {!r}', key,
                                 delimiter)
        self._delimiter = delimiter
        for key in self._values.keys():
            if isinstance(self._values[key], FlatDict):
                self._values[key].set_delimiter(delimiter)

Response: Override the default or passed in delimiter with a new value. If the delimiter already exists in a key an exception will be raised.


Instruction:
Given the following Python 3 function, write the documentation
def as_dict(self):
        out = dict({})
        for key in self.keys():
            if self._has_delimiter(key):
                pk, ck = key.split(self._delimiter, 1)
                if self._has_delimiter(ck):
                    ck = ck.split(self._delimiter, 1)[0]
                if isinstance(self._values[pk], FlatterDict) and pk not in out:
                    out[pk] = dict()
                if isinstance(self._values[pk][ck], FlatterDict):
                    if self._values[pk][ck].original_type == tuple:
                        out[pk][ck] = tuple(self._child_as_list(pk, ck))
                    elif self._values[pk][ck].original_type == list:
                        out[pk][ck] = self._child_as_list(pk, ck)
                    elif self._values[pk][ck].original_type == set:
                        out[pk][ck] = set(self._child_as_list(pk, ck))
                    elif self._values[pk][ck].original_type == dict:
                        out[pk][ck] = self._values[pk][ck].as_dict()
                else:
                    out[pk][ck] = self._values[pk][ck]
            else:
                out[key] = self._values[key]
        return out

Response: Return the FlatterDict as a nested dict.


Instruction:
Can you write a function in Python 3 where it
returns a list of values from the child FlatterDict instance with string based integer keys.

Response:
def _child_as_list(self, pk, ck):
        """Returns a list of values from the child FlatterDict instance
        with string based integer keys.

        :param str pk: The parent key
        :param str ck: The child key
        :rtype: list

        """
        return [self._values[pk][ck][k]
                for k in sorted(self._values[pk][ck].keys(),
                                key=lambda x: int(x))]


Instruction:
Implement a function in Python 3 to
generate an SQL query for the edge object.

Response:
def gen_query(self):
        """
        Generate an SQL query for the edge object.
        """
        return (
            SQL.forwards_relation(self.src, self.rel) if self.dst is None else
            SQL.inverse_relation(self.dst, self.rel)
            )


Instruction:
Make a summary of the following Python 3 code
def derived(self, statement, params=(), replace=False):
        return Query(
            db=self.db,
            sql=(statement,) if replace else self.sql + (statement,),
            params=self.params + params,
        )

Response:
Returns a new Query object set up correctly with
            the statement and params appended to the end
            s internal query and params.


Instruction:
How would you code a function in Python 3 to
traverse the graph and select the destination nodes for a particular relation.

Response:
def traverse(self, edge):
        """
        Traverse the graph, and selecting the destination
        nodes for a particular relation that the selected
        nodes are a source of, i.e. select the friends of
        my friends. You can traverse indefinitely.

        :param edge: The edge query. If the edge's
            destination node is specified then the source
            nodes will be selected.
        """
        query = self.statement
        rel, dst = edge.rel, edge.dst
        statement, params = (
            SQL.compound_fwd_query(query, rel) if dst is None else
            SQL.compound_inv_query(query, rel, dst)
        )
        return self.derived(statement, params, replace=True)


Instruction:
Can you generate the documentation for the following Python 3 function
def setup_sql(self, graphs):
        with closing(self.db.cursor()) as cursor:
            for table in graphs:
                cursor.execute(SQL.CREATE_TABLE % (table))
                for index in SQL.INDEXES:
                    cursor.execute(index % (table))
            self.db.commit()

Response: Sets up the SQL tables for the object and creates indexes as well.


Instruction:
How would you explain what the following Python 3 function does
def remove(src, rel, dst):
    smt = 'DELETE FROM %s' % rel
    queries = []
    params = []

    if src is not None:
        queries.append('src = ?')
        params.append(src)

    if dst is not None:
        queries.append('dst = ?')
        params.append(dst)

    if not queries:
        return smt, params
    smt = '%s WHERE %s' % (smt, ' AND '.join(queries))
    return smt, params

Response: Returns a SQL statement that removes edges from the SQL backing store. Either src or dst may be specified even both.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def limit(lower, upper):
    offset = lower or 0
    lim = (upper - offset) if upper else -1
    smt = 'LIMIT %d OFFSET %d' % (lim, offset)
    return smt, ()

Response: Returns a SQlite - compliant LIMIT statement that takes the lower and upper bounds into account.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def perform_ops(self):
        with self.db:
            with closing(self.db.cursor()) as cursor:
                cursor.execute('BEGIN TRANSACTION')
                self._perform_ops(cursor)

Response: Perform the operations on the database.


Instruction:
Create a Python 3 function to
create a client from a url.

Response:
def from_url(cls, url, **kwargs):
        """Create a client from a url."""
        url = urllib3.util.parse_url(url)
        if url.host:
            kwargs.setdefault('host', url.host)

        if url.port:
            kwargs.setdefault('port', url.port)

        if url.scheme == 'https':
            kwargs.setdefault('connection_class', urllib3.HTTPSConnectionPool)

        return cls(**kwargs)


Instruction:
How would you code a function in Python 3 to
initialize connection to the nsqd.

Response:
def connect(self):
        """Initialize connection to the nsqd."""
        if self.state == DISCONNECTED:
            raise errors.NSQException('connection already closed')

        if self.is_connected:
            return

        stream = Stream(self.address, self.port, self.timeout)
        stream.connect()

        self.stream = stream
        self.state = CONNECTED
        self.send(nsq.MAGIC_V2)


Instruction:
Create a Python 3 function for
closing the underlying socket.

Response:
def close_stream(self):
        """Close the underlying socket."""
        if not self.is_connected:
            return

        self.stream.close()
        self.state = DISCONNECTED
        self.on_close.send(self)


Instruction:
Write a Python 3 function that can
read an individual response from nsqd.

Response:
def read_response(self):
        """Read an individual response from nsqd.

        :returns: tuple of the frame type and the processed data.
        """
        response = self._read_response()
        frame, data = nsq.unpack_response(response)
        self.last_response = time.time()

        if frame not in self._frame_handlers:
            raise errors.NSQFrameError('unknown frame {}'.format(frame))

        frame_handler = self._frame_handlers[frame]
        processed_data = frame_handler(data)

        return frame, processed_data


Instruction:
Implement a function in Python 3 to
update the client metadata on the server and negotiate features.

Response:
def identify(self):
        """Update client metadata on the server and negotiate features.

        :returns: nsqd response data if there was feature negotiation,
            otherwise ``None``
        """
        self.send(nsq.identify({
            # nsqd 0.2.28+
            'client_id': self.client_id,
            'hostname': self.hostname,

            # nsqd 0.2.19+
            'feature_negotiation': True,
            'heartbeat_interval': self.heartbeat_interval,

            # nsqd 0.2.21+
            'output_buffer_size': self.output_buffer_size,
            'output_buffer_timeout': self.output_buffer_timeout,

            # nsqd 0.2.22+
            'tls_v1': self.tls_v1,

            # nsqd 0.2.23+
            'snappy': self.snappy,
            'deflate': self.deflate,
            'deflate_level': self.deflate_level,

            # nsqd nsqd 0.2.25+
            'sample_rate': self.sample_rate,
            'user_agent': self.user_agent,
        }))

        frame, data = self.read_response()

        if frame == nsq.FRAME_TYPE_ERROR:
            raise data

        if data == nsq.OK:
            return

        try:
            data = json.loads(data.decode('utf-8'))

        except ValueError:
            self.close_stream()
            raise errors.NSQException(
                'failed to parse IDENTIFY response JSON from nsqd: '
                '{!r}'.format(data))

        self.max_ready_count = data.get('max_rdy_count', self.max_ready_count)

        if self.tls_v1 and data.get('tls_v1'):
            self.upgrade_to_tls()

        if self.snappy and data.get('snappy'):
            self.upgrade_to_snappy()

        elif self.deflate and data.get('deflate'):
            self.deflate_level = data.get('deflate_level', self.deflate_level)
            self.upgrade_to_defalte()

        if self.auth_secret and data.get('auth_required'):
            self.auth()

        return data


Instruction:
Here you have a function in Python 3, explain what it does
def auth(self):
        self.send(nsq.auth(self.auth_secret))
        frame, data = self.read_response()

        if frame == nsq.FRAME_TYPE_ERROR:
            raise data

        try:
            response = json.loads(data.decode('utf-8'))
        except ValueError:
            self.close_stream()
            raise errors.NSQException(
                'failed to parse AUTH response JSON from nsqd: '
                '{!r}'.format(data))

        self.on_auth.send(self, response=response)
        return response

Response: Send an auth secret to nsqd and return the response.


Instruction:
Given the following Python 3 function, write the documentation
def subscribe(self, topic, channel):
        self.send(nsq.subscribe(topic, channel))

Response: Subscribe to a nsq topic and channel.


Instruction:
How would you explain what the following Python 3 function does
def publish(self, topic, data, defer=None):
        if defer is None:
            self.send(nsq.publish(topic, data))
        else:
            self.send(nsq.deferpublish(topic, data, defer))

Response: Publish a message to the given topic over tcp.


Instruction:
Create a Python 3 function for
publishing an iterable of messages to the given topic over http.

Response:
def multipublish(self, topic, messages):
        """Publish an iterable of messages to the given topic over http.

        :param topic: the topic to publish to

        :param messages: iterable of bytestrings to publish
        """
        self.send(nsq.multipublish(topic, messages))


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ready(self, count):
        self.ready_count = count
        self.send(nsq.ready(count))

Response: Indicate you are ready to receive count messages.


Instruction:
Can you generate the documentation for the following Python 3 function
def finish(self, message_id):
        self.send(nsq.finish(message_id))
        self.finish_inflight()
        self.on_finish.send(self, message_id=message_id)

Response: Finish a message (indicate successful processing).


Instruction:
Can you create a Python 3 function that
publishes a message to the given topic over http.

Response:
def publish(self, topic, data, defer=None):
        """Publish a message to the given topic over http.

        :param topic: the topic to publish to

        :param data: bytestring data to publish

        :param defer: duration in millisconds to defer before publishing
            (requires nsq 0.3.6)
        """
        nsq.assert_valid_topic_name(topic)
        fields = {'topic': topic}

        if defer is not None:
            fields['defer'] = '{}'.format(defer)

        return self._request('POST', '/pub', fields=fields, body=data)


Instruction:
Write a Python 3 function for
publishing an iterable of messages to the given topic over http.

Response:
def multipublish(self, topic, messages, binary=False):
        """Publish an iterable of messages to the given topic over http.

        :param topic: the topic to publish to

        :param messages: iterable of bytestrings to publish

        :param binary: enable binary mode. defaults to False
            (requires nsq 1.0.0)

        By default multipublish expects messages to be delimited by ``"\\n"``,
        use the binary flag to enable binary mode where the POST body is
        expected to be in the following wire protocol format.
        """
        nsq.assert_valid_topic_name(topic)
        fields = {'topic': topic}

        if binary:
            fields['binary'] = 'true'
            body = nsq.multipublish_body(messages)
        else:
            body = b'\n'.join(self._validate_mpub_message(m) for m in messages)

        return self._request('POST', '/mpub', fields=fields, body=body)


Instruction:
Write a Python 3 script to
empty all the queued messages for an existing topic.

Response:
def empty_topic(self, topic):
        """Empty all the queued messages for an existing topic."""
        nsq.assert_valid_topic_name(topic)
        return self._request('POST', '/topic/empty', fields={'topic': topic})


Instruction:
Write a Python 3 function for
emptying all the queued messages for an existing channel.

Response:
def empty_channel(self, topic, channel):
        """Empty all the queued messages for an existing channel."""
        nsq.assert_valid_topic_name(topic)
        nsq.assert_valid_channel_name(channel)
        return self._request('POST', '/channel/empty',
                             fields={'topic': topic, 'channel': channel})


Instruction:
How would you implement a function in Python 3 that
pauses message flow to all channels on an existing topic.

Response:
def pause_topic(self, topic):
        """Pause message flow to all channels on an existing topic.

        Messages will queue at topic.
        """
        nsq.assert_valid_topic_name(topic)
        return self._request('POST', '/topic/pause', fields={'topic': topic})


Instruction:
How would you implement a function in Python 3 that
resumes message flow to channels of an existing paused topic.

Response:
def unpause_topic(self, topic):
        """Resume message flow to channels of an existing, paused, topic."""
        nsq.assert_valid_topic_name(topic)
        return self._request('POST', '/topic/unpause', fields={'topic': topic})


Instruction:
How would you implement a function in Python 3 that
returns internal instrumented statistics.

Response:
def stats(self, topic=None, channel=None, text=False):
        """Return internal instrumented statistics.

        :param topic: (optional) filter to topic

        :param channel: (optional) filter to channel

        :param text: return the stats as a string (default: ``False``)
        """
        if text:
            fields = {'format': 'text'}
        else:
            fields = {'format': 'json'}

        if topic:
            nsq.assert_valid_topic_name(topic)
            fields['topic'] = topic

        if channel:
            nsq.assert_valid_channel_name(channel)
            fields['channel'] = channel

        return self._request('GET', '/stats', fields=fields)


Instruction:
Can you write a function in Python 3 where it
publishes data to a topic.

Response:
def publish_tcp(self, topic, data, **kwargs):
        """Use :meth:`NsqdTCPClient.publish` instead.

        .. deprecated:: 1.0.0
        """
        return self.__tcp_client.publish(topic, data, **kwargs)


Instruction:
Given the following Python 3 function, write the documentation
def publish_http(self, topic, data, **kwargs):
        self.__http_client.publish(topic, data, **kwargs)

Response: Deprecated use nsqd. HTTPClient. publish instead.


Instruction:
How would you code a function in Python 3 to
use this method to publish TCP messages to a topic.

Response:
def multipublish_tcp(self, topic, messages, **kwargs):
        """Use :meth:`NsqdTCPClient.multipublish` instead.

        .. deprecated:: 1.0.0
        """
        return self.__tcp_client.multipublish(topic, messages, **kwargs)


Instruction:
Write a Python 3 function that can
use the HTTP client to publish a set of messages.

Response:
def multipublish_http(self, topic, messages, **kwargs):
        """Use :meth:`NsqdHTTPClient.multipublish` instead.

        .. deprecated:: 1.0.0
        """
        return self.__http_client.multipublish(topic, messages, **kwargs)


Instruction:
Make a summary of the following Python 3 code
def start(self):
        if self._state == CLOSED:
            raise NSQException('producer already closed')

        if self.is_running:
            self.logger.warn('producer already started')
            return

        self.logger.debug('starting producer...')
        self._state = RUNNING

        for address in self.nsqd_tcp_addresses:
            address, port = address.split(':')
            self.connect_to_nsqd(address, int(port))

Response: Start discovering and listing to connections.


Instruction:
Write a Python 3 function that can
block until all connections have closed and workers are stopped.

Response:
def join(self, timeout=None, raise_error=False):
        """Block until all connections have closed and workers stopped."""
        self._workers.join(timeout, raise_error)


Instruction:
Write a Python 3 function for
publishing a message to the given topic.

Response:
def publish(self, topic, data, defer=None, block=True, timeout=None,
                raise_error=True):
        """Publish a message to the given topic.

        :param topic: the topic to publish to

        :param data: bytestring data to publish

        :param defer: duration in milliseconds to defer before publishing
            (requires nsq 0.3.6)

        :param block: wait for a connection to become available before
            publishing the message. If block is `False` and no connections
            are available, :class:`~gnsq.errors.NSQNoConnections` is raised

        :param timeout: if timeout is a positive number, it blocks at most
            ``timeout`` seconds before raising
            :class:`~gnsq.errors.NSQNoConnections`

        :param raise_error: if ``True``, it blocks until a response is received
            from the nsqd server, and any error response is raised. Otherwise
            an :class:`~gevent.event.AsyncResult` is returned
        """
        result = AsyncResult()
        conn = self._get_connection(block=block, timeout=timeout)

        try:
            self._response_queues[conn].append(result)
            conn.publish(topic, data, defer=defer)
        finally:
            self._put_connection(conn)

        if raise_error:
            return result.get()

        return result


Instruction:
Write a Python 3 function for
publishing an iterable of messages to the given topic.

Response:
def multipublish(self, topic, messages, block=True, timeout=None,
                     raise_error=True):
        """Publish an iterable of messages to the given topic.

        :param topic: the topic to publish to

        :param messages: iterable of bytestrings to publish

        :param block: wait for a connection to become available before
            publishing the message. If block is `False` and no connections
            are available, :class:`~gnsq.errors.NSQNoConnections` is raised

        :param timeout: if timeout is a positive number, it blocks at most
            ``timeout`` seconds before raising
            :class:`~gnsq.errors.NSQNoConnections`

        :param raise_error: if ``True``, it blocks until a response is received
            from the nsqd server, and any error response is raised. Otherwise
            an :class:`~gevent.event.AsyncResult` is returned
        """
        result = AsyncResult()
        conn = self._get_connection(block=block, timeout=timeout)

        try:
            self._response_queues[conn].append(result)
            conn.multipublish(topic, messages)
        finally:
            self._put_connection(conn)

        if raise_error:
            return result.get()

        return result


Instruction:
Create a Python 3 function to
respond to nsqd that this message was successfully processed.

Response:
def finish(self):
        """
        Respond to nsqd that you’ve processed this message successfully
        (or would like to silently discard it).
        """
        if self._has_responded:
            raise NSQException('already responded')
        self._has_responded = True
        self.on_finish.send(self)


Instruction:
Implement a Python 3 function for
responding to nsqd that this message was successfully processed.

Response:
def requeue(self, time_ms=0, backoff=True):
        """
        Respond to nsqd that you’ve failed to process this message successfully
        (and would like it to be requeued).
        """
        if self._has_responded:
            raise NSQException('already responded')
        self._has_responded = True
        self.on_requeue.send(self, timeout=time_ms, backoff=backoff)


Instruction:
Can you create a Python 3 function that
returns producers for a topic.

Response:
def lookup(self, topic):
        """Returns producers for a topic."""
        nsq.assert_valid_topic_name(topic)
        return self._request('GET', '/lookup', fields={'topic': topic})


Instruction:
Explain what the following Python 3 code does
def channels(self, topic):
        nsq.assert_valid_topic_name(topic)
        return self._request('GET', '/channels', fields={'topic': topic})

Response: Returns all known channels of a topic.


Instruction:
Given the following Python 3 function, write the documentation
def tombstone_topic(self, topic, node):
        nsq.assert_valid_topic_name(topic)
        return self._request('POST', '/topic/tombstone',
                             fields={'topic': topic, 'node': node})

Response: Tombstones a specific producer of an existing topic.


Instruction:
Explain what the following Python 3 code does
def start(self, block=True):
        if self._state == INIT:
            if not any(self.on_message.receivers_for(blinker.ANY)):
                raise RuntimeError('no receivers connected to on_message')

            self.logger.debug('starting %s...', self.name)
            self._state = RUNNING
            self.query_nsqd()

            if self.lookupds:
                self.query_lookupd()
                self._killables.add(self._workers.spawn(self._poll_lookupd))

            self._killables.add(self._workers.spawn(self._poll_ready))

        else:
            self.logger.warn('%s already started', self.name)

        if block:
            self.join()

Response: Start discovering and listing to connections.


Instruction:
Here you have a function in Python 3, explain what it does
def publish(self, topic, message):
        if not self.connections:
            raise NSQNoConnections()
        conn = random.choice(list(self.connections))
        conn.publish(topic, message)

Response: Use : class : ~gnsq. Producer instead.


Instruction:
Explain what the following Python 3 code does
def deprecated(fn):
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        warnings.warn(fn.__doc__.split('\n')[0],
                      category=DeprecationWarning, stacklevel=2)
        return fn(*args, **kwargs)
    return wrapper

Response: Mark a function as deprecated and warn the user on use.


Instruction:
Given the following Python 3 function, write the documentation
def _new_lnotab(instrs, lnotab):
    return {
        lno: _a_if_not_none(instr._stolen_by, instr)
        for lno, instr in lnotab.items()
    }

Response: Returns a new lnotab after the instructions have been transformed.


Instruction:
Can you tell what is the following Python 3 function doing
def transform(self, code, *, name=None, filename=None):
        # reverse lookups from for constants and names.
        reversed_consts = {}
        reversed_names = {}
        reversed_varnames = {}
        for instr in code:
            if isinstance(instr, LOAD_CONST):
                reversed_consts[instr] = instr.arg
            if instr.uses_name:
                reversed_names[instr] = instr.arg
            if isinstance(instr, (STORE_FAST, LOAD_FAST)):
                reversed_varnames[instr] = instr.arg

        instrs, consts = tuple(zip(*reversed_consts.items())) or ((), ())
        for instr, const in zip(instrs, self.transform_consts(consts)):
            instr.arg = const

        instrs, names = tuple(zip(*reversed_names.items())) or ((), ())
        for instr, name_ in zip(instrs, self.transform_names(names)):
            instr.arg = name_

        instrs, varnames = tuple(zip(*reversed_varnames.items())) or ((), ())
        for instr, varname in zip(instrs, self.transform_varnames(varnames)):
            instr.arg = varname

        with self._new_context(code):
            post_transform = self.patterndispatcher(code)

            return Code(
                post_transform,
                code.argnames,
                cellvars=self.transform_cellvars(code.cellvars),
                freevars=self.transform_freevars(code.freevars),
                name=name if name is not None else code.name,
                filename=filename if filename is not None else code.filename,
                firstlineno=code.firstlineno,
                lnotab=_new_lnotab(post_transform, code.lnotab),
                flags=code.flags,
            )

Response: Transform a codetransformer. Code object applying the transforms.


Instruction:
Given the following Python 3 function, write the documentation
def pformat_ast(node,
                include_attributes=INCLUDE_ATTRIBUTES_DEFAULT,
                indent=INDENT_DEFAULT):
    """
    Pretty-format an AST tree element

    Parameters
    ----------
    node : ast.AST
       Top-level node to render.
    include_attributes : bool, optional
        Whether to include node attributes.  Default False.
    indent : str, optional.
        Indentation string for nested expressions.  Default is two spaces.
    """
    def _fmt(node, prefix, level):

        def with_indent(*strs):
            return ''.join(((indent * level,) + strs))

        with_prefix = partial(with_indent, prefix)

        if isinstance(node, Name):
            # Special Case:
            # Render Name nodes on a single line.
            yield with_prefix(
                type(node).__name__,
                '(id=',
                repr(node.id),
                ', ctx=',
                type(node.ctx).__name__,
                '()),',
            )

        elif isinstance(node, Num):
            # Special Case:
            # Render Num nodes on a single line without names.
            yield with_prefix(
                type(node).__name__,
                '(%r),' % node.n,
            )

        elif isinstance(node, AST):
            fields_attrs = list(
                chain(
                    iter_fields(node),
                    iter_attributes(node) if include_attributes else (),
                )
            )
            if not fields_attrs:
                # Special Case:
                # Render the whole expression on one line if there are no
                # attributes.
                yield with_prefix(type(node).__name__, '(),')
                return

            yield with_prefix(type(node).__name__, '(')
            for name, value in fields_attrs:
                yield from _fmt(value, name + '=', level + 1)
            # Put a trailing comma if we're not at the top level.
            yield with_indent(')', ',' if level > 0 else '')

        elif isinstance(node, list):
            if not node:
                # Special Case:
                # Render empty lists on one line.
                yield with_prefix('[],')
                return

            yield with_prefix('[')
            yield from chain.from_iterable(
                map(partial(_fmt, prefix='', level=level + 1), node)
            )
            yield with_indent('],')
        else:
            yield with_prefix(repr(node), ',')

    return '\n'.join(_fmt(node, prefix='', level=0))

Response: Pretty - format an AST tree element.


Instruction:
Make a summary of the following Python 3 code
def walk_code(co, _prefix=''):
    name = _prefix + co.co_name
    yield name, co
    yield from chain.from_iterable(
        walk_code(c, _prefix=_extend_name(name, co))
        for c in co.co_consts
        if isinstance(c, CodeType)
    )

Response: Walk a code object and yield all the names and code objects that are also code objects.


Instruction:
Here you have a function in Python 3, explain what it does
def d(obj, mode='exec', file=None):
    if file is None:
        file = sys.stdout

    for name, co in walk_code(extract_code(obj, compile_mode=mode)):
        print(name, file=file)
        print('-' * len(name), file=file)
        dis.dis(co, file=file)
        print('', file=file)

Response: Interactive convenience for displaying the disassembly of a function module or code string.


Instruction:
Can you generate the documentation for the following Python 3 function
def display(text, mode='exec', file=None):

    if file is None:
        file = sys.stdout

    ast_section = StringIO()
    a(text, mode=mode, file=ast_section)

    code_section = StringIO()
    d(text, mode=mode, file=code_section)

    rendered = _DISPLAY_TEMPLATE.format(
        text=text,
        ast=ast_section.getvalue(),
        code=code_section.getvalue(),
    )
    print(rendered, file=file)

Response: Display text as AST and Bytecode.