Instruction:
How would you implement a function in Python 3 that
loads YAML and JSON configs and begin creating or updating aggregating and pushing the repos

Response:
def load_aggregate(args):
    """Load YAML and JSON configs and begin creating / updating , aggregating
    and pushing the repos (deprecated in favor or run())"""
    repos = load_config(args.config, args.expand_env)
    dirmatch = args.dirmatch
    for repo_dict in repos:
        r = Repo(**repo_dict)
        logger.debug('%s' % r)
        if not match_dir(r.cwd, dirmatch):
            logger.info("Skip %s", r.cwd)
            continue
        r.aggregate()
        if args.do_push:
            r.push()


Instruction:
Create a Python 3 function to
aggregate one repository according to the args.

Response:
def aggregate_repo(repo, args, sem, err_queue):
    """Aggregate one repo according to the args.

    Args:
         repo (Repo): The repository to aggregate.
         args (argparse.Namespace): CLI arguments.
    """
    try:
        logger.debug('%s' % repo)
        dirmatch = args.dirmatch
        if not match_dir(repo.cwd, dirmatch):
            logger.info("Skip %s", repo.cwd)
            return
        if args.command == 'aggregate':
            repo.aggregate()
            if args.do_push:
                repo.push()
        elif args.command == 'show-closed-prs':
            repo.show_closed_prs()
        elif args.command == 'show-all-prs':
            repo.show_all_prs()
    except Exception:
        err_queue.put_nowait(sys.exc_info())
    finally:
        sem.release()


Instruction:
Make a summary of the following Python 3 code
def run(args):

    repos = load_config(args.config, args.expand_env, args.force)

    jobs = max(args.jobs, 1)
    threads = []
    sem = threading.Semaphore(jobs)
    err_queue = Queue()

    for repo_dict in repos:
        if not err_queue.empty():
            break

        sem.acquire()
        r = Repo(**repo_dict)
        tname = os.path.basename(repo_dict['cwd'])

        if jobs > 1:
            t = threading.Thread(
                target=aggregate_repo, args=(r, args, sem, err_queue))
            t.daemon = True
            t.name = tname
            threads.append(t)
            t.start()
        else:
            with ThreadNameKeeper():
                threading.current_thread().name = tname
                aggregate_repo(r, args, sem, err_queue)

    for t in threads:
        t.join()

    if not err_queue.empty():
        while True:
            try:
                exc_type, exc_obj, exc_trace = err_queue.get_nowait()
            except EmptyQueue:
                break
            traceback.print_exception(exc_type, exc_obj, exc_trace)
        sys.exit(1)

Response:
Load YAML and JSON configs and run the command specified
    in args. command


Instruction:
Can you generate a brief explanation for the following Python 3 code
def has_no_error(
    state, incorrect_msg="Your code generated an error. Fix it and try again!"
):
    """Check whether the submission did not generate a runtime error.

    Simply use ``Ex().has_no_error()`` in your SCT whenever you want to check for errors.
    By default, after the entire SCT finished executing, ``sqlwhat`` will check
    for errors before marking the exercise as correct. You can disable this behavior
    by using ``Ex().allow_error()``.

    Args:
        incorrect_msg: If specified, this overrides the automatically generated feedback message
                       in case the student's query did not return a result.
    """

    if state.reporter.get_errors():
        state.do_test(incorrect_msg)

    return state

Response: Check whether the submission did not generate an error.


Instruction:
Create a Python 3 function to
check if the student s query returned a result.

Response:
def has_result(state, incorrect_msg="Your query did not return a result."):
    """Checks if the student's query returned a result.

    Args:
        incorrect_msg: If specified, this overrides the automatically generated feedback message
                       in case the student's query did not return a result.
    """

    # first check if there is no error
    has_no_error(state)

    if not state.solution_result:
        raise NameError(
            "You are using has_result() to verify that the student query generated an error, but the solution query did not return a result either!"
        )

    if not state.student_result:
        state.do_test(incorrect_msg)

    return state


Instruction:
Write a Python 3 script to
test whether the student and solution query results have equal numbers of rows.

Response:
def has_nrows(
    state,
    incorrect_msg="Your query returned a table with {{n_stu}} row{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} row{{'s' if n_sol > 1 else ''}}.",
):
    """Test whether the student and solution query results have equal numbers of rows.

    Args:
        incorrect_msg: If specified, this overrides the automatically generated feedback message
                       in case the number of rows in the student and solution query don't match.
    """

    # check that query returned something
    has_result(state)

    # assumes that columns cannot be jagged in size
    n_stu = len(next(iter(state.student_result.values())))
    n_sol = len(next(iter(state.solution_result.values())))

    if n_stu != n_sol:
        _msg = state.build_message(
            incorrect_msg, fmt_kwargs={"n_stu": n_stu, "n_sol": n_sol}
        )
        state.do_test(_msg)

    return state


Instruction:
Can you create a Python 3 function that
tests whether the student and solution query results have equal numbers of columns.

Response:
def has_ncols(
    state,
    incorrect_msg="Your query returned a table with {{n_stu}} column{{'s' if n_stu > 1 else ''}} while it should return a table with {{n_sol}} column{{'s' if n_sol > 1 else ''}}.",
):
    """Test whether the student and solution query results have equal numbers of columns.

    Args:
        incorrect_msg: If specified, this overrides the automatically generated feedback message
                       in case the number of columns in the student and solution query don't match.

    :Example:

        Consider the following solution and SCT: ::

            # solution
            SELECT artist_id as id, name FROM artists

            # sct
            Ex().has_ncols()

            # passing submission
            SELECT artist_id as id, name FROM artists

            # failing submission (too little columns)
            SELECT artist_id as id FROM artists

            # passing submission (two columns, even though not correct ones)
            SELECT artist_id, label FROM artists

    """

    # check that query returned something
    has_result(state)

    n_stu = len(state.student_result)
    n_sol = len(state.solution_result)

    if n_stu != n_sol:
        _msg = state.build_message(
            incorrect_msg, fmt_kwargs={"n_stu": n_stu, "n_sol": n_sol}
        )
        state.do_test(_msg)

    return state


Instruction:
Implement a Python 3 function for
checking that a particular row in the query result is represented as a single - row query result.

Response:
def check_row(state, index, missing_msg=None, expand_msg=None):
    """Zoom in on a particular row in the query result, by index.

    After zooming in on a row, which is represented as a single-row query result,
    you can use ``has_equal_value()`` to verify whether all columns in the zoomed in solution
    query result have a match in the student query result.

    Args:
        index: index of the row to zoom in on (zero-based indexed).
        missing_msg: if specified, this overrides the automatically generated feedback
                     message in case the row is missing in the student query result.
        expand_msg: if specified, this overrides the automatically generated feedback
                    message that is prepended to feedback messages that are thrown
                    further in the SCT chain.

    :Example:

        Suppose we are testing the following SELECT statements

        * solution: ``SELECT artist_id as id, name FROM artists LIMIT 5``
        * student : ``SELECT artist_id, name       FROM artists LIMIT 2``

        We can write the following SCTs: ::

            # fails, since row 3 at index 2 is not in the student result
            Ex().check_row(2)

            # passes, since row 2 at index 1 is in the student result
            Ex().check_row(0)

    """

    if missing_msg is None:
        missing_msg = "The system wants to verify row {{index + 1}} of your query result, but couldn't find it. Have another look."
    if expand_msg is None:
        expand_msg = "Have another look at row {{index + 1}} in your query result. "
    msg_kwargs = {"index": index}

    # check that query returned something
    has_result(state)

    stu_res = state.student_result
    sol_res = state.solution_result

    n_sol = len(next(iter(sol_res.values())))
    n_stu = len(next(iter(stu_res.values())))

    if index >= n_sol:
        raise BaseException(
            "There are only {} rows in the solution query result, and you're trying to fetch the row at index {}".format(
                n_sol, index
            )
        )

    if index >= n_stu:
        _msg = state.build_message(missing_msg, fmt_kwargs=msg_kwargs)
        state.do_test(_msg)

    return state.to_child(
        append_message={"msg": expand_msg, "kwargs": msg_kwargs},
        student_result={k: [v[index]] for k, v in stu_res.items()},
        solution_result={k: [v[index]] for k, v in sol_res.items()},
    )


Instruction:
Given the following Python 3 function, write the documentation
def check_column(state, name, missing_msg=None, expand_msg=None):

    if missing_msg is None:
        missing_msg = "We expected to find a column named `{{name}}` in the result of your query, but couldn't."
    if expand_msg is None:
        expand_msg = "Have another look at your query result. "
    msg_kwargs = {"name": name}

    # check that query returned something
    has_result(state)

    stu_res = state.student_result
    sol_res = state.solution_result

    if name not in sol_res:
        raise BaseException("name %s not in solution column names" % name)

    if name not in stu_res:
        _msg = state.build_message(missing_msg, fmt_kwargs=msg_kwargs)
        state.do_test(_msg)

    return state.to_child(
        append_message={"msg": expand_msg, "kwargs": msg_kwargs},
        student_result={name: stu_res[name]},
        solution_result={name: sol_res[name]},
    )

Response: Zoom in on a particular column in the query result.


Instruction:
Can you generate the documentation for the following Python 3 function
def check_all_columns(state, allow_extra=True, too_many_cols_msg=None, expand_msg=None):

    if too_many_cols_msg is None:
        too_many_cols_msg = (
            "Your query result contains the column {{col}} but shouldn't."
        )
    if expand_msg is None:
        expand_msg = "Have another look at your query result. "

    child_stu_result = {}
    child_sol_result = {}

    for col in state.solution_result:
        child = check_column(state, col)
        child_stu_result.update(**child.student_result)
        child_sol_result.update(**child.solution_result)

    cols_not_in_sol = list(
        set(state.student_result.keys()) - set(child_stu_result.keys())
    )
    if not allow_extra and len(cols_not_in_sol) > 0:
        _msg = state.build_message(
            "Your query result contains the column `{{col}}` but shouldn't.",
            fmt_kwargs={"col": cols_not_in_sol[0]},
        )
        state.do_test(_msg)

    return state.to_child(
        append_message={"msg": expand_msg, "kwargs": {}},
        student_result=child_stu_result,
        solution_result=child_sol_result,
    )

Response: This function checks all columns in the student query result.


Instruction:
Write a Python 3 function that can
verify if a student and solution query result match up.

Response:
def has_equal_value(state, ordered=False, ndigits=None, incorrect_msg=None):
    """Verify if a student and solution query result match up.

    This function must always be used after 'zooming' in on certain columns or records (check_column, check_row or check_result).
    ``has_equal_value`` then goes over all columns that are still left in the solution query result, and compares each column with the
    corresponding column in the student query result.

    Args:
        ordered: if set to False, the default, all rows are sorted (according
                 to the first column and the following columns as tie breakers).
                 if set to True, the order of rows in student and solution query have to match.
        digits: if specified, number of decimals to use when comparing column values.
        incorrect_msg: if specified, this overrides the automatically generated feedback
                       message in case a column in the student query result does not match
                       a column in the solution query result.

    :Example:

        Suppose we are testing the following SELECT statements

        * solution: ``SELECT artist_id as id, name FROM artists ORDER BY name``
        * student : ``SELECT artist_id, name       FROM artists``

        We can write the following SCTs: ::

            # passes, as order is not important by default
            Ex().check_column('name').has_equal_value()

            # fails, as order is deemed important
            Ex().check_column('name').has_equal_value(ordered=True)

            # check_column fails, as id is not in the student query result
            Ex().check_column('id').has_equal_value()

            # check_all_columns fails, as id not in the student query result
            Ex().check_all_columns().has_equal_value()
    """

    if not hasattr(state, "parent"):
        raise ValueError(
            "You can only use has_equal_value() on the state resulting from check_column, check_row or check_result."
        )

    if incorrect_msg is None:
        incorrect_msg = "Column `{{col}}` seems to be incorrect.{{' Make sure you arranged the rows correctly.' if ordered else ''}}"

    # First of all, check if number of rows correspond
    has_nrows(state)

    if not ordered:
        stu_res, sol_res = sort_rows(state)
    else:
        stu_res = state.student_result
        sol_res = state.solution_result

    for sol_col_name, sol_col_vals in sol_res.items():
        stu_col_vals = stu_res[sol_col_name]
        if ndigits is not None:
            try:
                sol_col_vals = round_seq(sol_col_vals, ndigits)
                stu_col_vals = round_seq(stu_col_vals, ndigits)
            except:
                pass

        if sol_col_vals != stu_col_vals:
            _msg = state.build_message(
                incorrect_msg, fmt_kwargs={"col": sol_col_name, "ordered": ordered}
            )
            state.do_test(_msg)

    return state


Instruction:
Can you tell what is the following Python 3 function doing
def lowercase(state):
    return state.to_child(
        student_result={k.lower(): v for k, v in state.student_result.items()},
        solution_result={k.lower(): v for k, v in state.solution_result.items()},
    )

Response: Convert all column names to their lower case versions to improve robustness


Instruction:
Given the following Python 3 function, write the documentation
def check_result(state):

    state1 = lowercase(state)
    state2 = check_all_columns(state1)
    has_equal_value(state2)
    return state2

Response: High level function which wraps other SCTs for checking results.


Instruction:
Given the following Python 3 function, write the documentation
def check_query(state, query, error_msg=None, expand_msg=None):

    if error_msg is None:
        error_msg = "Running `{{query}}` after your submission generated an error."
    if expand_msg is None:
        expand_msg = "The autograder verified the result of running `{{query}}` against the database. "

    msg_kwargs = {"query": query}

    # before redoing the query,
    # make sure that it didn't generate any errors
    has_no_error(state)

    _msg = state.build_message(error_msg, fmt_kwargs=msg_kwargs)

    # sqlbackend makes sure all queries are run in transactions.
    # Rerun the solution code first, after which we run the provided query
    with dbconn(state.solution_conn) as conn:
        _ = runQuery(conn, state.solution_code)
        sol_res = runQuery(conn, query)

    if sol_res is None:
        raise ValueError("Solution failed: " + _msg)

    # sqlbackend makes sure all queries are run in transactions.
    # Rerun the student code first, after wich we run the provided query
    with dbconn(state.student_conn) as conn:
        _ = runQuery(conn, state.student_code)
        stu_res = runQuery(conn, query)

    if stu_res is None:
        state.do_test(_msg)

    return state.to_child(
        append_message={"msg": expand_msg, "kwargs": msg_kwargs},
        student_result=stu_res,
        solution_result=sol_res,
    )

Response: Run arbitrary queries against the database and return the results.


Instruction:
How would you explain what the following Python 3 function does
def print_err(*args, **kwargs):
    if kwargs.get('file', None) is None:
        kwargs['file'] = sys.stderr
    print(*args, **kwargs)

Response: A wrapper for print that uses stderr by default.


Instruction:
How would you code a function in Python 3 to
walk a directory and print status updates along the way.

Response:
def walk_dir_animated(path, maxdircnt=1000):
    """ Walk a directory, printing status updates along the way. """
    p = AnimatedProgress(
        'Walking {}...'.format(path),
        frames=Frames.dots_orbit.as_rainbow(),
        show_time=True,
    )
    rootcnt = 0
    print('\nStarting animated progress.')
    with p:
        for root, dirs, files in os.walk(path):
            rootcnt += 1
            if rootcnt % 50 == 0:
                p.text = 'Walking {}...'.format(C(root, 'cyan'))
            if rootcnt > maxdircnt:
                # Stop is called because we are printing before the
                # AnimatedProgress is finished running.
                p.stop()
                print('\nFinished walking {} directories.'.format(
                    C(maxdircnt, 'blue', style='bright')
                ))
                break
        else:
            # AnimatedProgress still running, `stop` it before printing.
            p.stop()
            print_err('\nNever made it to {} directories ({}).'.format(
                C(maxdircnt, 'blue', style='bright'),
                C(rootcnt, 'red', style='bright'),
            ))
    print('\nFinished with animated progress.')
    return 0


Instruction:
Explain what the following Python 3 code does
def walk_dir_progress(path, maxdircnt=5000, file=sys.stdout):
    p = ProgressBar(
        'Walking {}'.format(C(path, 'cyan')),
        bars=Bars.numbers_blue.with_wrapper(('(', ')')),
        show_time=True,
        file=file,
    )
    rootcnt = 0
    print('\nStarting progress bar...')
    p.start()

    for root, dirs, files in os.walk(path):
        rootcnt += 1
        if rootcnt % 100 == 0:
            p.update(
                percent=min((rootcnt / maxdircnt) * 100, 100),
                text='Walking {}...'.format(
                    C(os.path.split(root)[-1], 'cyan'),
                )
            )

        if rootcnt > maxdircnt:
            # Stop is called because we are printing before the
            # AnimatedProgress is finished running.
            p.stop()
            print(
                '\nFinished walking {} directories.'.format(
                    C(maxdircnt, 'blue', style='bright')
                ),
                file=file,
            )
            break
    else:
        # AnimatedProgress still running, `stop` it before printing.
        p.stop()
        print_err(
            '\nNever made it to {} directories ({}).'.format(
                C(maxdircnt, 'blue', style='bright'),
                C(rootcnt, 'red', style='bright'),
            )
        )
    print('\nFinished with progress bar.')
    return 0

Response: Walk a directory and print progress updates along the way.


Instruction:
How would you explain what the following Python 3 function does
def _coloredhelp(s):
    newlines = []
    bigindent = (' ' * 16)
    in_opts = False
    for line in s.split('\n'):
        linestripped = line.strip('\n').strip().strip(':')
        if linestripped == 'Usage':
            # label
            line = line.replace('Usage', str(C('Usage', **ARGS_LABEL)))
        elif linestripped == 'Options':
            line = line.replace('Options', str(C('Options', **ARGS_LABEL)))
            in_opts = True
        elif (':' in line) and (not line.startswith(bigindent)):
            # opt,desc line. colorize it.
            lineparts = line.split(':')
            opt = lineparts[0]
            vals = [lineparts[1]] if len(lineparts) == 2 else lineparts[1:]

            # colorize opt
            if ',' in opt:
                opts = opt.split(',')
            else:
                opts = [opt]
            optstr = ','.join(str(C(o, **ARGS_OPTIONS)) for o in opts)

            # colorize desc
            valstr = ':'.join(str(C(val, **ARGS_DESC)) for val in vals)
            line = ':'.join((optstr, valstr))
        elif in_opts and line.startswith(bigindent):
            # continued desc string..
            # Make any 'Default:Value' parts look the same as the opt,desc.

            line = ':'.join(str(C(s, **ARGS_DESC)) for s in line.split(':'))
        elif (not line.startswith('    ')):
            # header line.
            line = str(C(line, **ARGS_HEADER))
        else:
            # Everything else, usage mainly.
            if SCRIPT:
                line = line.replace(SCRIPT, str(C(SCRIPT, **ARGS_SCRIPT)))

        newlines.append(
            '{}{}'.format(line, C('', style='reset_all'))
        )
    return '\n'.join(newlines)

Response: Colorize the usage string for docopt


Instruction:
How would you explain what the following Python 3 function does
def docopt(
        doc, argv=None, help=True, version=None, options_first=False,
        script=None, colors=None):
    """
This is a wrapper for docopt.docopt that also sets SCRIPT to `script`.
    When SCRIPT is set, it can be colorized for the usage string.
    A dict of Colr options can be passed with `colors` to alter the
    styles.
    Available color options keys:
        desc     : Colr args for the description of options.
        label    : Colr args for the 'Usage:' and 'Options:' labels.
        header   : Colr args for the top line (program name), and any
                   other line that is not indented at all.
        options  : Colr args for the options themselves ('-h,--help').
        script   : Colr args for the script name, if found in the usage
                   text.
        version  : Colr args for the version when --version is used.

    Example:
        # `colors` only updates the default settings. You must override
        # them to change ALL the settings.
        argd = docopt(
            ...,
            script=SCRIPT,
            colors={'script': {'fore': 'red'}}
        )

Original docopt documentation follows:
    """
    # docopt documentation is appended programmatically after this func def.

    global SCRIPT
    global ARGS_DESC, ARGS_HEADER, ARGS_LABEL, ARGS_OPTIONS
    global ARGS_SCRIPT, ARGS_VERSION

    SCRIPT = script
    if colors:
        # Setup colors, if any were given.
        ARGS_DESC.update(
            colors.get('desc', colors.get('description', {}))
        )
        ARGS_HEADER.update(colors.get('header', {}))
        ARGS_LABEL.update(colors.get('label', {}))
        ARGS_OPTIONS.update(colors.get('options', {}))
        ARGS_SCRIPT.update(colors.get('script', {}))
        ARGS_VERSION.update(colors.get('version', {}))

    return _old_docopt(
        doc,
        argv=argv,
        help=help,
        version=version,
        options_first=options_first,
    )

Response: Wrapper for docopt. docopt that sets SCRIPT to script.


Instruction:
Can you generate the documentation for the following Python 3 function
def display(method=EraseMethod.ALL_MOVE):
        accepted_methods = ('0', '1', '2', '3', '4')
        methodstr = str(method)
        if methodstr not in accepted_methods:
            raise ValueError('Invalid method, expected {}. Got: {!r}'.format(
                ', '.join(accepted_methods),
                method,
            ))
        if methodstr == '4':
            methods = (2, 3)
        else:
            methods = (method, )
        return EscapeCode(
            ''.join(str(EscapeCode('{}J'.format(m))) for m in methods)
        )

Response: Display the current state of the current element in the screen.


Instruction:
Make a summary of the following Python 3 code
def line(method=EraseMethod.ALL):
        methods = ('0', '1', '2')
        if str(method) not in methods:
            raise ValueError('Invalid method, expected {}. Got: {!r}'.format(
                ', '.join(methods),
                method,
            ))
        return EscapeCode('{}K'.format(method))

Response: Erase a line or part of a line.


Instruction:
Can you tell what is the following Python 3 function doing
def try_unbuffered_file(file, _alreadyopen={}):
    try:
        fileno = file.fileno()
    except (AttributeError, UnsupportedOperation):
        # Unable to use fileno to re-open unbuffered. Oh well.
        # The output may be line buffered, which isn't that great for
        # repeatedly drawing and erasing text, or hiding/showing the cursor.
        return file
    filedesc = _alreadyopen.get(fileno, None)
    if filedesc is not None:
        return filedesc

    filedesc = fdopen(fileno, 'wb', 0)
    _alreadyopen[fileno] = filedesc
    # TODO: sys.stdout/stderr don't need to be closed.
    #       But would it be worth it to try and close these opened files?
    return filedesc

Response: Try re - opening a file in an unbuffered mode and return it.


Instruction:
Can you generate the documentation for the following Python 3 function
def _loop(self):
        self.stop_flag.value = False
        self.time_started.value = time()
        self.time_elapsed.value = 0

        while True:
            if self.stop_flag.value:
                break
            self.update_text()
            with self.time_started.get_lock():
                start = self.time_started.value
                with self.time_elapsed.get_lock():
                    self.time_elapsed.value = time() - start
                    if (
                            self.timeout.value and
                            (self.time_elapsed.value > self.timeout.value)):
                        self.stop()
                        raise ProgressTimedOut(
                            self.name,
                            self.time_elapsed.value,
                        )

Response: This is the main loop that runs in the subproces. It is called from the main thread. It is called from the main thread. It is called from the main thread. It is called from the main thread.


Instruction:
Write a Python 3 script to
run the main loop in a subprocess.

Response:
def run(self):
        """ Runs the printer loop in a subprocess. This is called by
            multiprocessing.
        """
        try:
            self._loop()
        except Exception:
            # Send the exception through the exc_queue, so the parent
            # process can check it.
            typ, val, tb = sys.exc_info()
            tb_lines = traceback.format_exception(typ, val, tb)
            self.exc_queue.put((val, tb_lines))


Instruction:
How would you explain what the following Python 3 function does
def stop(self):
        self.stop_flag.value = True
        with self.lock:
            (
                Control().text(C(' ', style='reset_all'))
                .pos_restore().move_column(1).erase_line()
                .write(self.file)
            )

Response: Stop this WriterProcessBase and reset the cursor.


Instruction:
Create a Python 3 function for
writing the current text and check for any new text changes.

Response:
def update_text(self):
        """ Write the current text, and check for any new text changes.
            This also updates the elapsed time.
        """
        self.write()
        try:
            newtext = self.text_queue.get_nowait()
            self._text = newtext
        except Empty:
            pass


Instruction:
How would you implement a function in Python 3 that
writes the current text to self. file and flush it.

Response:
def write(self):
        """ Write the current text to self.file, and flush it.
            This can be overridden to handle custom writes.
        """
        if self._text is not None:
            with self.lock:
                self.file.write(str(self._text).encode())
                self.file.flush()
        sleep(self.nice_delay)


Instruction:
Write a Python 3 script to
try retrieving the last subprocess exception.

Response:
def exception(self):
        """ Try retrieving the last subprocess exception.
            If set, the exception is returned. Otherwise None is returned.
        """
        if self._exception is not None:
            return self._exception
        try:
            exc, tblines = self.exc_queue.get_nowait()
        except Empty:
            self._exception, self.tb_lines = None, None
        else:
            # Raise any exception that the subprocess encountered and sent.
            self._exception, self.tb_lines = exc, tblines
        return self._exception


Instruction:
Create a Python 3 function for
setting self.fmt, with some extra help for plain format strings.

Response:
def fmt(self, value):
        """ Sets self.fmt, with some extra help for plain format strings. """
        if isinstance(value, str):
            value = value.split(self.join_str)
        if not (value and isinstance(value, (list, tuple))):
            raise TypeError(
                ' '.join((
                    'Expecting str or list/tuple of formats {!r}.',
                    'Got: ({}) {!r}'
                )).format(
                    self.default_format,
                    type(value).__name__,
                    value,
                ))
        self._fmt = value


Instruction:
Can you tell what is the following Python 3 function doing
def run(self):
        try:
            Control().cursor_hide().write(file=self.file)
            super().run()
        except KeyboardInterrupt:
            self.stop()
        finally:
            Control().cursor_show().write(file=self.file)

Response: Overrides WriterProcess. run to handle KeyboardInterrupts better.


Instruction:
Can you write a function in Python 3 where it
stops this animated progress and block until it is finished.

Response:
def stop(self):
        """ Stop this animated progress, and block until it is finished. """
        super().stop()
        while not self.stopped:
            # stop() should block, so printing afterwards isn't interrupted.
            sleep(0.001)
        # Retrieve the latest exception, if any.
        exc = self.exception
        if exc is not None:
            raise exc


Instruction:
Write a Python 3 function for
writing a single frame of the progress spinner to the terminal.

Response:
def write(self):
        """ Writes a single frame of the progress spinner to the terminal.
            This function updates the current frame before returning.
        """
        if self.text is None:
            # Text has not been sent through the pipe yet.
            # Do not write anything until it is set to non-None value.
            return None
        if self._last_text == self.text:
            char_delay = 0
        else:
            char_delay = self.char_delay
            self._last_text = self.text
        with self.lock:
            ctl = Control().move_column(1).pos_save().erase_line()
            if char_delay == 0:
                ctl.text(str(self)).write(file=self.file)
            else:
                self.write_char_delay(ctl, char_delay)
            ctl.delay(self.delay)
        return None


Instruction:
Write a Python 3 function that can
advance to the next available frame.

Response:
def _advance_frame(self):
        """ Sets `self.current_frame` to the next frame, looping to the
            beginning if needed.
        """
        self.current_frame += 1
        if self.current_frame == self.frame_len:
            self.current_frame = 0


Instruction:
Can you tell what is the following Python 3 function doing
def _get_delay(self, userdelay, frameslist):
        # User frameslists might not be a FrameSet.
        delay = userdelay or getattr(frameslist, 'delay', None)
        delay = (delay or self.default_delay) - self.nice_delay
        if delay < 0:
            delay = 0
        return delay

Response: Get the appropriate delay value to use for the user.


Instruction:
How would you explain what the following Python 3 function does
def write_char_delay(self, ctl, delay):
        for i, fmt in enumerate(self.fmt):
            if '{text' in fmt:
                # The text will use a write delay.
                ctl.text(fmt.format(text=self.text))
                if i != (self.fmt_len - 1):
                    ctl.text(self.join_str)
                ctl.write(
                    file=self.file,
                    delay=delay
                )
            else:
                # Anything else is written with no delay.
                ctl.text(fmt.format(
                    frame=self.frames[self.current_frame],
                    elapsed=self.elapsed
                ))
                if i != (self.fmt_len - 1):
                    # Add the join_str to pieces, except the last piece.
                    ctl.text(self.join_str)
                ctl.write(file=self.file)
        return ctl

Response: Write the formatted format pieces in order applying a delay between characters for the text only.


Instruction:
How would you code a function in Python 3 to
update the percentage and message.

Response:
def update(self, percent=None, text=None):
        """ Update the progress bar percentage and message. """
        if percent is not None:
            self.percent = percent
        if text is not None:
            self.message = text
        super().update()


Instruction:
Make a summary of the following Python 3 code
def cls_get_by_name(cls, name):
    try:
        val = getattr(cls, name)
    except AttributeError:
        for attr in (a for a in dir(cls) if not a.startswith('_')):
            try:
                val = getattr(cls, attr)
            except AttributeError:
                # Is known to happen.
                continue
            valname = getattr(val, 'name', None)
            if valname == name:
                return val
        else:
            raise ValueError('No {} with that name: {}'.format(
                cls.__name__,
                name,
            ))
    else:
        return val

Response: Return a class attribute by searching the attributes name attribute.


Instruction:
Explain what the following Python 3 code does
def cls_names(cls, wanted_cls, registered=True):
    return [
        fset.name
        for fset in cls_sets(cls, wanted_cls, registered=registered)
    ]

Response: Return a list of all attributes for the wanted_cls attributes in this object.


Instruction:
Can you create a Python 3 function that
registers a new FrameSet or FrameSet subclass as a member of a class.

Response:
def cls_register(cls, frameset, new_class, init_args, name=None):
    """ Register a new FrameSet or FrameSet subclass as a member/attribute
        of a class.
        Returns the new FrameSet or FrameSet subclass.
        Arguments:
            frameset  : An existing FrameSet, or an iterable of strings.
            init_args : A list of properties from the `frameset` to try to use
                        for initializing the new FrameSet.
            new_class : The class type to initialize.
            name      : New name for the FrameSet, also used as the
                        classes attribute name.
                        If the `frameset` object has not `name` attribute,
                        this argument is required. It must not be empty
                        when given.
    """
    name = name or getattr(frameset, 'name', None)
    if name is None:
        raise ValueError(
            '`name` is needed when the `frameset` has no name attribute.'
        )
    kwargs = {'name': name}
    for initarg in init_args:
        kwargs[initarg] = getattr(frameset, initarg, None)

    newframeset = new_class(frameset, **kwargs)
    # Mark this FrameSet/BarSet as a registered item (not basic/original).
    newframeset._registered = True
    setattr(cls, name, newframeset)
    return newframeset


Instruction:
How would you explain what the following Python 3 function does
def cls_sets(cls, wanted_cls, registered=True):
    sets = []
    for attr in dir(cls):
        if attr.startswith('_'):
            continue
        val = getattr(cls, attr, None)
        if not isinstance(val, wanted_cls):
            continue
        if (not registered) and getattr(val, '_registered', False):
            continue
        sets.append(val)
    return sets

Response:
Return a list of all wanted_cls attributes in this
        class where wanted_cls is the desired attribute type.


Instruction:
Can you tell what is the following Python 3 function doing
def _build_color_variants(cls):
    # Get the basic frame types first.
    frametypes = cls.sets(registered=False)

    _colornames = [
        # 'black', disabled for now, it won't show on my terminal.
        'red',
        'green',
        'yellow',
        'blue',
        'magenta',
        'cyan',
        'white',
    ]
    _colornames.extend('light{}'.format(s) for s in _colornames[:])
    for colorname in _colornames:
        for framesobj in frametypes:
            framename = '{}_{}'.format(framesobj.name, colorname)
            cls.register(
                framesobj.as_colr(fore=colorname),
                name=framename,
            )

Response:
Build colorized variants of all frames and return a list of
        all frame object names.


Instruction:
Write a Python 3 script to
create a new FrameSet from an existing BarSet object.

Response:
def from_barset(
            cls, barset, name=None, delay=None,
            use_wrapper=True, wrapper=None):
        """ Copy a BarSet's frames to create a new FrameSet.

            Arguments:
                barset      : An existing BarSet object to copy frames from.
                name        : A name for the new FrameSet.
                delay       : Delay for the animation.
                use_wrapper : Whether to use the old barset's wrapper in the
                              frames.
                wrapper     : A new wrapper pair to use for each frame.
                              This overrides the `use_wrapper` option.
        """
        if wrapper:
            data = tuple(barset.wrap_str(s, wrapper=wrapper) for s in barset)
        elif use_wrapper:
            data = tuple(barset.wrap_str(s) for s in barset)
        else:
            data = barset.data
        return cls(
            data,
            name=name,
            delay=delay
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def as_gradient(self, name=None, style=None, rgb_mode=False):
        return self._as_gradient(
            ('wrapper', ),
            name=name,
            style=style,
            rgb_mode=rgb_mode,
        )

Response: Wrap each frame in a Colr object using Colr. gradient.


Instruction:
Given the following Python 3 function, write the documentation
def as_percent(self, percent):
        if not self:
            return self.wrap_str()

        length = len(self)
        # Using mod 100, to provide some kind of "auto reset". 0 is 0 though.
        percentmod = (int(percent) % 100) or min(percent, 100)
        index = int((length / 100) * percentmod)
        try:
            barstr = str(self[index])
        except IndexError:
            barstr = self[-1]

        return self.wrap_str(barstr)

Response: Return a string representing a percentage of this progress bar.


Instruction:
Given the following Python 3 function, write the documentation
def as_rainbow(self, offset=35, style=None, rgb_mode=False):
        return self._as_rainbow(
            ('wrapper', ),
            offset=offset,
            style=style,
            rgb_mode=rgb_mode,
        )

Response: Wrap each frame in a Colr object using Colr. rainbow.


Instruction:
How would you code a function in Python 3 to
create a new instance of a nacarity. A nacarity. n

Response:
def from_char(
            cls, char, name=None, width=None, fill_char=None,
            bounce=False, reverse=False, back_char=None, wrapper=None):
        """ Create progress bar frames from a "moving" character.
            The frames simulate movement of the character, from left to
            right through empty space (`fill_char`).

            Arguments:
                char           : Character to move across the bar.
                name           : Name for the new BarSet.
                width          : Width of the progress bar.
                                 Default: 25
                fill_char      : Character to fill empty space.
                                 Default: ' ' (space)
                bounce         : Whether the frames should simulate a bounce
                                 from one side to another.
                                 Default: False
                reverse        : Whether the character should start on the
                                 right.
                                 Default: False
                back_char  : Character to use when "bouncing" backward.
                                 Default: `char`
        """
        return cls(
            cls._generate_move(
                char,
                width=width or cls.default_width,
                fill_char=str(fill_char or cls.default_fill_char),
                bounce=bounce,
                reverse=reverse,
                back_char=back_char,
            ),
            name=name,
            wrapper=wrapper or cls.default_wrapper,
        )


Instruction:
Can you generate the documentation for the following Python 3 function
def from_str(cls, s, name=None, fill_char=None, wrapper=None):
        fill_char = fill_char or cls.default_fill_char
        maxlen = len(s)
        frames = []
        for pos in range(1, maxlen):
            framestr = s[:pos]
            # Not using ljust, because fill_char may be a str, not a char.
            frames.append(
                ''.join((
                    framestr,
                    fill_char * (maxlen - len(framestr))
                ))
            )
        frames.append(s)
        return cls(
            frames,
            name=name,
            wrapper=wrapper,
        )

Response: Create a new BarSet from a single string.


Instruction:
How would you explain what the following Python 3 function does
def _generate_move(
            cls, char, width=None, fill_char=None,
            bounce=False, reverse=True, back_char=None):
        """ Yields strings that simulate movement of a character from left
            to right. For use with `BarSet.from_char`.

            Arguments:
                char          : Character to move across the progress bar.
                width         : Width for the progress bar.
                                Default: cls.default_width
                fill_char     : String for empty space.
                                Default: cls.default_fill_char
                bounce        : Whether to move the character in both
                                directions.
                reverse       : Whether to start on the right side.
                back_char  : Character to use for the bounce's backward
                                movement.
                                Default: `char`
        """
        width = width or cls.default_width
        char = str(char)
        filler = str(fill_char or cls.default_fill_char) * (width - len(char))

        rangeargs = RangeMoveArgs(
            (0, width, 1),
            (width, 0, -1),
        )
        if reverse:
            # Reverse the arguments for range to start from the right.
            # Not using swap, because the stopping point is different.
            rangeargs = RangeMoveArgs(
                (width, -1, -1),
                (0, width - 1, 1),
            )

        yield from (
            ''.join((filler[:i], char, filler[i:]))
            for i in range(*rangeargs.forward)
        )

        if bounce:
            bouncechar = char if back_char is None else back_char
            yield from (
                ''.join((filler[:i], str(bouncechar), filler[i:]))
                for i in range(*rangeargs.backward)
            )

Response: Generates a generator that generates the string that simulate a character from left to right.


Instruction:
How would you code a function in Python 3 to
copy this BarSet and return a new BarSet with the specified wrapper.

Response:
def with_wrapper(self, wrapper=None, name=None):
        """ Copy this BarSet, and return a new BarSet with the specified
            name and wrapper.
            If no name is given, `{self.name}_custom_wrapper` is used.
            If no wrapper is given, the new BarSet will have no wrapper.
        """
        name = name or '{}_custom_wrapper'.format(self.name)
        return self.__class__(self.data, name=name, wrapper=wrapper)


Instruction:
Explain what the following Python 3 code does
def wrap_str(self, s=None, wrapper=None):
        wrapper = wrapper or (self.wrapper or ('', ''))
        return str('' if s is None else s).join(wrapper)

Response:
Wrap a string in self. wrapper with some extra handling for
            empty or None strings.


Instruction:
Can you implement a function in Python 3 that
registers a new BarSet as a member or attribute of this class.

Response:
def register(cls, barset, name=None):
        """ Register a new BarSet as a member/attribute of this class.
            Returns the new BarSet.
            Arguments:
                barset    : An existing BarSet, or an iterable of strings.
                name      : New name for the BarSet, also used as the
                            classes attribute name.
                            If the `barset` object has not `name` attribute,
                            this argument is required. It must not be empty
                            when given.
        """
        return cls_register(cls, barset, BarSet, ('wrapper', ), name=name)


Instruction:
Make a summary of the following Python 3 code
def register(cls, frameset, name=None):
        return cls_register(cls, frameset, FrameSet, ('delay', ), name=name)

Response: Register a new FrameSet as a member or attribute of this class.


Instruction:
Can you write a function in Python 3 where it
creates a new instance from a pyuv. errno error code.

Response:
def from_errno(cls, errno):
        """Create a new instance from a :mod:`pyuv.errno` error code."""
        message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno),
                                    pyuv.errno.strerror(errno))
        return cls(message, errno)


Instruction:
Write a Python 3 script to
bind to protocol and start calling callbacks on it.

Response:
def start(self, protocol):
        """Bind to *protocol* and start calling callbacks on it. """
        if self._protocol is not None:
            raise TransportError('already started')
        self._protocol = protocol
        self._protocol.connection_made(self)
        if self._readable:
            self.resume_reading()
        if self._writable:
            self._writing = True
            self._can_write.set()


Instruction:
How would you implement a function in Python 3 that
sets the low and high watermark for the write buffer.

Response:
def set_write_buffer_limits(self, high=None, low=None):
        """Set the low and high watermark for the write buffer."""
        if high is None:
            high = self.write_buffer_size
        if low is None:
            low = high // 2
        if low > high:
            low = high
        self._write_buffer_high = high
        self._write_buffer_low = low


Instruction:
Here you have a function in Python 3, explain what it does
def close(self):
        if self._closing or self._handle.closed:
            return
        elif self._protocol is None:
            raise TransportError('transport not started')
        # If the write buffer is empty, close now. Otherwise defer to
        # _on_write_complete that will close when the buffer is empty.
        if self._write_buffer_size == 0:
            self._handle.close(self._on_close_complete)
            assert self._handle.closed
        else:
            self._closing = True

Response: Close the transport after all oustanding data has been written.


Instruction:
How would you code a function in Python 3 to
close the transport immediately.

Response:
def abort(self):
        """Close the transport immediately."""
        if self._handle.closed:
            return
        elif self._protocol is None:
            raise TransportError('transport not started')
        self._handle.close(self._on_close_complete)
        assert self._handle.closed


Instruction:
Can you generate the documentation for the following Python 3 function
def write(self, data, handle=None):
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError("data: expecting a bytes-like instance, got {!r}"
                                .format(type(data).__name__))
        if handle is not None and not isinstance(self._handle, pyuv.Pipe):
            raise ValueError('handle: can only be sent over pyuv.Pipe')
        self._check_status()
        if not self._writable:
            raise TransportError('transport is not writable')
        if self._closing:
            raise TransportError('transport is closing')
        try:
            if handle:
                self._handle.write(data, self._on_write_complete, handle)
            else:
                self._handle.write(data, self._on_write_complete)
        except pyuv.error.UVError as e:
            self._error = TransportError.from_errno(e.args[0])
            self.abort()
            raise compat.saved_exc(self._error)
        # We only keep track of the number of outstanding write requests
        # outselves. See note in get_write_buffer_size().
        self._write_buffer_size += 1
        self._maybe_pause_protocol()

Response: Write data to the transport.


Instruction:
Here you have a function in Python 3, explain what it does
def write_eof(self):
        self._check_status()
        if not self._writable:
            raise TransportError('transport is not writable')
        if self._closing:
            raise TransportError('transport is closing')
        try:
            self._handle.shutdown(self._on_write_complete)
        except pyuv.error.UVError as e:
            self._error = TransportError.from_errno(e.args[0])
            self.abort()
            raise compat.saved_exc(self._error)
        self._write_buffer_size += 1

Response: Shut down the write direction of the transport.


Instruction:
Can you generate the documentation for the following Python 3 function
def get_extra_info(self, name, default=None):
        if name == 'sockname':
            if not hasattr(self._handle, 'getsockname'):
                return default
            try:
                return self._handle.getsockname()
            except pyuv.error.UVError:
                return default
        elif name == 'peername':
            if not hasattr(self._handle, 'getpeername'):
                return default
            try:
                return self._handle.getpeername()
            except pyuv.error.UVError:
                return default
        elif name == 'winsize':
            if not hasattr(self._handle, 'get_winsize'):
                return default
            try:
                return self._handle.get_winsize()
            except pyuv.error.UVError:
                return default
        elif name == 'unix_creds':
            # In case you're wondering, DBUS needs this.
            if not isinstance(self._handle, pyuv.Pipe) or not hasattr(socket, 'SO_PEERCRED'):
                return default
            try:
                fd = self._handle.fileno()
                sock = socket.fromfd(fd, socket.AF_UNIX, socket.SOCK_DGRAM)  # will dup()
                with contextlib.closing(sock):
                    creds = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED,
                                            struct.calcsize('3i'))
            except socket.error:
                return default
            return struct.unpack('3i', creds)
        elif name == 'server_hostname':
            return self._server_hostname
        else:
            return super(Transport, self).get_extra_info(name, default)

Response: Get extra information for a specific transport class.


Instruction:
Here you have a function in Python 3, explain what it does
def _on_recv_complete(self, handle, addr, flags, data, error):
        assert handle is self._handle
        if error:
            self._log.warning('pyuv error {} in recv callback', error)
            self._protocol.error_received(TransportError.from_errno(error))
        elif flags:
            assert flags & pyuv.UV_UDP_PARTIAL
            self._log.warning('ignoring partial datagram')
        elif data:
            self._protocol.datagram_received(data, addr)

Response: Callback used with handle. start_recv.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _on_send_complete(self, handle, error):
        assert handle is self._handle
        self._write_buffer_size -= 1
        assert self._write_buffer_size >= 0
        if self._error:
            self._log.debug('ignore sendto status {} after error', error)
        # See note in _on_write_complete() about UV_ECANCELED
        elif error and error != pyuv.errno.UV_ECANCELED:
            self._log.warning('pyuv error {} in sendto callback', error)
            self._protocol.error_received(TransportError.from_errno(error))
        self._maybe_resume_protocol()
        self._maybe_close()

Response: Callback used with handle. send.


Instruction:
Can you write a function in Python 3 where it
sends a datagram containing data to addr.

Response:
def sendto(self, data, addr=None):
        """Send a datagram containing *data* to *addr*.

        The *addr* argument may be omitted only if the handle was bound to a
        default remote address.
        """
        if not isinstance(data, (bytes, bytearray, memoryview)):
            raise TypeError("data: expecting a bytes-like instance, got {!r}"
                                .format(type(data).__name__))
        self._check_status()
        if not self._writable:
            raise TransportError('transport is not writable')
        try:
            self._handle.send(addr, data, self._on_send_complete)
        except pyuv.error.UVError as e:
            error = TransportError.from_errno(e.args[0])
            # Try to discern between permanent and transient errors. Permanent
            # errors close the transport. This list is very likely not complete.
            if error.errno != pyuv.errno.UV_EBADF:
                raise error
            self._error = error
            self.abort()
        self._write_buffer_size += 1
        self._maybe_pause_protocol()


Instruction:
Write a Python 3 function that can
parse a D - BUS address string into a list of addresses.

Response:
def parse_dbus_address(address):
    """Parse a D-BUS address string into a list of addresses."""
    if address == 'session':
        address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
        if not address:
            raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
    elif address == 'system':
        address = os.environ.get('DBUS_SYSTEM_BUS_ADDRESS',
                                 'unix:path=/var/run/dbus/system_bus_socket')
    addresses = []
    for addr in address.split(';'):
        p1 = addr.find(':')
        if p1 == -1:
            raise ValueError('illegal address string: {}'.format(addr))
        kind = addr[:p1]
        args = dict((kv.split('=') for kv in addr[p1+1:].split(',')))
        if kind == 'unix':
            if 'path' in args:
                addr = args['path']
            elif 'abstract' in args:
                addr = '\0' + args['abstract']
            else:
                raise ValueError('require "path" or "abstract" for unix')
        elif kind == 'tcp':
            if 'host' not in args or 'port' not in args:
                raise ValueError('require "host" and "port" for tcp')
            addr = (args['host'], int(args['port']))
        else:
            raise ValueError('unknown transport: {}'.format(kind))
        addresses.append(addr)
    return addresses


Instruction:
Write a Python 3 script for
parsing a D - BUS header. Return the message size.

Response:
def parse_dbus_header(header):
    """Parse a D-BUS header. Return the message size."""
    if six.indexbytes(header, 0) == ord('l'):
        endian = '<'
    elif six.indexbytes(header, 0) == ord('B'):
        endian = '>'
    else:
        raise ValueError('illegal endianness')
    if not 1 <= six.indexbytes(header, 1) <= 4:
        raise ValueError('illegel message type')
    if struct.unpack(endian + 'I', header[8:12])[0] == 0:
        raise ValueError('illegal serial number')
    harrlen = struct.unpack(endian + 'I', header[12:16])[0]
    padlen = (8 - harrlen) % 8
    bodylen = struct.unpack(endian + 'I', header[4:8])[0]
    return 16 + harrlen + padlen + bodylen


Instruction:
Here you have a function in Python 3, explain what it does
def getMechanismName(self):
        if self._server_side:
            mech = self._authenticator.current_mech
            return mech.getMechanismName() if mech else None
        else:
            return getattr(self._authenticator, 'authMech', None)

Response: Return the authentication mechanism name.


Instruction:
Implement a Python 3 function for
returning the authenticated user name.

Response:
def getUserName(self):
        """Return the authenticated user name (server side)."""
        if not self._server_side:
            return
        mech = self._authenticator.current_mech
        return mech.getUserName() if mech else None


Instruction:
Write a Python 3 function for
returning the unique name of the D - BUS connection.

Response:
def get_unique_name(self):
        """Return the unique name of the D-BUS connection."""
        self._name_acquired.wait()
        if self._error:
            raise compat.saved_exc(self._error)
        elif self._transport is None:
            raise DbusError('not connected')
        return self._unique_name


Instruction:
Can you create a Python 3 function that
sends a message to the D - BUS.

Response:
def send_message(self, message):
        """Send a D-BUS message.

        The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
        """
        if not isinstance(message, txdbus.DbusMessage):
            raise TypeError('message: expecting DbusMessage instance (got {!r})',
                                type(message).__name__)
        self._name_acquired.wait()
        if self._error:
            raise compat.saved_exc(self._error)
        elif self._transport is None:
            raise DbusError('not connected')
        self._writer.write(message.rawMessage)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def call_method(self, service, path, interface, method, signature=None,
                    args=None, no_reply=False, auto_start=False, timeout=-1):
        """Call a D-BUS method and wait for its reply.

        This method calls the D-BUS method with name *method* that resides on
        the object at bus address *service*, at path *path*, on interface
        *interface*.

        The *signature* and *args* are optional arguments that can be used to
        add parameters to the method call. The signature is a D-BUS signature
        string, while *args* must be a sequence of python types that can be
        converted into the types specified by the signature. See the `D-BUS
        specification
        <http://dbus.freedesktop.org/doc/dbus-specification.html>`_ for a
        reference on signature strings.

        The flags *no_reply* and *auto_start* control the NO_REPLY_EXPECTED and
        NO_AUTO_START flags on the D-BUS message.

        The return value is the result of the D-BUS method call. This will be a
        possibly empty sequence of values.
        """
        message = txdbus.MethodCallMessage(path, method, interface=interface,
                                destination=service, signature=signature, body=args,
                                expectReply=not no_reply, autoStart=auto_start)
        serial = message.serial
        if timeout == -1:
            timeout = self._timeout
        try:
            with switch_back(timeout) as switcher:
                self._method_calls[serial] = switcher
                self.send_message(message)
                args, _ = self._hub.switch()
        finally:
            self._method_calls.pop(serial, None)
        response = args[0]
        assert response.reply_serial == serial
        if isinstance(response, txdbus.ErrorMessage):
            raise DbusMethodCallError(method, response)
        args = tuple(response.body) if response.body else ()
        return args

Response: Call a method on the specified object at the specified bus address.


Instruction:
Create a Python 3 function to
connect to the database and wait until the connection is established.

Response:
def connect(self, address='session'):
        """Connect to *address* and wait until the connection is established.

        The *address* argument must be a D-BUS server address, in the format
        described in the D-BUS specification. It may also be one of the special
        addresses ``'session'`` or ``'system'``, to connect to the D-BUS
        session and system bus, respectively.
        """
        if isinstance(address, six.string_types):
            addresses = parse_dbus_address(address)
        else:
            addresses = [address]
        for addr in addresses:
            try:
                super(DbusClient, self).connect(addr)
            except pyuv.error.UVError:
                continue
            break
        else:
            raise DbusError('could not connect to any address')
        # Wait for authentication to complete
        self.get_unique_name()


Instruction:
Write a Python 3 script to
start listening on the given address for new connection.

Response:
def listen(self, address='session'):
        """Start listening on *address* for new connection.

        The *address* argument must be a D-BUS server address, in the format
        described in the D-BUS specification. It may also be one of the special
        addresses ``'session'`` or ``'system'``, to connect to the D-BUS
        session and system bus, respectively.
        """
        if isinstance(address, six.string_types):
            addresses = parse_dbus_address(address)
        else:
            addresses = [address]
        for addr in addresses:
            try:
                super(DbusServer, self).listen(addr)
            except pyuv.error.UVError:
                self._log.error('skipping address {}', saddr(addr))


Instruction:
Here you have a function in Python 3, explain what it does
def docfrom(base):
    def setdoc(func):
        func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '')
        return func
    return setdoc

Response: Decorator to set a function s docstring from another function.


Instruction:
Write a Python 3 script for
returning a string that uniquely and compactly identifies an object.

Response:
def objref(obj):
    """Return a string that uniquely and compactly identifies an object."""
    ref = _objrefs.get(obj)
    if ref is None:
        clsname = obj.__class__.__name__.split('.')[-1]
        seqno = _lastids.setdefault(clsname, 1)
        ref = '{}-{}'.format(clsname, seqno)
        _objrefs[obj] = ref
        _lastids[clsname] += 1
    return ref


Instruction:
Can you generate the documentation for the following Python 3 function
def delegate_method(other, method, name=None):
    frame = sys._getframe(1)
    classdict = frame.f_locals

    @functools.wraps(method)
    def delegate(self, *args, **kwargs):
        other_self = other.__get__(self)
        return method(other_self, *args, **kwargs)

    if getattr(method, '__switchpoint__', False):
        delegate.__switchpoint__ = True

    if name is None:
        name = method.__name__
    propname = None
    for key in classdict:
        if classdict[key] is other:
            propname = key
            break
    # If we know the property name, replace the docstring with a small
    # reference instead of copying the function docstring.
    if propname:
        qname = getattr(method, '__qualname__', method.__name__)
        if '.' in qname:
            delegate.__doc__ = 'A shorthand for ``self.{propname}.{name}()``.' \
                               .format(name=name, propname=propname)
        else:
            delegate.__doc__ = 'A shorthand for ``{name}({propname}, ...)``.' \
                               .format(name=name, propname=propname)
    classdict[name] = delegate

Response: Add a method to the current class that delegates to another method.


Instruction:
Can you generate the documentation for the following Python 3 function
def accept_ws(buf, pos):
    match = re_ws.match(buf, pos)
    if not match:
        return None, pos
    return buf[match.start(0):match.end(0)], match.end(0)

Response: Skip whitespace at the current buffer position.


Instruction:
Implement a Python 3 function for
accepting a literal character at the current buffer position.

Response:
def accept_lit(char, buf, pos):
    """Accept a literal character at the current buffer position."""
    if pos >= len(buf) or buf[pos] != char:
        return None, pos
    return char, pos+1


Instruction:
How would you explain what the following Python 3 function does
def expect_lit(char, buf, pos):
    if pos >= len(buf) or buf[pos] != char:
        return None, len(buf)
    return char, pos+1

Response: Expect a literal character at the current buffer position.


Instruction:
Explain what the following Python 3 code does
def accept_re(regexp, buf, pos):
    match = regexp.match(buf, pos)
    if not match:
        return None, pos
    return buf[match.start(1):match.end(1)], match.end(0)

Response: Accept a regular expression at the current buffer position.


Instruction:
Write a Python 3 script to
require a regular expression at the current buffer position.

Response:
def expect_re(regexp, buf, pos):
    """Require a regular expression at the current buffer position."""
    match = regexp.match(buf, pos)
    if not match:
        return None, len(buf)
    return buf[match.start(1):match.end(1)], match.end(0)


Instruction:
Create a Python 3 function to
parse the Content - Type header.

Response:
def parse_content_type(header):
    """Parse the "Content-Type" header."""
    typ = subtyp = None; options = {}
    typ, pos = expect_re(re_token, header, 0)
    _, pos = expect_lit('/', header, pos)
    subtyp, pos = expect_re(re_token, header, pos)
    ctype = header[:pos] if subtyp else ''
    while pos < len(header):
        _, pos = accept_ws(header, pos)
        _, pos = expect_lit(';', header, pos)
        _, pos = accept_ws(header, pos)
        name, pos = expect_re(re_token, header, pos)
        _, pos = expect_lit('=', header, pos)
        char = lookahead(header, pos)
        if char == '"':
            value, pos = expect_re(re_qstring, header, pos)
            value = re_qpair.sub('\\1', value)
        elif char:
            value, pos = expect_re(re_token, header, pos)
        if name and value is not None:
            options[name] = value
    return ctype, options


Instruction:
Can you tell what is the following Python 3 function doing
def parse_te(header):
    pos = 0
    names = []
    while pos < len(header):
        name, pos = expect_re(re_token, header, pos)
        _, pos = accept_ws(header, pos)
        _, pos = accept_lit(';', header, pos)
        _, pos = accept_ws(header, pos)
        qvalue, pos = accept_re(re_qvalue, header, pos)
        if name:
            names.append((name, qvalue))
        _, pos = accept_ws(header, pos)
        _, pos = expect_lit(',', header, pos)
        _, pos = accept_ws(header, pos)
    return names

Response: Parse the TE header.


Instruction:
How would you code a function in Python 3 to
parse the Trailer header.

Response:
def parse_trailer(header):
    """Parse the "Trailer" header."""
    pos = 0
    names = []
    while pos < len(header):
        name, pos = expect_re(re_token, header, pos)
        if name:
            names.append(name)
        _, pos = accept_ws(header, pos)
        _, pos = expect_lit(',', header, pos)
        _, pos = accept_ws(header, pos)
    return names


Instruction:
Can you implement a function in Python 3 that
creates a RFC1123 style Date header for the given timestamp.

Response:
def rfc1123_date(timestamp=None):
    """Create a RFC1123 style Date header for *timestamp*."""
    if timestamp is None:
        timestamp = time.time()
    timestamp = int(timestamp)
    global _cached_timestamp, _cached_datestring
    if timestamp != _cached_timestamp:
        # The time stamp must be GMT, and cannot be localized.
        tm = time.gmtime(timestamp)
        s = rfc1123_fmt.replace('%a', weekdays[tm.tm_wday]) \
                       .replace('%b', months[tm.tm_mon-1])
        _cached_datestring = time.strftime(s, tm)
        _cached_timestamp = timestamp
    return _cached_datestring


Instruction:
Can you tell what is the following Python 3 function doing
def parse_url(url, default_scheme='http', is_connect=False):
    # If this is not in origin-form, authority-form or asterisk-form and no
    # scheme is present, assume it's in absolute-form with a missing scheme.
    # See RFC7230 section 5.3.
    if url[:1] not in '*/' and not is_connect and '://' not in url:
        url = '{}://{}'.format(default_scheme, url)
    burl = s2b(url)
    parser = ffi.new('struct http_parser_url *')
    lib.http_parser_url_init(parser)
    res = lib.http_parser_parse_url(ffi.from_buffer(burl), len(burl), is_connect, parser)
    if res != 0:
        raise ValueError('invalid URL')
    parsed = ParsedUrl.from_parser(parser, url)
    return parsed

Response: Parse an URL and return its components.


Instruction:
Write a Python 3 function for
returning the value of header name*.

Response:
def get_header(headers, name, default=None):
    """Return the value of header *name*.

    The *headers* argument must be a list of ``(name, value)`` tuples. If the
    header is found its associated value is returned, otherwise *default* is
    returned. Header names are matched case insensitively.
    """
    name = name.lower()
    for header in headers:
        if header[0].lower() == name:
            return header[1]
    return default


Instruction:
Can you generate the documentation for the following Python 3 function
def remove_headers(headers, name):
    i = 0
    name = name.lower()
    for j in range(len(headers)):
        if headers[j][0].lower() != name:
            if i != j:
                headers[i] = headers[j]
            i += 1
    del headers[i:]
    return headers

Response: Remove all headers with name name.


Instruction:
Can you implement a function in Python 3 that
creates a chunk for the HTTP chunked transfer encoding.

Response:
def create_chunk(buf):
    """Create a chunk for the HTTP "chunked" transfer encoding."""
    chunk = []
    chunk.append(s2b('{:X}\r\n'.format(len(buf))))
    chunk.append(buf)
    chunk.append(b'\r\n')
    return b''.join(chunk)


Instruction:
Write a Python 3 function that can
create the ending that terminates a chunked body.

Response:
def create_chunked_body_end(trailers=None):
    """Create the ending that terminates a chunked body."""
    chunk = []
    chunk.append('0\r\n')
    if trailers:
        for name, value in trailers:
            chunk.append(name)
            chunk.append(': ')
            chunk.append(value)
            chunk.append('\r\n')
    chunk.append('\r\n')
    return s2b(''.join(chunk))


Instruction:
Make a summary of the following Python 3 code
def create_request(version, method, url, headers):
    # According to my measurements using b''.join is faster that constructing a
    # bytearray.
    message = []
    message.append('{} {} HTTP/{}\r\n'.format(method, url, version))
    for name, value in headers:
        message.append(name)
        message.append(': ')
        message.append(value)
        message.append('\r\n')
    message.append('\r\n')
    return s2b(''.join(message))

Response: Create a HTTP request header.


Instruction:
Implement a function in Python 3 to
create a HTTP response header.

Response:
def create_response(version, status, headers):
    """Create a HTTP response header."""
    message = []
    message.append('HTTP/{} {}\r\n'.format(version, status))
    for name, value in headers:
        message.append(name)
        message.append(': ')
        message.append(value)
        message.append('\r\n')
    message.append('\r\n')
    return s2b(''.join(message))


Instruction:
Can you generate the documentation for the following Python 3 function
def addr(self):
        port = self.port
        if port:
            port = int(port)
        else:
            port = default_ports.get(self.scheme or 'http')
        return (self.host, port)

Response: Address tuple that can be used with gruvi. create_connection.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def start_request(self, method, url, headers=None, bodylen=None):
        self._headers = headers or []
        agent = host = clen = trailer = None
        # Check the headers provided, and capture some information about the
        # request from them.
        for name, value in self._headers:
            lname = name.lower()
            # Only HTTP applications are allowed to set "hop-by-hop" headers.
            if lname in hop_by_hop:
                raise ValueError('header {} is hop-by-hop'.format(name))
            elif lname == 'user-agent':
                agent = value
            elif lname == 'host':
                host = value
            elif lname == 'content-length':
                clen = int(value)
            elif lname == 'trailer':
                trailer = parse_trailer(value)
            elif lname == 'content-type' and value.startswith('text/'):
                ctype, params = parse_content_type(value)
                self._charset = params.get('charset')
        version = self._protocol._version
        # The Host header is mandatory in 1.1. Add it if it's missing.
        if host is None and version == '1.1' and self._protocol._server_name:
            self._headers.append(('Host', self._protocol._server_name))
        # Identify ourselves.
        if agent is None:
            self._headers.append(('User-Agent', self._protocol.identifier))
        # Check if we need to use chunked encoding due to unknown body size.
        if clen is None and bodylen is None:
            if version == '1.0':
                raise HttpError('body size unknown for HTTP/1.0')
            self._chunked = True
        self._content_length = clen
        # Check if trailers are requested and if so need to switch to chunked.
        if trailer:
            if version == '1.0':
                raise HttpError('cannot support trailers for HTTP/1.0')
            if clen is not None:
                remove_headers(self._headers, 'Content-Length')
            self._chunked = True
        self._trailer = trailer
        # Add Content-Length if we know the body size and are not using chunked.
        if not self._chunked and clen is None and bodylen >= 0:
            self._headers.append(('Content-Length', str(bodylen)))
            self._content_length = bodylen
        # Complete the "Hop by hop" headers.
        if version == '1.0':
            self._headers.append(('Connection', 'keep-alive'))
        elif version == '1.1':
            self._headers.append(('Connection', 'te'))
            self._headers.append(('TE', 'trailers'))
        if self._chunked:
            self._headers.append(('Transfer-Encoding', 'chunked'))
        # Start the request
        self._protocol._requests.append(method)
        header = create_request(version, method, url, self._headers)
        self._protocol.writer.write(header)

Response: Start a new HTTP request.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def write(self, buf):
        if not isinstance(buf, six.binary_type):
            raise TypeError('buf: must be a bytes instance')
        # Be careful not to write zero-length chunks as they indicate the end of a body.
        if len(buf) == 0:
            return
        if self._content_length and self._bytes_written > self._content_length:
            raise RuntimeError('wrote too many bytes ({} > {})'
                                    .format(self._bytes_written, self._content_length))
        self._bytes_written += len(buf)
        if self._chunked:
            buf = create_chunk(buf)
        self._protocol.writer.write(buf)

Response: Write a single entry to the request body.


Instruction:
Create a Python 3 function for
ending the request body.

Response:
def end_request(self):
        """End the request body."""
        if not self._chunked:
            return
        trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
                        if self._trailer else None
        ending = create_chunked_body_end(trailers)
        self._protocol.writer.write(ending)


Instruction:
Create a Python 3 function for
making a new HTTP request.

Response:
def request(self, method, url, headers=None, body=None):
        """Make a new HTTP request.

        The *method* argument is the HTTP method as a string, for example
        ``'GET'`` or ``'POST'``. The *url* argument specifies the URL.

        The optional *headers* argument specifies extra HTTP headers to use in
        the request. It must be a sequence of ``(name, value)`` tuples.

        The optional *body* argument may be used to include a body in the
        request. It must be a ``bytes`` instance, a file-like object opened in
        binary mode, or an iterable producing ``bytes`` instances.  To send
        potentially large bodies, use the file or iterator interfaces. This has
        the benefit that only a single chunk is kept in memory at a time.

        The response to the request can be obtained by calling the
        :meth:`getresponse` method. You may make multiple requests before
        reading a response. For every request that you make however, you must
        call :meth:`getresponse` exactly once. The remote HTTP implementation
        will send by the responses in the same order as the requests.

        This method will use the "chunked" transfer encoding if here is a body
        and the body size is unknown ahead of time. This happens when the file
        or interator interface is used in the abence of a "Content-Length"
        header.
        """
        if self._error:
            raise compat.saved_exc(self._error)
        elif self._transport is None:
            raise HttpError('not connected')
        request = HttpRequest(self)
        bodylen = -1 if body is None else \
                        len(body) if isinstance(body, bytes) else None
        request.start_request(method, url, headers, bodylen)
        if isinstance(body, bytes):
            request.write(body)
        elif hasattr(body, 'read'):
            while True:
                chunk = body.read(4096)
                if not chunk:
                    break
                request.write(chunk)
        elif hasattr(body, '__iter__'):
            for chunk in body:
                request.write(chunk)
        request.end_request()


Instruction:
Here you have a function in Python 3, explain what it does
def getresponse(self):
        if self._error:
            raise compat.saved_exc(self._error)
        elif self._transport is None:
            raise HttpError('not connected')
        message = self._queue.get(timeout=self._timeout)
        if isinstance(message, Exception):
            raise compat.saved_exc(message)
        return message

Response: Wait for and return a HTTP response.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def unique_hash(filepath: str, blocksize: int=80)->str:
    s = sha1()
    with open(filepath, "rb") as f:
        buf = f.read(blocksize)
        s.update(buf)
    return s.hexdigest()

Response: Small function to generate a hash to uniquely generate a file.


Instruction:
Here you have a function in Python 3, explain what it does
def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:

    audiofile = AudioSegment.from_file(filename)

    if limit:
        audiofile = audiofile[:limit * 1000]

    data = np.fromstring(audiofile._data, np.int16)

    channels = []
    for chn in range(audiofile.channels):
        channels.append(data[chn::audiofile.channels])

    fs = audiofile.frame_rate

    return channels, fs

Response: Reads any file supported by pydub and returns the data contained within the audio file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def path_to_songname(path: str)->str:
    return os.path.splitext(os.path.basename(path))[0]

Response: Extracts a song name from a filepath. Used to identify which songs have already been fingerprinted on disk.


Instruction:
Explain what the following Python 3 code does
def create_connection(protocol_factory, address, ssl=False, server_hostname=None,
                      local_address=None, family=0, flags=0, ipc=False, timeout=None,
                      mode='rw'):
    """Create a new client connection.

    This method creates a new :class:`pyuv.Handle`, connects it to *address*,
    and then waits for the connection to be established. When the connection is
    established, the handle is wrapped in a transport, and a new protocol
    instance is created by calling *protocol_factory*. The protocol is then
    connected to the transport by calling the transport's
    :meth:`~BaseTransport.start` method which in turn calls
    :meth:`~BaseProtocol.connection_made` on the protocol. Finally the results
    are returned as a ``(transport, protocol)`` tuple.

    The address may be either be a string, a (host, port) tuple, a
    ``pyuv.Stream`` handle or a file descriptor:

    * If the address is a string, this method connects to a named pipe using a
      :class:`pyuv.Pipe` handle. The address specifies the pipe name.
    * If the address is a tuple, this method connects to a TCP/IP service using
      a :class:`pyuv.TCP` handle. The first element of the tuple specifies the
      IP address or DNS name, and the second element specifies the port number
      or service name.
    * If the address is a ``pyuv.Stream`` instance, it must be an already
      connected stream.
    * If the address is a file descriptor, then it is attached to a
      :class:`pyuv.TTY` stream if :func:`os.isatty` returns true, or to a
      :class:`pyuv.Pipe` instance otherwise.

    The *ssl* parameter indicates whether an SSL/TLS connection is desired. If
    so then an :class:`ssl.SSLContext` instance is used to wrap the connection
    using the :mod:`ssl` module's asynchronous SSL support. The context is
    created as follows. If *ssl* is an :class:`~ssl.SSLContext` instance, it is
    used directly. If it is a function, it is called with the connection handle
    as an argument and it must return a context . If it is ``True`` then a
    default context is created using :func:`gruvi.create_default_context`. To
    disable SSL (the default), pass ``False``. If SSL is active, the return
    transport will be an :class:`SslTransport` instance, otherwise it will be a
    :class:`Transport` instance.

    The *server_hostname* parameter is only relevant for SSL connections, and
    specifies the server hostname to use with SNI (Server Name Indication). If
    no server hostname is provided, the hostname specified in *address* is
    used, if available.

    The *local_address* keyword argument is relevant only for TCP transports.
    If provided, it specifies the local address to bind to.

    The *family* and *flags* keyword arguments are used to customize address
    resolution for TCP handles as described in :func:`socket.getaddrinfo`.

    The *mode* parameter specifies if the transport should be put in read-only
    (``'r'``), write-only (``'w'``) or read-write (``'rw'``) mode. For TTY
    transports, the mode must be either read-only or write-only. For all other
    transport the mode should usually be read-write.
    """
    hub = get_hub()
    log = logging.get_logger()
    handle_args = ()
    if isinstance(address, (six.binary_type, six.text_type)):
        handle_type = pyuv.Pipe
        handle_args = (ipc,)
        addresses = [address]
    elif isinstance(address, tuple):
        handle_type = pyuv.TCP
        result = getaddrinfo(address[0], address[1], family, socket.SOCK_STREAM,
                             socket.IPPROTO_TCP, flags)
        addresses = [res[4] for res in result]
        if server_hostname is None:
            server_hostname = address[0]
            # Python 2.7 annoyingly gives a unicode IP address
            if not isinstance(server_hostname, str):
                server_hostname = server_hostname.encode('ascii')
    elif isinstance(address, int):
        if os.isatty(address):
            if mode not in ('r', 'w'):
                raise ValueError("mode: must be either 'r' or 'w' for tty")
            handle = pyuv.TTY(hub.loop, address, mode == 'r')
        else:
            handle = pyuv.Pipe(hub.loop, ipc)
        handle.open(address)
        addresses = []; error = None
    elif isinstance(address, pyuv.Stream):
        handle = address
        addresses = []; error = None
    else:
        raise TypeError('expecting a string, tuple, fd, or pyuv.Stream')
    for addr in addresses:
        log.debug('trying address {}', saddr(addr))
        handle = handle_type(hub.loop, *handle_args)
        error = None
        try:
            if compat.pyuv_pipe_helper(handle, handle_args, 'connect', addr):
                break
            with switch_back(timeout) as switcher:
                handle.connect(addr, switcher)
                result = hub.switch()
                _, error = result[0]
        except pyuv.error.UVError as e:
            error = e[0]
        except Timeout:
            error = pyuv.errno.UV_ETIMEDOUT
        if not error:
            break
        handle.close()
        log.warning('connect() failed with error {}', error)
    if error:
        log.warning('all addresses failed')
        raise TransportError.from_errno(error)
    if local_address:
        handle.bind(*local_address)
    protocol = protocol_factory()
    protocol._timeout = timeout
    if ssl:
        context = ssl if hasattr(ssl, 'set_ciphers') \
                        else ssl(handle) if callable(ssl) \
                        else create_default_context(False)
        transport = SslTransport(handle, context, False, server_hostname)
    else:
        transport = Transport(handle, server_hostname, mode)
    events = transport.start(protocol)
    if events:
        for event in events:
            event.wait()
        transport._check_status()
    return (transport, protocol)

Response: Create a new connection to the given address.


Instruction:
Create a Python 3 function for
creating a new network server.

Response:
def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0,
                  ipc=False, backlog=128):
    """
    Create a new network server.

    This creates one or more :class:`pyuv.Handle` instances bound to *address*,
    puts them in listen mode and starts accepting new connections. For each
    accepted connection, a new transport is created which is connected to a new
    protocol instance obtained by calling *protocol_factory*.

    The *address* argument may be either be a string, a ``(host, port)`` tuple,
    or a ``pyuv.Stream`` handle:

    * If the address is a string, this method creates a new :class:`pyuv.Pipe`
      instance and binds it to *address*.
    * If the address is a tuple, this method creates one or more
      :class:`pyuv.TCP` handles. The first element of the tuple specifies the
      IP address or DNS name, and the second element specifies the port number
      or service name. A transport is created for each resolved address.
    * If the address is a ``pyuv.Stream`` handle, it must already be bound to
      an address.

    The *ssl* parameter indicates whether SSL should be used for accepted
    connections. See :func:`create_connection` for a description.

    The *family* and *flags* keyword arguments are used to customize address
    resolution for TCP handles as described in :func:`socket.getaddrinfo`.

    The *ipc* parameter indicates whether this server will accept new
    connections via file descriptor passing. This works for `pyuv.Pipe` handles
    only, and the user is required to call :meth:`Server.accept_connection`
    whenever a new connection is pending.

    The *backlog* parameter specifies the listen backlog i.e the maximum number
    of not yet accepted active opens to queue. To disable listening for new
    connections (useful when *ipc* was set), set the backlog to ``None``.

    The return value is a :class:`Server` instance.
    """
    server = Server(protocol_factory)
    server.listen(address, ssl=ssl, family=family, flags=flags, backlog=backlog)
    return server


Instruction:
Given the following Python 3 function, write the documentation
def connect(self, address, **kwargs):
        if self._transport:
            raise RuntimeError('already connected')
        kwargs.setdefault('timeout', self._timeout)
        conn = create_connection(self._protocol_factory, address, **kwargs)
        self._transport = conn[0]
        self._transport._log = self._log
        self._protocol = conn[1]
        self._protocol._log = self._log

Response: Connect to a new address and wait for the connection to be established.


Instruction:
Here you have a function in Python 3, explain what it does
def handle_connection(self, client, ssl):
        if ssl:
            context = ssl if hasattr(ssl, 'set_ciphers') \
                            else ssl(client) if callable(ssl) \
                            else create_default_context(True)
            transport = SslTransport(client, context, True)
        else:
            transport = Transport(client)
        transport._log = self._log
        transport._server = self
        if DEBUG:
            self._log.debug('new connection on {}', saddr(client.getsockname()))
            if hasattr(client, 'getpeername'):
                self._log.debug('remote peer is {}', saddr(client.getpeername()))
        protocol = self._protocol_factory()
        protocol._log = self._log
        protocol._timeout = self._timeout
        self._connections[transport] = protocol
        self.connection_made(transport, protocol)
        transport.start(protocol)

Response: Handle a new connection with handle client.


Instruction:
Can you implement a function in Python 3 that
creates a new transport bind it to address and start listening for new connections.

Response:
def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
        """Create a new transport, bind it to *address*, and start listening
        for new connections.

        See :func:`create_server` for a description of *address* and the
        supported keyword arguments.
        """
        handles = []
        handle_args = ()
        if isinstance(address, six.string_types):
            handle_type = pyuv.Pipe
            handle_args = (ipc,)
            addresses = [address]
        elif isinstance(address, tuple):
            handle_type = pyuv.TCP
            result = getaddrinfo(address[0], address[1], family, socket.SOCK_STREAM,
                                 socket.IPPROTO_TCP, flags)
            addresses = [res[4] for res in result]
        elif isinstance(address, pyuv.Stream):
            handles.append(address)
            addresses = []
        else:
            raise TypeError('expecting a string, tuple or pyuv.Stream')
        for addr in addresses:
            handle = handle_type(self._hub.loop, *handle_args)
            try:
                if compat.pyuv_pipe_helper(handle, handle_args, 'bind', addr):
                    handles.append(handle)
                    break
                handle.bind(addr)
            except pyuv.error.UVError as e:
                self._log.warning('bind error {!r}, skipping {}', e[0], saddr(addr))
                continue
            handles.append(handle)
        addresses = []
        for handle in handles:
            if backlog is not None:
                callback = functools.partial(self._on_new_connection, ssl=ssl)
                handle.listen(callback, backlog)
                addr = handle.getsockname()
                self._log.debug('listen on {}', saddr(addr))
            addresses.append(addr)
        self._handles += handles
        self._addresses += addresses


Instruction:
Explain what the following Python 3 code does
def close(self):
        for handle in self._handles:
            if not handle.closed:
                handle.close()
        del self._handles[:]
        for transport, _ in self.connections:
            transport.close()
        self._all_closed.wait()

Response: Close the listening sockets and all accepted connections.


Instruction:
Can you tell what is the following Python 3 function doing
def main(argd=None):
    global DEBUG, debug

    # The argd parameter for main() is for testing purposes only.
    argd = argd or docopt(
        USAGESTR,
        version=VERSIONSTR,
        script=SCRIPT,
        # Example usage of colr_docopt colors.
        colors={
            'header': {'fore': 'yellow'},
            'script': {'fore': 'lightblue', 'style': 'bright'},
            'version': {'fore': 'lightblue'},
        }
    )

    DEBUG = argd['--debug']
    # Load real debug function if available.
    if DEBUG:
        load_debug_deps()
    else:
        debug = noop

    if argd['--auto-disable']:
        auto_disable()

    if argd['--names']:
        return list_names()
    elif argd['--translate']:
        # Just translate a simple code and exit.
        try:
            print('\n'.join(
                translate(
                    argd['CODE'] or read_stdin().split(),
                    rgb_mode=argd['--truecolor'],
                )
            ))
        except ValueError as ex:
            print_err('Translation error: {}'.format(ex))
            return 1
        return 0
    elif argd['--listcodes']:
        # List all escape codes found in some text and exit.
        return list_known_codes(
            argd['TEXT'] or read_stdin(),
            unique=argd['--unique'],
            rgb_mode=argd['--truecolor'],
        )

    txt = argd['TEXT'] or read_stdin()
    fd = sys.stderr if argd['--err'] else sys.stdout
    end = '' if argd['--newline'] else '\n'

    if argd['--stripcodes']:
        txt = justify(strip_codes(txt), argd)
        print(txt, file=fd, end=end)
        return 0

    clr = get_colr(txt, argd)

    # Center, ljust, rjust, or not.
    clr = justify(clr, argd)
    if clr:
        print(str(clr), file=fd, end=end)
        return 0
    # Error while building Colr.
    return 1

Response: Main entry point for the colr_docopt script.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def debug(*args, **kwargs):
    if kwargs.get('file', None) is None:
        kwargs['file'] = sys.stderr
    msg = kwargs.get('sep', ' ').join(str(a) for a in args)
    print('debug: {}'.format(msg), **kwargs)

Response: Print to stderr unless printdebug is installed.


Instruction:
How would you implement a function in Python 3 that
tries popping a key from a dict. Otherwise return the default value.

Response:
def dict_pop_or(d, key, default=None):
    """ Try popping a key from a dict.
        Instead of raising KeyError, just return the default value.
    """
    val = default
    with suppress(KeyError):
        val = d.pop(key)
    return val


Instruction:
Can you create a Python 3 function that
returns a Colr instance based on user args.

Response:
def get_colr(txt, argd):
    """ Return a Colr instance based on user args. """
    fore = parse_colr_arg(
        get_name_arg(argd, '--fore', 'FORE', default=None),
        rgb_mode=argd['--truecolor'],
    )
    back = parse_colr_arg(
        get_name_arg(argd, '--back', 'BACK', default=None),
        rgb_mode=argd['--truecolor'],
    )
    style = get_name_arg(argd, '--style', 'STYLE', default=None)
    if argd['--gradient']:
        # Build a gradient from user args.
        return C(txt).gradient(
            name=argd['--gradient'],
            spread=try_int(argd['--spread'], 1, minimum=0),
            fore=fore,
            back=back,
            style=style,
            rgb_mode=argd['--truecolor'],
        )
    if argd['--gradientrgb']:
        # Build an rgb gradient from user args.
        rgb_start, rgb_stop = parse_gradient_rgb_args(argd['--gradientrgb'])
        return C(txt).gradient_rgb(
            fore=fore,
            back=back,
            style=style,
            start=rgb_start,
            stop=rgb_stop,
        )
    if argd['--rainbow']:
        return C(txt).rainbow(
            fore=fore,
            back=back,
            style=style,
            freq=try_float(argd['--frequency'], 0.1, minimum=0),
            offset=try_int(argd['--offset'], randint(0, 255), minimum=0),
            spread=try_float(argd['--spread'], 3.0, minimum=0),
            rgb_mode=argd['--truecolor'],
        )

    # Normal colored output.
    return C(txt, fore=fore, back=back, style=style)


Instruction:
Write a Python 3 function that can
return the first argument value given in a docopt arg dict.

Response:
def get_name_arg(argd, *argnames, default=None):
    """ Return the first argument value given in a docopt arg dict.
        When not given, return default.
    """
    val = None
    for argname in argnames:
        if argd[argname]:
            val = argd[argname].lower().strip()
            break
    return val if val else default