Instruction:
Can you tell what is the following Python 3 function doing
def match(match_expr, exc_type, exc_value, exc_traceback):
    # Emulate standard behavior when match_expr is an exception subclass.
    if isinstance(match_expr, type) and issubclass(match_expr, BaseException):
        return issubclass(exc_type, match_expr)

    # Match on type and args when match_expr is an exception instance.
    return (
        issubclass(exc_type, type(match_expr))
        and
        match_expr.args == exc_value.args
    )

Response: Match an exception expression.


Instruction:
Given the following Python 3 function, write the documentation
def pycode_to_body(co, context):
    code = Code.from_pycode(co)

    # On each instruction, temporarily store all the jumps to the **next**
    # instruction.  This is used in _make_expr to determine when an expression
    # is part of a short-circuiting expression.
    for a, b in sliding_window(2, code.instrs):
        a._next_target_of = b._target_of
    b._next_target_of = set()

    try:
        body = instrs_to_body(deque(code.instrs), context)
        if context.in_function_block:
            return make_global_and_nonlocal_decls(code.instrs) + body
        return body
    finally:
        # Clean up jump target data.
        for i in code.instrs:
            del i._next_target_of

Response: Convert a Python code object to a list of AST body elements.


Instruction:
How would you implement a function in Python 3 that
converts a list of Instruction objects to a list of AST body nodes.

Response:
def instrs_to_body(instrs, context):
    """
    Convert a list of Instruction objects to a list of AST body nodes.
    """
    stack = []
    body = []
    process_instrs(instrs, stack, body, context)

    if stack:
        raise DecompilationError(
            "Non-empty stack at the end of instrs_to_body(): %s." % stack
        )
    return body


Instruction:
Write a Python 3 function for
processing all the instructions in the instruction queue.

Response:
def process_instrs(queue, stack, body, context):
    """
    Process instructions from the instruction queue.
    """
    next_instr = queue.popleft
    while queue:
        newcontext = _process_instr(next_instr(), queue, stack, body, context)
        if newcontext is not None:
            context = newcontext


Instruction:
Can you generate the documentation for the following Python 3 function
def make_if_statement(instr, queue, stack, context):
    test_expr = make_expr(stack)
    if isinstance(instr, instrs.POP_JUMP_IF_TRUE):
        test_expr = ast.UnaryOp(op=ast.Not(), operand=test_expr)

    first_block = popwhile(op.is_not(instr.arg), queue, side='left')
    if isinstance(first_block[-1], instrs.RETURN_VALUE):
        body = instrs_to_body(first_block, context)
        return ast.If(test=test_expr, body=body, orelse=[])

    jump_to_end = expect(
        first_block.pop(), instrs.JUMP_FORWARD, "at end of if-block"
    )

    body = instrs_to_body(first_block, context)

    # First instruction after the whole if-block.
    end = jump_to_end.arg
    if instr.arg is jump_to_end.arg:
        orelse = []
    else:
        orelse = instrs_to_body(
            popwhile(op.is_not(end), queue, side='left'),
            context,
        )

    return ast.If(test=test_expr, body=body, orelse=orelse)

Response: Make an ast. If block from a POP_JUMP_IF_TRUE or POP_JUMP_IF_FALSE instruction.


Instruction:
How would you explain what the following Python 3 function does
def _process_instr_import_name(instr, queue, stack, body, context):
    # If this is "import module", fromlist is None.
    # If this this is "from module import a, b fromlist will be ('a', 'b').
    fromlist = stack.pop().arg

    # level argument to __import__.  Should be 0, 1, or 2.
    level = stack.pop().arg

    module = instr.arg
    if fromlist is None:  # Regular import.
        attr_loads = _pop_import_LOAD_ATTRs(module, queue)
        store = queue.popleft()
        # There are two cases where we should emit an alias:
        # import a as <anything but a>
        # import a.b.c as <anything (including a)>
        if attr_loads or module.split('.')[0] != store.arg:
            asname = store.arg
        else:
            asname = None
        body.append(
            ast.Import(
                names=[
                    ast.alias(
                        name=module,
                        asname=(asname),
                    ),
                ],
                level=level,
            ),
        )
        return
    elif fromlist == ('*',):  # From module import *.
        expect(queue.popleft(), instrs.IMPORT_STAR, "after IMPORT_NAME")
        body.append(
            ast.ImportFrom(
                module=module,
                names=[ast.alias(name='*', asname=None)],
                level=level,
            ),
        )
        return

    # Consume a pair of IMPORT_FROM, STORE_NAME instructions for each entry in
    # fromlist.
    names = list(map(make_importfrom_alias(queue, body, context), fromlist))
    body.append(ast.ImportFrom(module=module, names=names, level=level))

    # Remove the final POP_TOP of the imported module.
    expect(queue.popleft(), instrs.POP_TOP, "after 'from import'")

Response: Process an IMPORT_NAME instruction.


Instruction:
Explain what the following Python 3 code does
def _pop_import_LOAD_ATTRs(module_name, queue):
    popped = popwhile(is_a(instrs.LOAD_ATTR), queue, side='left')
    if popped:
        expected = module_name.split('.', maxsplit=1)[1]
        actual = '.'.join(map(op.attrgetter('arg'), popped))
        if expected != actual:
            raise DecompilationError(
                "Decompiling import of module %s, but LOAD_ATTRS imply %s" % (
                    expected, actual,
                )
            )
    return popped

Response: Pop LOAD_ATTR instructions for an import of the form a. b. c. d.


Instruction:
Write a Python 3 function for
making an ast. alias node for the names list of an ast. ImportFrom node.

Response:
def make_importfrom_alias(queue, body, context, name):
    """
    Make an ast.alias node for the names list of an ast.ImportFrom.

    Parameters
    ----------
    queue : deque
        Instruction Queue
    body : list
        Current body.
    context : DecompilationContext
    name : str
        Expected name of the IMPORT_FROM node to be popped.

    Returns
    -------
    alias : ast.alias

    Side Effects
    ------------
    Consumes IMPORT_FROM and STORE_NAME instructions from queue.
    """
    import_from, store = queue.popleft(), queue.popleft()
    expect(import_from, instrs.IMPORT_FROM, "after IMPORT_NAME")

    if not import_from.arg == name:
        raise DecompilationError(
            "IMPORT_FROM name mismatch. Expected %r, but got %s." % (
                name, import_from,
            )
        )
    return ast.alias(
        name=name,
        asname=store.arg if store.arg != name else None,
    )


Instruction:
Create a Python 3 function to
set a make_function_context, then push onto the stack.

Response:
def _make_function(instr, queue, stack, body, context):
    """
    Set a make_function_context, then push onto the stack.
    """
    assert stack, "Empty stack before MAKE_FUNCTION."
    prev = stack[-1]
    expect(prev, instrs.LOAD_CONST, "before MAKE_FUNCTION")

    stack.append(instr)

    if is_lambda_name(prev.arg):
        return

    return context.update(
        make_function_context=MakeFunctionContext(
            closure=isinstance(instr, instrs.MAKE_CLOSURE),
        )
    )


Instruction:
Write a Python 3 script for
making an ast. Assign node.

Response:
def make_assignment(instr, queue, stack):
    """
    Make an ast.Assign node.
    """
    value = make_expr(stack)

    # Make assignment targets.
    # If there are multiple assignments (e.g. 'a = b = c'),
    # each LHS expression except the last is preceded by a DUP_TOP instruction.
    # Thus, we make targets until we don't see a DUP_TOP, and then make one
    # more.
    targets = []
    while isinstance(instr, instrs.DUP_TOP):
        targets.append(make_assign_target(queue.popleft(), queue, stack))
        instr = queue.popleft()

    targets.append(make_assign_target(instr, queue, stack))

    return ast.Assign(targets=targets, value=value)


Instruction:
Create a Python 3 function to
pop instructions from queue that form the body of a with - block.

Response:
def pop_with_body_instrs(setup_with_instr, queue):
    """
    Pop instructions from `queue` that form the body of a with block.
    """
    body_instrs = popwhile(op.is_not(setup_with_instr.arg), queue, side='left')

    # Last two instructions should always be POP_BLOCK, LOAD_CONST(None).
    # These don't correspond to anything in the AST, so remove them here.
    load_none = body_instrs.pop()
    expect(load_none, instrs.LOAD_CONST, "at end of with-block")
    pop_block = body_instrs.pop()
    expect(pop_block, instrs.POP_BLOCK, "at end of with-block")
    if load_none.arg is not None:
        raise DecompilationError(
            "Expected LOAD_CONST(None), but got "
            "%r instead" % (load_none)
        )

    # Target of the setup_with should be a WITH_CLEANUP instruction followed by
    # an END_FINALLY.  Neither of these correspond to anything in the AST.
    with_cleanup = queue.popleft()
    expect(with_cleanup, instrs.WITH_CLEANUP, "at end of with-block")
    end_finally = queue.popleft()
    expect(end_finally, instrs.END_FINALLY, "at end of with-block")

    return body_instrs


Instruction:
Write a Python 3 script for
making an ast. withitem node.

Response:
def make_withitem(queue, stack):
    """
    Make an ast.withitem node.
    """
    context_expr = make_expr(stack)
    # This is a POP_TOP for just "with <expr>:".
    # This is a STORE_NAME(name) for "with <expr> as <name>:".
    as_instr = queue.popleft()
    if isinstance(as_instr, (instrs.STORE_FAST,
                             instrs.STORE_NAME,
                             instrs.STORE_DEREF,
                             instrs.STORE_GLOBAL)):
        return ast.withitem(
            context_expr=context_expr,
            optional_vars=make_assign_target(as_instr, queue, stack),
        )
    elif isinstance(as_instr, instrs.POP_TOP):
        return ast.withitem(context_expr=context_expr, optional_vars=None)
    else:
        raise DecompilationError(
            "Don't know how to make withitem from %s" % as_instr,
        )


Instruction:
How would you explain what the following Python 3 function does
def make_for_loop(loop_body_instrs, else_body_instrs, context):
    # Instructions from start until GET_ITER are the builders for the iterator
    # expression.
    iterator_expr = make_expr(
        popwhile(not_a(instrs.GET_ITER), loop_body_instrs, side='left')
    )

    # Next is the GET_ITER instruction, which we don't need.
    loop_body_instrs.popleft()

    # Next is FOR_ITER, which is the jump target for Continue nodes.
    top_of_loop = loop_body_instrs.popleft()

    # This can be a STORE_* or an UNPACK_SEQUENCE followed by some number of
    # stores.
    target = make_assign_target(
        loop_body_instrs.popleft(),
        loop_body_instrs,
        stack=[],
    )

    body, orelse_body = make_loop_body_and_orelse(
        top_of_loop, loop_body_instrs, else_body_instrs, context
    )

    return ast.For(
        target=target,
        iter=iterator_expr,
        body=body,
        orelse=orelse_body,
    )

Response: Make an ast. For node.


Instruction:
Create a Python 3 function to
make the body and orelse lists for a for loop.

Response:
def make_loop_body_and_orelse(top_of_loop, body_instrs, else_instrs, context):
    """
    Make body and orelse lists for a for/while loop whose first instruction is
    `top_of_loop`.

    Parameters
    ----------
    top_of_loop : Instruction
        The first body of the loop.  For a for-loop, this should always be a
        FOR_ITER.  For a while loop, it's the first instruction of the stack
        builders for the loop test expression
    body_instrs : deque
        Queue of Instructions that form the body of the loop.  The last two
        elements of body_instrs should be a JUMP_ABSOLUTE to `top_of_loop` and
        a POP_BLOCK.
    else_instrs : deque
        Queue of Instructions that form the else block of the loop.  Should be
        an empty deque if there is no else block.
    context : DecompilationContext

    Returns
    -------
    body : list[ast.AST]
        List of ast nodes forming the loop body.
    orelse_body : list[ast.AST]
        List of ast nodes forming the else-block body.
    """
    # Remove the JUMP_ABSOLUTE and POP_BLOCK instructions at the bottom of the
    # loop.
    body_instrs.pop()
    body_instrs.pop()
    body = instrs_to_body(body_instrs, context.update(top_of_loop=top_of_loop))

    if else_instrs:
        else_body = instrs_to_body(else_instrs, context)
    else:
        else_body = []

    return body, else_body


Instruction:
Can you generate a brief explanation for the following Python 3 code
def make_while_loop(test_and_body_instrs, else_body_instrs, context):
    top_of_loop = test_and_body_instrs[0]

    # The popped elements are the stack_builders for the loop test expression.
    # The top of the loop_body_instrs is either a POP_JUMP_IF_TRUE or a
    # POP_JUMP_IF_FALSE.
    test, body_instrs = make_while_loop_test_expr(test_and_body_instrs)
    body, orelse_body = make_loop_body_and_orelse(
        top_of_loop, body_instrs, else_body_instrs, context,
    )

    # while-else blocks are not yet supported or handled.
    return ast.While(test=test, body=body, orelse=orelse_body)

Response: Make an ast. While node.


Instruction:
Make a summary of the following Python 3 code
def pop_loop_instrs(setup_loop_instr, queue):
    # Grab everything from left side of the queue until the jump target of
    # SETUP_LOOP.
    body = popwhile(op.is_not(setup_loop_instr.arg), queue, side='left')

    # Anything after the last POP_BLOCK instruction is the else-block.
    else_body = popwhile(not_a(instrs.POP_BLOCK), body, side='right')

    jump_to_top, pop_block = body[-2], body[-1]
    if not isinstance(jump_to_top, instrs.JUMP_ABSOLUTE):
        raise DecompilationError(
            "Penultimate instruction of loop body is "
            "%s, not JUMP_ABSOLUTE." % jump_to_top,
        )

    if not isinstance(pop_block, instrs.POP_BLOCK):
        raise DecompilationError(
            "Last instruction of loop body is "
            "%s, not pop_block." % pop_block,
        )

    loop_expr = jump_to_top.arg
    if isinstance(loop_expr, instrs.FOR_ITER):
        return 'for', body, else_body
    return 'while', body, else_body

Response: Given a SETUP_LOOP instruction and a queue of instructions from the queue pop the instructions from the queue.


Instruction:
Given the following Python 3 function, write the documentation
def _make_expr(toplevel, stack_builders):
    base_expr = _make_expr_internal(toplevel, stack_builders)
    if not toplevel._next_target_of:
        return base_expr

    subexprs = deque([base_expr])
    ops = deque([])
    while stack_builders and stack_builders[-1] in toplevel._next_target_of:
        jump = stack_builders.pop()
        if not isinstance(jump, _BOOLOP_JUMP_TYPES):
            raise DecompilationError(
                "Don't know how to decompile %s inside expression." % jump,
            )
        subexprs.appendleft(make_expr(stack_builders))
        ops.appendleft(_BOOLOP_JUMP_TO_AST_OP[type(jump)]())

    if len(subexprs) <= 1:
        raise DecompilationError(
            "Expected at least one JUMP instruction before expression."
        )

    return normalize_boolop(make_boolop(subexprs, ops))

Response:
Override the single - dispatched make_expr with wrapper logic for handling
    short - circuiting expressions.


Instruction:
Write a Python 3 script to
create a boolop expression from a list of expressions and a list of op_types.

Response:
def make_boolop(exprs, op_types):
    """
    Parameters
    ----------
    exprs : deque
    op_types : deque[{ast.And, ast.Or}]
    """
    if len(op_types) > 1:
        return ast.BoolOp(
            op=op_types.popleft(),
            values=[exprs.popleft(), make_boolop(exprs, op_types)],
        )

    assert len(exprs) == 2
    return ast.BoolOp(op=op_types.popleft(), values=list(exprs))


Instruction:
Write a Python 3 function that can
normalize a boolop by folding together nested And or exprs.

Response:
def normalize_boolop(expr):
    """
    Normalize a boolop by folding together nested And/Or exprs.
    """
    optype = expr.op
    newvalues = []
    for subexpr in expr.values:
        if not isinstance(subexpr, ast.BoolOp):
            newvalues.append(subexpr)
        elif type(subexpr.op) != type(optype):
            newvalues.append(normalize_boolop(subexpr))
        else:
            # Normalize subexpression, then inline its values into the
            # top-level subexpr.
            newvalues.extend(normalize_boolop(subexpr).values)
    return ast.BoolOp(op=optype, values=newvalues)


Instruction:
How would you implement a function in Python 3 that
makes the keywords entry for an ast. Call node.

Response:
def make_call_keywords(stack_builders, count):
    """
    Make the keywords entry for an ast.Call node.
    """
    out = []
    for _ in range(count):
        value = make_expr(stack_builders)
        load_kwname = stack_builders.pop()
        if not isinstance(load_kwname, instrs.LOAD_CONST):
            raise DecompilationError(
                "Expected a LOAD_CONST, but got %r" % load_kwname
            )
        if not isinstance(load_kwname.arg, str):
            raise DecompilationError(
                "Expected LOAD_CONST of a str, but got %r." % load_kwname,
            )
        out.append(ast.keyword(arg=load_kwname.arg, value=value))
    out.reverse()
    return out


Instruction:
Create a Python 3 function to
make the args entry for an ast. Call node.

Response:
def make_call_positionals(stack_builders, count):
    """
    Make the args entry for an ast.Call node.
    """
    out = [make_expr(stack_builders) for _ in range(count)]
    out.reverse()
    return out


Instruction:
Explain what the following Python 3 code does
def make_exprs(stack_builders, count):
    exprs = [make_expr(stack_builders) for _ in range(count)]
    # Elements are on the stack from right to left, but we want them from right
    # to left.
    exprs.reverse()
    return exprs

Response: Make elements of set and list of tuple literal.


Instruction:
Given the following Python 3 function, write the documentation
def _make_expr_empty_dict(toplevel, stack_builders):
    if toplevel.arg:
        raise DecompilationError(
            "make_expr() called with nonzero BUILD_MAP arg %d" % toplevel.arg
        )

    if stack_builders:
        raise DecompilationError(
            "Unexpected stack_builders for BUILD_MAP(0): %s" % stack_builders
        )
    return ast.Dict(keys=[], values=[])

Response: Make an empty dict.


Instruction:
Can you create a Python 3 function that
finds the BUILD_MAP instruction for which the last element of stack_builders is a store.

Response:
def find_build_map(stack_builders):
    """
    Find the BUILD_MAP instruction for which the last element of
    ``stack_builders`` is a store.
    """
    assert isinstance(stack_builders[-1], instrs.STORE_MAP)

    to_consume = 0
    for instr in reversed(stack_builders):
        if isinstance(instr, instrs.STORE_MAP):
            # NOTE: This branch should always be hit on the first iteration.
            to_consume += 1
        elif isinstance(instr, instrs.BUILD_MAP):
            to_consume -= instr.arg
            if to_consume <= 0:
                return instr
    else:
        raise DecompilationError(
            "Couldn't find BUILD_MAP for last element of %s." % stack_builders
        )


Instruction:
Can you tell what is the following Python 3 function doing
def _make_dict_elems(build_instr, builders):
    keys = []
    values = []
    for _ in range(build_instr.arg):
        popped = builders.pop()
        if not isinstance(popped, instrs.STORE_MAP):
            raise DecompilationError(
                "Expected a STORE_MAP but got %s" % popped
            )

        keys.append(make_expr(builders))
        values.append(make_expr(builders))

    # Keys and values are emitted in reverse order of how they appear in the
    # AST.
    keys.reverse()
    values.reverse()
    return keys, values

Response:
Return a list of keys and values for the dictionary literal
    generated by build_instr.


Instruction:
Explain what the following Python 3 code does
def normalize_tuple_slice(node):
    if not any(isinstance(elt, ast.Slice) for elt in node.elts):
        return ast.Index(value=node)

    return ast.ExtSlice(
        [
            # Wrap non-Slice nodes in Index nodes.
            elt if isinstance(elt, ast.Slice) else ast.Index(value=elt)
            for elt in node.elts
        ]
    )

Response:
Normalizes an ast. Tuple node representing the internals of a slice. Returns an ast. ExtSlice node if there are any any
    slices.


Instruction:
Can you implement a function in Python 3 that
returns a handler function for binary operator nodes.

Response:
def _binop_handler(nodetype):
    """
    Factory function for binary operator handlers.
    """
    def _handler(toplevel, stack_builders):
        right = make_expr(stack_builders)
        left = make_expr(stack_builders)
        return ast.BinOp(left=left, op=nodetype(), right=right)
    return _handler


Instruction:
How would you implement a function in Python 3 that
constructs a function from a sequence of builders and a closure.

Response:
def make_function(function_builders, *, closure):
    """
    Construct a FunctionDef AST node from a sequence of the form:

    LOAD_CLOSURE, N times (when handling MAKE_CLOSURE)
    BUILD_TUPLE(N) (when handling MAKE_CLOSURE)
    <decorator builders> (optional)
    <default builders>, (optional)
    <annotation builders> (optional)
    LOAD_CONST(<tuple of annotated names>) (optional)
    LOAD_CONST(code),
    LOAD_CONST(name),
    MAKE_FUNCTION | MAKE_CLOSURE
    <decorator calls> (optional)
    """
    decorator_calls = deque()
    while isinstance(function_builders[-1], instrs.CALL_FUNCTION):
        decorator_calls.appendleft(function_builders.pop())

    *builders, load_code_instr, load_name_instr, make_function_instr = (
        function_builders
    )

    _check_make_function_instrs(
        load_code_instr, load_name_instr, make_function_instr,
    )

    co = load_code_instr.arg
    name = load_name_instr.arg
    args, kwonly, varargs, varkwargs = paramnames(co)

    # Convert default and annotation builders to AST nodes.
    defaults, kw_defaults, annotations = make_defaults_and_annotations(
        make_function_instr,
        builders,
    )

    # Convert decorator function builders.  The stack is in reverse order.
    decorators = [make_expr(builders) for _ in decorator_calls]
    decorators.reverse()

    if closure:
        # There should be a tuple of closure cells still on the stack here.
        # These don't appear in the AST, but we need to consume them to ensure
        # correctness down the line.
        closure_cells = make_closure_cells(builders)  # noqa

    # We should have consumed all our builders by this point.
    if builders:
        raise DecompilationError(
            "Unexpected leftover builders for %s: %s." % (
                make_function_instr, builders
            )
        )

    return ast.FunctionDef(
        body_code=co,
        name=name.split('.')[-1],
        args=make_function_arguments(
            args,
            kwonly,
            varargs,
            varkwargs,
            defaults,
            kw_defaults,
            annotations,
        ),
        body=pycode_to_body(co, DecompilationContext(in_function_block=True)),
        decorator_list=decorators,
        returns=annotations.get('return'),
    )


Instruction:
Can you tell what is the following Python 3 function doing
def make_function_arguments(args,
                            kwonly,
                            varargs,
                            varkwargs,
                            defaults,
                            kw_defaults,
                            annotations):
    """
    Make an ast.arguments from the args parsed out of a code object.
    """
    return ast.arguments(
        args=[ast.arg(arg=a, annotation=annotations.get(a)) for a in args],
        kwonlyargs=[
            ast.arg(arg=a, annotation=annotations.get(a)) for a in kwonly
        ],
        defaults=defaults,
        kw_defaults=list(map(kw_defaults.get, kwonly)),
        vararg=None if varargs is None else ast.arg(
            arg=varargs, annotation=annotations.get(varargs),
        ),
        kwarg=None if varkwargs is None else ast.arg(
            arg=varkwargs, annotation=annotations.get(varkwargs)
        ),
    )

Response: Make an ast. arguments from the args parsed out of a code object.


Instruction:
Write a Python 3 function for
giving a list of instructions in instrs and a list of ast. Global and ast. Nonlocal declarations return a canonical list of ast. Global and ast. Nonlocal declarations.

Response:
def make_global_and_nonlocal_decls(code_instrs):
    """
    Find all STORE_GLOBAL and STORE_DEREF instructions in `instrs` and convert
    them into a canonical list of `ast.Global` and `ast.Nonlocal` declarations.
    """
    globals_ = sorted(set(
        i.arg for i in code_instrs if isinstance(i, instrs.STORE_GLOBAL)
    ))
    nonlocals = sorted(set(
        i.arg for i in code_instrs
        if isinstance(i, instrs.STORE_DEREF) and i.vartype == 'free'
    ))

    out = []
    if globals_:
        out.append(ast.Global(names=globals_))
    if nonlocals:
        out.append(ast.Nonlocal(names=nonlocals))
    return out


Instruction:
Implement a function in Python 3 to
return the AST expressions corresponding to the defaults kwonly defaults and annotations for a function created by make_function_instr.

Response:
def make_defaults_and_annotations(make_function_instr, builders):
    """
    Get the AST expressions corresponding to the defaults, kwonly defaults, and
    annotations for a function created by `make_function_instr`.
    """
    # Integer counts.
    n_defaults, n_kwonlydefaults, n_annotations = unpack_make_function_arg(
        make_function_instr.arg
    )
    if n_annotations:
        # TOS should be a tuple of annotation names.
        load_annotation_names = builders.pop()
        annotations = dict(zip(
            reversed(load_annotation_names.arg),
            (make_expr(builders) for _ in range(n_annotations - 1))
        ))
    else:
        annotations = {}

    kwonlys = {}
    while n_kwonlydefaults:
        default_expr = make_expr(builders)
        key_instr = builders.pop()
        if not isinstance(key_instr, instrs.LOAD_CONST):
            raise DecompilationError(
                "kwonlydefault key is not a LOAD_CONST: %s" % key_instr
            )
        if not isinstance(key_instr.arg, str):
            raise DecompilationError(
                "kwonlydefault key builder is not a "
                "'LOAD_CONST of a string: %s" % key_instr
            )

        kwonlys[key_instr.arg] = default_expr
        n_kwonlydefaults -= 1

    defaults = make_exprs(builders, n_defaults)
    return defaults, kwonlys, annotations


Instruction:
Here you have a function in Python 3, explain what it does
def _check_make_function_instrs(load_code_instr,
                                load_name_instr,
                                make_function_instr,
                                *,
                                expect_lambda=False):
    """
    Validate the instructions passed to a make_function call.
    """

    # Validate load_code_instr.
    if not isinstance(load_code_instr, instrs.LOAD_CONST):
        raise TypeError(
            "make_function expected 'load_code_instr` to be a "
            "LOAD_CONST, but got %s" % load_code_instr,
        )
    if not isinstance(load_code_instr.arg, types.CodeType):
        raise TypeError(
            "make_function expected load_code_instr "
            "to load a code object, but got %s" % load_code_instr.arg,
        )

    # Validate load_name_instr
    if not isinstance(load_name_instr, instrs.LOAD_CONST):
        raise TypeError(
            "make_function expected 'load_name_instr` to be a "
            "LOAD_CONST, but got %s" % load_code_instr,
        )

    if not isinstance(load_name_instr.arg, str):
        raise TypeError(
            "make_function expected load_name_instr "
            "to load a string, but got %r instead" % load_name_instr.arg
        )

    # This is an endswith rather than '==' because the arg is the
    # fully-qualified name.
    is_lambda = is_lambda_name(load_name_instr.arg)
    if expect_lambda and not is_lambda:
        raise ValueError(
            "Expected to make a function named <lambda>, but "
            "got %r instead." % load_name_instr.arg
        )
    if not expect_lambda and is_lambda:
        raise ValueError("Unexpectedly received lambda function.")

    # Validate make_function_instr
    if not isinstance(make_function_instr, (instrs.MAKE_FUNCTION,
                                            instrs.MAKE_CLOSURE)):
        raise TypeError(
            "make_function expected a MAKE_FUNCTION or MAKE_CLOSURE"
            "instruction, but got %s instead." % make_function_instr
        )

Response: Validate the instructions passed to a make_function call.


Instruction:
Here you have a function in Python 3, explain what it does
def pop_arguments(instr, stack):
    needed = instr.stack_effect
    if needed >= 0:
        raise DecompilationError(
            "%s is does not have a negative stack effect" % instr
        )

    for popcount, to_pop in enumerate(reversed(stack), start=1):
        needed += to_pop.stack_effect
        if not needed:
            break
    else:
        raise DecompilationError(
            "Reached end of stack without finding inputs to %s" % instr,
        )

    popped = stack[-popcount:]
    stack[:] = stack[:-popcount]

    return popped

Response:
Pop instructions off stack until we pop all instructions that will
    produce values popped by instr.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _check_stack_for_module_return(stack):
    fail = (
        len(stack) != 1
        or not isinstance(stack[0], instrs.LOAD_CONST)
        or stack[0].arg is not None
    )

    if fail:
        raise DecompilationError(
            "Reached end of non-function code "
            "block with unexpected stack: %s." % stack
        )

Response:
Verify that the stack is in the expected state before the dummy
    RETURN_VALUE instruction.


Instruction:
Write a Python 3 script for
checking that an instruction is of the expected type.

Response:
def expect(instr, expected, context):
    """
    Check that an instruction is of the expected type.
    """
    if not isinstance(instr, expected):
        raise DecompilationError(
            "Expected a {expected} instruction {context}. Got {instr}.".format(
                instr=instr, expected=expected, context=context,
            )
        )
    return instr


Instruction:
Write a Python 3 script to
pop elements off a queue while cond is True.

Response:
def popwhile(cond, queue, *, side):
    """
    Pop elements off a queue while `cond(nextelem)` is True.

    Parameters
    ----------
    cond : predicate
    queue : deque
    side : {'left', 'right'}

    Returns
    -------
    popped : deque

    Examples
    --------
    >>> from collections import deque
    >>> d = deque([1, 2, 3, 2, 1])
    >>> popwhile(lambda x: x < 3, d, side='left')
    deque([1, 2])
    >>> d
    deque([3, 2, 1])
    >>> popwhile(lambda x: x < 3, d, side='right')
    deque([2, 1])
    >>> d
    deque([3])
    """
    if side not in ('left', 'right'):
        raise ValueError("`side` must be one of 'left' or 'right'")

    out = deque()

    if side == 'left':
        popnext = queue.popleft
        pushnext = out.append
        nextidx = 0
    else:
        popnext = queue.pop
        pushnext = out.appendleft
        nextidx = -1

    while queue:
        if not cond(queue[nextidx]):
            break
        pushnext(popnext())
    return out


Instruction:
Can you tell what is the following Python 3 function doing
def paramnames(co):
    flags = co.co_flags
    varnames = co.co_varnames

    argcount, kwonlyargcount = co.co_argcount, co.co_kwonlyargcount
    total = argcount + kwonlyargcount

    args = varnames[:argcount]
    kwonlyargs = varnames[argcount:total]
    varargs, varkwargs = None, None
    if flags & Flag.CO_VARARGS:
        varargs = varnames[total]
        total += 1
    if flags & Flag.CO_VARKEYWORDS:
        varkwargs = varnames[total]

    return args, kwonlyargs, varargs, varkwargs

Response: Get the parameter names from a pycode object.


Instruction:
Write a Python 3 function that can
return the name of the variable manipulated by a uses_free instruction.

Response:
def _freevar_argname(arg, cellvars, freevars):
    """
    Get the name of the variable manipulated by a 'uses_free' instruction.

    Parameters
    ----------
    arg : int
        The raw argument to a uses_free instruction that we want to resolve to
        a name.
    cellvars : list[str]
        The co_cellvars of the function for which we want to resolve `arg`.
    freevars : list[str]
        The co_freevars of the function for which we want to resolve `arg`.

    Notes
    -----
    From https://docs.python.org/3.5/library/dis.html#opcode-LOAD_CLOSURE:

        The name of the variable is co_cellvars[i] if i is less than the length
        of co_cellvars. Otherwise it is co_freevars[i - len(co_cellvars)]
    """
    len_cellvars = len(cellvars)
    if arg < len_cellvars:
        return cellvars[arg]
    return freevars[arg - len_cellvars]


Instruction:
Explain what the following Python 3 code does
def pycode(argcount,
           kwonlyargcount,
           nlocals,
           stacksize,
           flags,
           codestring,
           constants,
           names,
           varnames,
           filename,
           name,
           firstlineno,
           lnotab,
           freevars=(),
           cellvars=()):
    """types.CodeType constructor that accepts keyword arguments.

    See Also
    --------
    types.CodeType
    """
    return CodeType(
        argcount,
        kwonlyargcount,
        nlocals,
        stacksize,
        flags,
        codestring,
        constants,
        names,
        varnames,
        filename,
        name,
        firstlineno,
        lnotab,
        freevars,
        cellvars,
    )

Response: Returns a new CodeType instance that can be used to create a code object.


Instruction:
Here you have a function in Python 3, explain what it does
def from_pycode(cls, co):
        # Make it sparse to instrs[n] is the instruction at bytecode[n]
        sparse_instrs = tuple(
            _sparse_args(
                Instruction.from_opcode(
                    b.opcode,
                    Instruction._no_arg if b.arg is None else _RawArg(b.arg),
                ) for b in Bytecode(co)
            ),
        )
        for idx, instr in enumerate(sparse_instrs):
            if instr is None:
                # The sparse value
                continue
            if instr.absjmp:
                instr.arg = sparse_instrs[instr.arg]
            elif instr.reljmp:
                instr.arg = sparse_instrs[instr.arg + idx + argsize + 1]
            elif isinstance(instr, LOAD_CONST):
                instr.arg = co.co_consts[instr.arg]
            elif instr.uses_name:
                instr.arg = co.co_names[instr.arg]
            elif instr.uses_varname:
                instr.arg = co.co_varnames[instr.arg]
            elif instr.uses_free:
                instr.arg = _freevar_argname(
                    instr.arg,
                    co.co_freevars,
                    co.co_cellvars,
                )
            elif instr.have_arg and isinstance(instr.arg, _RawArg):
                instr.arg = int(instr.arg)

        flags = Flag.unpack(co.co_flags)
        has_vargs = flags['CO_VARARGS']
        has_kwargs = flags['CO_VARKEYWORDS']

        # Here we convert the varnames format into our argnames format.
        paramnames = co.co_varnames[
            :(co.co_argcount +
              co.co_kwonlyargcount +
              has_vargs +
              has_kwargs)
        ]
        # We start with the positional arguments.
        new_paramnames = list(paramnames[:co.co_argcount])
        # Add *args next.
        if has_vargs:
            new_paramnames.append('*' + paramnames[-1 - has_kwargs])
        # Add positional only arguments next.
        new_paramnames.extend(paramnames[
            co.co_argcount:co.co_argcount + co.co_kwonlyargcount
        ])
        # Add **kwargs last.
        if has_kwargs:
            new_paramnames.append('**' + paramnames[-1])

        return cls(
            filter(bool, sparse_instrs),
            argnames=new_paramnames,
            cellvars=co.co_cellvars,
            freevars=co.co_freevars,
            name=co.co_name,
            filename=co.co_filename,
            firstlineno=co.co_firstlineno,
            lnotab={
                lno: sparse_instrs[off] for off, lno in findlinestarts(co)
            },
            flags=flags,
        )

Response: Create a Code object from a python code object.


Instruction:
Create a Python 3 function for
creating a python code object from the more abstract object.

Response:
def to_pycode(self):
        """Create a python code object from the more abstract
        codetransfomer.Code object.

        Returns
        -------
        co : CodeType
            The python code object.
        """
        consts = self.consts
        names = self.names
        varnames = self.varnames
        freevars = self.freevars
        cellvars = self.cellvars
        bc = bytearray()
        for instr in self.instrs:
            bc.append(instr.opcode)  # Write the opcode byte.
            if isinstance(instr, LOAD_CONST):
                # Resolve the constant index.
                bc.extend(consts.index(instr.arg).to_bytes(argsize, 'little'))
            elif instr.uses_name:
                # Resolve the name index.
                bc.extend(names.index(instr.arg).to_bytes(argsize, 'little'))
            elif instr.uses_varname:
                # Resolve the local variable index.
                bc.extend(
                    varnames.index(instr.arg).to_bytes(argsize, 'little'),
                )
            elif instr.uses_free:
                # uses_free is really "uses freevars **or** cellvars".
                try:
                    # look for the name in cellvars
                    bc.extend(
                        cellvars.index(instr.arg).to_bytes(argsize, 'little'),
                    )
                except ValueError:
                    # fall back to freevars, incrementing the length of
                    # cellvars.
                    bc.extend(
                        (freevars.index(instr.arg) + len(cellvars)).to_bytes(
                            argsize,
                            'little',
                        )
                    )
            elif instr.absjmp:
                # Resolve the absolute jump target.
                bc.extend(
                    self.bytecode_offset(instr.arg).to_bytes(
                        argsize,
                        'little',
                    ),
                )
            elif instr.reljmp:
                # Resolve the relative jump target.
                # We do this by subtracting the curren't instructions's
                # sparse index from the sparse index of the argument.
                # We then subtract argsize - 1 to account for the bytes the
                # current instruction takes up.
                bytecode_offset = self.bytecode_offset
                bc.extend((
                    bytecode_offset(instr.arg) -
                    bytecode_offset(instr) -
                    argsize -
                    1
                ).to_bytes(argsize, 'little',))
            elif instr.have_arg:
                # Write any other arg here.
                bc.extend(instr.arg.to_bytes(argsize, 'little'))
            elif WORDCODE:
                # with wordcode, all instructions are padded to 2 bytes
                bc.append(0)

        return CodeType(
            self.argcount,
            self.kwonlyargcount,
            len(varnames),
            self.stacksize,
            self.py_flags,
            bytes(bc),
            consts,
            names,
            varnames,
            self.filename,
            self.name,
            self.firstlineno,
            self.py_lnotab,
            freevars,
            cellvars,
        )


Instruction:
Can you tell what is the following Python 3 function doing
def varnames(self):
        # We must sort to preserve the order between calls.
        # The set comprehension is to drop the duplicates.
        return self._argnames + tuple(sorted({
            instr.arg
            for instr in self.instrs
            if instr.uses_varname and instr.arg not in self._argnames
        }))

Response: The names of all of the local variables in this code object.


Instruction:
Make a summary of the following Python 3 code
def py_lnotab(self):
        reverse_lnotab = reverse_dict(self.lnotab)
        py_lnotab = []
        prev_instr = 0
        prev_lno = self.firstlineno
        for addr, instr in enumerate(_sparse_args(self.instrs)):
            lno = reverse_lnotab.get(instr)
            if lno is None:
                continue

            delta = lno - prev_lno
            py_lnotab.append(addr - prev_instr)
            py_lnotab.append(min(delta, max_lnotab_increment))
            delta -= max_lnotab_increment
            while delta > 0:
                py_lnotab.append(0)
                py_lnotab.append(min(delta, max_lnotab_increment))
                delta -= max_lnotab_increment

            prev_lno = lno
            prev_instr = addr

        return bytes(py_lnotab)

Response: The encoded lnotab that python uses to compute when lines start.


Instruction:
Explain what the following Python 3 code does
def stacksize(self):
        return max(scanl(
            op.add,
            0,
            map(op.attrgetter('stack_effect'), self.instrs),
        ))

Response: The maximum amount of stack space used by this code object.


Instruction:
Implement a Python 3 function for
initializing a unitialized slot to a value.

Response:
def initialize_slot(obj, name, value):
    """Initalize an unitialized slot to a value.

    If there is already a value for this slot, this is a nop.

    Parameters
    ----------
    obj : immutable
        An immutable object.
    name : str
        The name of the slot to initialize.
    value : any
        The value to initialize the slot to.
    """
    if not hasattr(obj, name):
        object_setattr(obj, name, value)


Instruction:
Implement a function in Python 3 to
create the init function for an immutable object.

Response:
def _create_init(name, slots, defaults):
    """Create the __init__ function for an immutable object.

    Parameters
    ----------
    name : str
        The name of the immutable class.
    slots : iterable of str
        The __slots__ field from the class.
    defaults : dict or None
        The default values for the arguments to __init__.

    Returns
    -------
    init : callable
        The __init__ function for the new immutable class.
    """
    if any(s.startswith('__') for s in slots):
        raise TypeError(
            "immutable classes may not have slots that start with '__'",
        )

    # If we have no defaults, ignore all of this.
    kwdefaults = None
    if defaults is not None:
        hit_default = False
        _defaults = []  # positional defaults
        kwdefaults = {}  # kwonly defaults
        kwdefs = False
        for s in slots:
            if s not in defaults and hit_default:
                raise SyntaxError(
                    'non-default argument follows default argument'
                )

            if not kwdefs:
                try:
                    # Try to grab the next default.
                    # Pop so that we know they were all consumed when we
                    # are done.
                    _defaults.append(defaults.pop(s))
                except KeyError:
                    # Not in the dict, we haven't hit any defaults yet.
                    pass
                else:
                    # We are now consuming default arguments.
                    hit_default = True
                if s.startswith('*'):
                    if s in defaults:
                        raise TypeError(
                            'cannot set default for var args or var kwargs',
                        )
                    if not s.startswith('**'):
                        kwdefs = True
            else:
                kwdefaults[s] = defaults.pop(s)

        if defaults:
            # We didn't consume all of the defaults.
            raise TypeError(
                'default value for non-existent argument%s: %s' % (
                    's' if len(defaults) > 1 else '',
                    ', '.join(starmap('{0}={1!r}'.format, defaults.items())),
                )
            )

        # cast back to tuples
        defaults = tuple(_defaults)

    if not slots:
        return _no_arg_init, ()

    ns = {'__initialize_slot': initialize_slot}
    # filter out lone star
    slotnames = tuple(filter(None, (s.strip('*') for s in slots)))
    # We are using exec here so that we can later inspect the call signature
    # of the __init__. This makes the positional vs keywords work as intended.
    # This is totally reasonable, no h8 m8!
    exec(
        'def __init__(_{name}__self, {args}):    \n    {assign}'.format(
            name=name,
            args=', '.join(slots),
            assign='\n    '.join(
                map(
                    '__initialize_slot(_{1}__self, "{0}", {0})'.format,
                    slotnames,
                    repeat(name),
                ),
            ),
        ),
        ns,
    )
    init = ns['__init__']
    init.__defaults__ = defaults
    init.__kwdefaults__ = kwdefaults
    return init, slotnames


Instruction:
Make a summary of the following Python 3 code
def _wrapinit(init):
    try:
        spec = getfullargspec(init)
    except TypeError:
        # we cannot preserve the type signature.
        def __init__(*args, **kwargs):
            self = args[0]
            __setattr__._initializing.add(self)
            init(*args, **kwargs)
            __setattr__._initializing.remove(self)
            _check_missing_slots(self)

        return __init__

    args = spec.args
    varargs = spec.varargs
    if not (args or varargs):
        raise TypeError(
            "%r must accept at least one positional argument for 'self'" %
            getattr(init, '__qualname__', getattr(init, '__name__', init)),
        )

    if not args:
        self = '%s[0]' % varargs
        forward = argspec = '*' + varargs
    else:
        self = args[0]
        forward = argspec = ', '.join(args)

    if args and varargs:
        forward = '%s, *%s' % (forward, spec.varargs)
        argspec = '%s, *%s' % (argspec, spec.varargs)
    if spec.kwonlyargs:
        forward = '%s, %s' % (
            forward,
            ', '.join(map('{0}={0}'.format, spec.kwonlyargs))
        )
        argspec = '%s,%s%s' % (
            argspec,
            '*, ' if not spec.varargs else '',
            ', '.join(spec.kwonlyargs),
        )
    if spec.varkw:
        forward = '%s, **%s' % (forward, spec.varkw)
        argspec = '%s, **%s' % (argspec, spec.varkw)

    ns = {
        '__init': init,
        '__initializing': __setattr__._initializing,
        '__check_missing_slots': _check_missing_slots,
    }
    exec(
        dedent(
            """\
            def __init__({argspec}):
                __initializing.add({self})
                __init({forward})
                __initializing.remove({self})
                __check_missing_slots({self})
            """.format(
                argspec=argspec,
                self=self,
                forward=forward,
            ),
        ),
        ns,
    )
    __init__ = ns['__init__']
    __init__.__defaults__ = spec.defaults
    __init__.__kwdefaults__ = spec.kwonlydefaults
    __init__.__annotations__ = spec.annotations
    return __init__

Response:
Wrap an existing initialize function by thawing self for the duration
AttributeNames of the init.


Instruction:
How would you implement a function in Python 3 that
checks that all the available slots are set in immutable .

Response:
def _check_missing_slots(ob):
    """Check that all slots have been initialized when a custom __init__ method
    is provided.

    Parameters
    ----------
    ob : immutable
        The instance that was just initialized.

    Raises
    ------
    TypeError
        Raised when the instance has not set values that are named in the
        __slots__.
    """
    missing_slots = tuple(
        filter(lambda s: not hasattr(ob, s), ob.__slots__),
    )
    if missing_slots:
        raise TypeError(
            'not all slots initialized in __init__, missing: {0}'.format(
                missing_slots,
            ),
        )


Instruction:
Write a Python 3 script to
reduce ns by f starting with n yielding each intermediate value.

Response:
def scanl(f, n, ns):
    """Reduce ns by f starting with n yielding each intermediate value.

    tuple(scanl(f, n, ns))[-1] == reduce(f, ns, n)

    Parameters
    ----------
    f : callable
        A binary function.
    n : any
        The starting value.
    ns : iterable of any
        The iterable to scan over.

    Yields
    ------
    p : any
        The value of reduce(f, ns[:idx]) where idx is the current index.

    Examples
    --------
    >>> import operator as op
    >>> tuple(scanl(op.add, 0, (1, 2, 3, 4)))
    (0, 1, 3, 6, 10)
    """
    yield n
    for m in ns:
        n = f(n, m)
        yield n


Instruction:
How would you explain what the following Python 3 function does
def ffill(iterable):
    it = iter(iterable)
    previous = next(it)
    yield previous
    for e in it:
        if e is None:
            yield previous
        else:
            previous = e
            yield e

Response: Forward fill non None values in some iterable.


Instruction:
How would you code a function in Python 3 to
convert a ( possibly nested ) iterable into a flattened iterator.

Response:
def flatten(seq, *, recurse_types=(tuple, list, set, frozenset)):
    """
    Convert a (possibly nested) iterator into a flattened iterator.

    Parameters
    ----------
    seq : iterable
        The sequence to flatten.
    recurse_types, optional
        Types to recursively flatten.
        Defaults to (tuple, list, set, frozenset).

    >>> list(flatten((1, (2, 3), ((4,), 5))))
    [1, 2, 3, 4, 5]

    >>> list(flatten(["abc", "def"], recurse_types=(str,)))
    ['a', 'b', 'c', 'd', 'e', 'f']
    """
    for elem in seq:
        if isinstance(elem, recurse_types):
            yield from flatten(elem)
        else:
            yield elem


Instruction:
Can you tell what is the following Python 3 function doing
def types(self):
        out = []
        if self._transform_bytes:
            out.append(bytes)
        if self._transform_str:
            out.append(str)
        return tuple(out)

Response: Returns a tuple containing the types transformed by this transformer.


Instruction:
Given the following Python 3 function, write the documentation
def _transform_constant_sequence(self, seq):
        should_transform = is_a(self.types)

        if not any(filter(should_transform, flatten(seq))):
            # Tuple doesn't contain any transformable strings. Ignore.
            yield LOAD_CONST(seq)
            return

        for const in seq:
            if should_transform(const):
                yield from self.transform_stringlike(const)
            elif isinstance(const, (tuple, frozenset)):
                yield from self._transform_constant_sequence(const)
            else:
                yield LOAD_CONST(const)

        if isinstance(seq, tuple):
            yield BUILD_TUPLE(len(seq))
        else:
            assert isinstance(seq, frozenset)
            yield BUILD_TUPLE(len(seq))
            yield LOAD_CONST(frozenset)
            yield ROT_TWO()
            yield CALL_FUNCTION(1)

Response: Transform a frozenset or tuple.


Instruction:
Here you have a function in Python 3, explain what it does
def transform_stringlike(self, const):
        yield LOAD_CONST(const)
        if isinstance(const, bytes):
            yield from self.bytes_instrs
        elif isinstance(const, str):
            yield from self.str_instrs

Response: Yield instructions to process a str or bytes constant.


Instruction:
Write a Python 3 script for
creating an __init__ method for a call type instruction.

Response:
def _mk_call_init(class_):
    """Create an __init__ function for a call type instruction.

    Parameters
    ----------
    class_ : type
        The type to bind the function to.

    Returns
    -------
    __init__ : callable
        The __init__ method for the class.
    """
    def __init__(self, packed=no_default, *, positional=0, keyword=0):
        if packed is no_default:
            arg = int.from_bytes(bytes((positional, keyword)), 'little')
        elif not positional and not keyword:
            arg = packed
        else:
            raise TypeError('cannot specify packed and unpacked arguments')
        self.positional, self.keyword = arg.to_bytes(2, 'little')
        super(class_, self).__init__(arg)

    return __init__


Instruction:
Write a Python 3 script for
stealing the jump index off of instr. This makes anything that would have jumped to this instruction.

Response:
def steal(self, instr):
        """Steal the jump index off of `instr`.

        This makes anything that would have jumped to `instr` jump to
        this Instruction instead.

        Parameters
        ----------
        instr : Instruction
            The instruction to steal the jump sources from.

        Returns
        -------
        self : Instruction
            The instruction that owns this method.

        Notes
        -----
        This mutates self and ``instr`` inplace.
        """
        instr._stolen_by = self
        for jmp in instr._target_of:
            jmp.arg = self
        self._target_of = instr._target_of
        instr._target_of = set()
        return self


Instruction:
Write a Python 3 script to
create an instruction from an opcode and raw argument.

Response:
def from_opcode(cls, opcode, arg=_no_arg):
        """
        Create an instruction from an opcode and raw argument.

        Parameters
        ----------
        opcode : int
            Opcode for the instruction to create.
        arg : int, optional
            The argument for the instruction.

        Returns
        -------
        intsr : Instruction
            An instance of the instruction named by ``opcode``.
        """
        return type(cls)(opname[opcode], (cls,), {}, opcode=opcode)(arg)


Instruction:
How would you explain what the following Python 3 function does
def stack_effect(self):
        if self.opcode == NOP.opcode:  # noqa
            # dis.stack_effect is broken here
            return 0

        return stack_effect(
            self.opcode,
            *((self.arg if isinstance(self.arg, int) else 0,)
              if self.have_arg else ())
        )

Response: The net effect of executing this instruction on the interpreter stack.


Instruction:
Can you generate the documentation for the following Python 3 function
def equiv(self, instr):
        return type(self) == type(instr) and self.arg == instr.arg

Response: Checks if this instruction is equivalent to another instruction.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def create_environment(home_dir, site_packages=False, clear=False,
                       unzip_setuptools=False,
                       prompt=None, search_dirs=None, download=False,
                       no_setuptools=False, no_pip=False, no_wheel=False,
                       symlink=True):
    """
    Creates a new environment in ``home_dir``.

    If ``site_packages`` is true, then the global ``site-packages/``
    directory will be on the path.

    If ``clear`` is true (default False) then the environment will
    first be cleared.
    """
    home_dir, lib_dir, inc_dir, bin_dir = path_locations(home_dir)

    py_executable = os.path.abspath(install_python(
        home_dir, lib_dir, inc_dir, bin_dir,
        site_packages=site_packages, clear=clear, symlink=symlink))

    install_distutils(home_dir)

    to_install = []

    if not no_setuptools:
        to_install.append('setuptools')

    if not no_pip:
        to_install.append('pip')

    if not no_wheel:
        to_install.append('wheel')

    if to_install:
        install_wheel(
            to_install,
            py_executable,
            search_dirs,
            download=download,
        )

    install_activate(home_dir, bin_dir, prompt)

    install_python_config(home_dir, bin_dir, prompt)

Response: Creates a new environment in the given home_dir.


Instruction:
How would you implement a function in Python 3 that
returns the path locations for the environment.

Response:
def path_locations(home_dir):
    """Return the path locations for the environment (where libraries are,
    where scripts go, etc)"""
    home_dir = os.path.abspath(home_dir)
    # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its
    # prefix arg is broken: http://bugs.python.org/issue3386
    if is_win:
        # Windows has lots of problems with executables with spaces in
        # the name; this function will remove them (using the ~1
        # format):
        mkdir(home_dir)
        if ' ' in home_dir:
            import ctypes
            GetShortPathName = ctypes.windll.kernel32.GetShortPathNameW
            size = max(len(home_dir)+1, 256)
            buf = ctypes.create_unicode_buffer(size)
            try:
                u = unicode
            except NameError:
                u = str
            ret = GetShortPathName(u(home_dir), buf, size)
            if not ret:
                print('Error: the path "%s" has a space in it' % home_dir)
                print('We could not determine the short pathname for it.')
                print('Exiting.')
                sys.exit(3)
            home_dir = str(buf.value)
        lib_dir = join(home_dir, 'Lib')
        inc_dir = join(home_dir, 'Include')
        bin_dir = join(home_dir, 'Scripts')
    if is_jython:
        lib_dir = join(home_dir, 'Lib')
        inc_dir = join(home_dir, 'Include')
        bin_dir = join(home_dir, 'bin')
    elif is_pypy:
        lib_dir = home_dir
        inc_dir = join(home_dir, 'include')
        bin_dir = join(home_dir, 'bin')
    elif not is_win:
        lib_dir = join(home_dir, 'lib', py_version)
        inc_dir = join(home_dir, 'include', py_version + abiflags)
        bin_dir = join(home_dir, 'bin')
    return home_dir, lib_dir, inc_dir, bin_dir


Instruction:
Implement a Python 3 function for
copying tcl and tk libraries on Windows

Response:
def copy_tcltk(src, dest, symlink):
    """ copy tcl/tk libraries on Windows (issue #93) """
    if majver == 2:
        libver = '8.5'
    else:
        libver = '8.6'
    for name in ['tcl', 'tk']:
        srcdir = src + '/tcl/' + name + libver
        dstdir = dest + '/tcl/' + name + libver
        copyfileordir(srcdir, dstdir, symlink)


Instruction:
Implement a function in Python 3 to
install the python modules and returns a new version of the base environment.

Response:
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear, symlink=True):
    """Install just the base environment, no distutils patches etc"""
    if sys.executable.startswith(bin_dir):
        print('Please use the *system* python to run this script')
        return

    if clear:
        rmtree(lib_dir)
        ## FIXME: why not delete it?
        ## Maybe it should delete everything with #!/path/to/venv/python in it
        logger.notify('Not deleting %s', bin_dir)

    if hasattr(sys, 'real_prefix'):
        logger.notify('Using real prefix %r' % sys.real_prefix)
        prefix = sys.real_prefix
    elif hasattr(sys, 'base_prefix'):
        logger.notify('Using base prefix %r' % sys.base_prefix)
        prefix = sys.base_prefix
    else:
        prefix = sys.prefix
    mkdir(lib_dir)
    fix_lib64(lib_dir, symlink)
    stdlib_dirs = [os.path.dirname(os.__file__)]
    if is_win:
        stdlib_dirs.append(join(os.path.dirname(stdlib_dirs[0]), 'DLLs'))
    elif is_darwin:
        stdlib_dirs.append(join(stdlib_dirs[0], 'site-packages'))
    if hasattr(os, 'symlink'):
        logger.info('Symlinking Python bootstrap modules')
    else:
        logger.info('Copying Python bootstrap modules')
    logger.indent += 2
    try:
        # copy required files...
        for stdlib_dir in stdlib_dirs:
            if not os.path.isdir(stdlib_dir):
                continue
            for fn in os.listdir(stdlib_dir):
                bn = os.path.splitext(fn)[0]
                if fn != 'site-packages' and bn in REQUIRED_FILES:
                    copyfile(join(stdlib_dir, fn), join(lib_dir, fn), symlink)
        # ...and modules
        copy_required_modules(home_dir, symlink)
    finally:
        logger.indent -= 2
    # ...copy tcl/tk
    if is_win:
        copy_tcltk(prefix, home_dir, symlink)
    mkdir(join(lib_dir, 'site-packages'))
    import site
    site_filename = site.__file__
    if site_filename.endswith('.pyc') or site_filename.endswith('.pyo'):
        site_filename = site_filename[:-1]
    elif site_filename.endswith('$py.class'):
        site_filename = site_filename.replace('$py.class', '.py')
    site_filename_dst = change_prefix(site_filename, home_dir)
    site_dir = os.path.dirname(site_filename_dst)
    writefile(site_filename_dst, SITE_PY)
    writefile(join(site_dir, 'orig-prefix.txt'), prefix)
    site_packages_filename = join(site_dir, 'no-global-site-packages.txt')
    if not site_packages:
        writefile(site_packages_filename, '')

    if is_pypy or is_win:
        stdinc_dir = join(prefix, 'include')
    else:
        stdinc_dir = join(prefix, 'include', py_version + abiflags)
    if os.path.exists(stdinc_dir):
        copyfile(stdinc_dir, inc_dir, symlink)
    else:
        logger.debug('No include dir %s' % stdinc_dir)

    platinc_dir = distutils.sysconfig.get_python_inc(plat_specific=1)
    if platinc_dir != stdinc_dir:
        platinc_dest = distutils.sysconfig.get_python_inc(
            plat_specific=1, prefix=home_dir)
        if platinc_dir == platinc_dest:
            # Do platinc_dest manually due to a CPython bug;
            # not http://bugs.python.org/issue3386 but a close cousin
            platinc_dest = subst_path(platinc_dir, prefix, home_dir)
        if platinc_dest:
            # PyPy's stdinc_dir and prefix are relative to the original binary
            # (traversing virtualenvs), whereas the platinc_dir is relative to
            # the inner virtualenv and ignores the prefix argument.
            # This seems more evolved than designed.
            copyfile(platinc_dir, platinc_dest, symlink)

    # pypy never uses exec_prefix, just ignore it
    if sys.exec_prefix != prefix and not is_pypy:
        if is_win:
            exec_dir = join(sys.exec_prefix, 'lib')
        elif is_jython:
            exec_dir = join(sys.exec_prefix, 'Lib')
        else:
            exec_dir = join(sys.exec_prefix, 'lib', py_version)
        for fn in os.listdir(exec_dir):
            copyfile(join(exec_dir, fn), join(lib_dir, fn), symlink)

    if is_jython:
        # Jython has either jython-dev.jar and javalib/ dir, or just
        # jython.jar
        for name in 'jython-dev.jar', 'javalib', 'jython.jar':
            src = join(prefix, name)
            if os.path.exists(src):
                copyfile(src, join(home_dir, name), symlink)
        # XXX: registry should always exist after Jython 2.5rc1
        src = join(prefix, 'registry')
        if os.path.exists(src):
            copyfile(src, join(home_dir, 'registry'), symlink=False)
        copyfile(join(prefix, 'cachedir'), join(home_dir, 'cachedir'),
                 symlink=False)

    mkdir(bin_dir)
    py_executable = join(bin_dir, os.path.basename(sys.executable))
    if 'Python.framework' in prefix:
        # OS X framework builds cause validation to break
        # https://github.com/pypa/virtualenv/issues/322
        if os.environ.get('__PYVENV_LAUNCHER__'):
            del os.environ["__PYVENV_LAUNCHER__"]
        if re.search(r'/Python(?:-32|-64)*$', py_executable):
            # The name of the python executable is not quite what
            # we want, rename it.
            py_executable = os.path.join(
                    os.path.dirname(py_executable), 'python')

    logger.notify('New %s executable in %s', expected_exe, py_executable)
    pcbuild_dir = os.path.dirname(sys.executable)
    pyd_pth = os.path.join(lib_dir, 'site-packages', 'virtualenv_builddir_pyd.pth')
    if is_win and os.path.exists(os.path.join(pcbuild_dir, 'build.bat')):
        logger.notify('Detected python running from build directory %s', pcbuild_dir)
        logger.notify('Writing .pth file linking to build directory for *.pyd files')
        writefile(pyd_pth, pcbuild_dir)
    else:
        pcbuild_dir = None
        if os.path.exists(pyd_pth):
            logger.info('Deleting %s (not Windows env or not build directory python)' % pyd_pth)
            os.unlink(pyd_pth)

    if sys.executable != py_executable:
        ## FIXME: could I just hard link?
        executable = sys.executable
        shutil.copyfile(executable, py_executable)
        make_exe(py_executable)
        if is_win or is_cygwin:
            pythonw = os.path.join(os.path.dirname(sys.executable), 'pythonw.exe')
            if os.path.exists(pythonw):
                logger.info('Also created pythonw.exe')
                shutil.copyfile(pythonw, os.path.join(os.path.dirname(py_executable), 'pythonw.exe'))
            python_d = os.path.join(os.path.dirname(sys.executable), 'python_d.exe')
            python_d_dest = os.path.join(os.path.dirname(py_executable), 'python_d.exe')
            if os.path.exists(python_d):
                logger.info('Also created python_d.exe')
                shutil.copyfile(python_d, python_d_dest)
            elif os.path.exists(python_d_dest):
                logger.info('Removed python_d.exe as it is no longer at the source')
                os.unlink(python_d_dest)
            # we need to copy the DLL to enforce that windows will load the correct one.
            # may not exist if we are cygwin.
            py_executable_dll = 'python%s%s.dll' % (
                sys.version_info[0], sys.version_info[1])
            py_executable_dll_d = 'python%s%s_d.dll' % (
                sys.version_info[0], sys.version_info[1])
            pythondll = os.path.join(os.path.dirname(sys.executable), py_executable_dll)
            pythondll_d = os.path.join(os.path.dirname(sys.executable), py_executable_dll_d)
            pythondll_d_dest = os.path.join(os.path.dirname(py_executable), py_executable_dll_d)
            if os.path.exists(pythondll):
                logger.info('Also created %s' % py_executable_dll)
                shutil.copyfile(pythondll, os.path.join(os.path.dirname(py_executable), py_executable_dll))
            if os.path.exists(pythondll_d):
                logger.info('Also created %s' % py_executable_dll_d)
                shutil.copyfile(pythondll_d, pythondll_d_dest)
            elif os.path.exists(pythondll_d_dest):
                logger.info('Removed %s as the source does not exist' % pythondll_d_dest)
                os.unlink(pythondll_d_dest)
        if is_pypy:
            # make a symlink python --> pypy-c
            python_executable = os.path.join(os.path.dirname(py_executable), 'python')
            if sys.platform in ('win32', 'cygwin'):
                python_executable += '.exe'
            logger.info('Also created executable %s' % python_executable)
            copyfile(py_executable, python_executable, symlink)

            if is_win:
                for name in ['libexpat.dll', 'libpypy.dll', 'libpypy-c.dll',
                            'libeay32.dll', 'ssleay32.dll', 'sqlite3.dll',
                            'tcl85.dll', 'tk85.dll']:
                    src = join(prefix, name)
                    if os.path.exists(src):
                        copyfile(src, join(bin_dir, name), symlink)

                for d in sys.path:
                    if d.endswith('lib_pypy'):
                        break
                else:
                    logger.fatal('Could not find lib_pypy in sys.path')
                    raise SystemExit(3)
                logger.info('Copying lib_pypy')
                copyfile(d, os.path.join(home_dir, 'lib_pypy'), symlink)

    if os.path.splitext(os.path.basename(py_executable))[0] != expected_exe:
        secondary_exe = os.path.join(os.path.dirname(py_executable),
                                     expected_exe)
        py_executable_ext = os.path.splitext(py_executable)[1]
        if py_executable_ext.lower() == '.exe':
            # python2.4 gives an extension of '.4' :P
            secondary_exe += py_executable_ext
        if os.path.exists(secondary_exe):
            logger.warn('Not overwriting existing %s script %s (you must use %s)'
                        % (expected_exe, secondary_exe, py_executable))
        else:
            logger.notify('Also creating executable in %s' % secondary_exe)
            shutil.copyfile(sys.executable, secondary_exe)
            make_exe(secondary_exe)

    if '.framework' in prefix:
        if 'Python.framework' in prefix:
            logger.debug('MacOSX Python framework detected')
            # Make sure we use the embedded interpreter inside
            # the framework, even if sys.executable points to
            # the stub executable in ${sys.prefix}/bin
            # See http://groups.google.com/group/python-virtualenv/
            #                              browse_thread/thread/17cab2f85da75951
            original_python = os.path.join(
                prefix, 'Resources/Python.app/Contents/MacOS/Python')
        if 'EPD' in prefix:
            logger.debug('EPD framework detected')
            original_python = os.path.join(prefix, 'bin/python')
        shutil.copy(original_python, py_executable)

        # Copy the framework's dylib into the virtual
        # environment
        virtual_lib = os.path.join(home_dir, '.Python')

        if os.path.exists(virtual_lib):
            os.unlink(virtual_lib)
        copyfile(
            os.path.join(prefix, 'Python'),
            virtual_lib,
            symlink)

        # And then change the install_name of the copied python executable
        try:
            mach_o_change(py_executable,
                          os.path.join(prefix, 'Python'),
                          '@executable_path/../.Python')
        except:
            e = sys.exc_info()[1]
            logger.warn("Could not call mach_o_change: %s. "
                        "Trying to call install_name_tool instead." % e)
            try:
                call_subprocess(
                    ["install_name_tool", "-change",
                     os.path.join(prefix, 'Python'),
                     '@executable_path/../.Python',
                     py_executable])
            except:
                logger.fatal("Could not call install_name_tool -- you must "
                             "have Apple's development tools installed")
                raise

    if not is_win:
        # Ensure that 'python', 'pythonX' and 'pythonX.Y' all exist
        py_exe_version_major = 'python%s' % sys.version_info[0]
        py_exe_version_major_minor = 'python%s.%s' % (
            sys.version_info[0], sys.version_info[1])
        py_exe_no_version = 'python'
        required_symlinks = [ py_exe_no_version, py_exe_version_major,
                         py_exe_version_major_minor ]

        py_executable_base = os.path.basename(py_executable)

        if py_executable_base in required_symlinks:
            # Don't try to symlink to yourself.
            required_symlinks.remove(py_executable_base)

        for pth in required_symlinks:
            full_pth = join(bin_dir, pth)
            if os.path.exists(full_pth):
                os.unlink(full_pth)
            if symlink:
                os.symlink(py_executable_base, full_pth)
            else:
                copyfile(py_executable, full_pth, symlink)

    if is_win and ' ' in py_executable:
        # There's a bug with subprocess on Windows when using a first
        # argument that has a space in it.  Instead we have to quote
        # the value:
        py_executable = '"%s"' % py_executable
    # NOTE: keep this check as one line, cmd.exe doesn't cope with line breaks
    cmd = [py_executable, '-c', 'import sys;out=sys.stdout;'
        'getattr(out, "buffer", out).write(sys.prefix.encode("utf-8"))']
    logger.info('Testing executable with %s %s "%s"' % tuple(cmd))
    try:
        proc = subprocess.Popen(cmd,
                            stdout=subprocess.PIPE)
        proc_stdout, proc_stderr = proc.communicate()
    except OSError:
        e = sys.exc_info()[1]
        if e.errno == errno.EACCES:
            logger.fatal('ERROR: The executable %s could not be run: %s' % (py_executable, e))
            sys.exit(100)
        else:
            raise e

    proc_stdout = proc_stdout.strip().decode("utf-8")
    proc_stdout = os.path.normcase(os.path.abspath(proc_stdout))
    norm_home_dir = os.path.normcase(os.path.abspath(home_dir))
    if hasattr(norm_home_dir, 'decode'):
        norm_home_dir = norm_home_dir.decode(sys.getfilesystemencoding())
    if proc_stdout != norm_home_dir:
        logger.fatal(
            'ERROR: The executable %s is not functioning' % py_executable)
        logger.fatal(
            'ERROR: It thinks sys.prefix is %r (should be %r)'
            % (proc_stdout, norm_home_dir))
        logger.fatal(
            'ERROR: virtualenv is not compatible with this system or executable')
        if is_win:
            logger.fatal(
                'Note: some Windows users have reported this error when they '
                'installed Python for "Only this user" or have multiple '
                'versions of Python installed. Copying the appropriate '
                'PythonXX.dll to the virtualenv Scripts/ directory may fix '
                'this problem.')
        sys.exit(100)
    else:
        logger.info('Got sys.prefix result: %r' % proc_stdout)

    pydistutils = os.path.expanduser('~/.pydistutils.cfg')
    if os.path.exists(pydistutils):
        logger.notify('Please make sure you remove any previous custom paths from '
                      'your %s file.' % pydistutils)
    ## FIXME: really this should be calculated earlier

    fix_local_scheme(home_dir, symlink)

    if site_packages:
        if os.path.exists(site_packages_filename):
            logger.info('Deleting %s' % site_packages_filename)
            os.unlink(site_packages_filename)

    return py_executable


Instruction:
Write a Python 3 script for
fixing lib64 in the current directory.

Response:
def fix_lib64(lib_dir, symlink=True):
    """
    Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y
    instead of lib/pythonX.Y.  If this is such a platform we'll just create a
    symlink so lib64 points to lib
    """
    # PyPy's library path scheme is not affected by this.
    # Return early or we will die on the following assert.
    if is_pypy:
        logger.debug('PyPy detected, skipping lib64 symlinking')
        return
    # Check we have a lib64 library path
    if not [p for p in distutils.sysconfig.get_config_vars().values()
            if isinstance(p, basestring) and 'lib64' in p]:
        return

    logger.debug('This system uses lib64; symlinking lib64 to lib')

    assert os.path.basename(lib_dir) == 'python%s' % sys.version[:3], (
        "Unexpected python lib dir: %r" % lib_dir)
    lib_parent = os.path.dirname(lib_dir)
    top_level = os.path.dirname(lib_parent)
    lib_dir = os.path.join(top_level, 'lib')
    lib64_link = os.path.join(top_level, 'lib64')
    assert os.path.basename(lib_parent) == 'lib', (
        "Unexpected parent dir: %r" % lib_parent)
    if os.path.lexists(lib64_link):
        return
    if symlink:
        os.symlink('lib', lib64_link)
    else:
        copyfile('lib', lib64_link)


Instruction:
Make a summary of the following Python 3 code
def mach_o_change(path, what, value):

    def do_macho(file, bits, endian):
        # Read Mach-O header (the magic number is assumed read by the caller)
        cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags = read_data(file, endian, 6)
        # 64-bits header has one more field.
        if bits == 64:
            read_data(file, endian)
        # The header is followed by ncmds commands
        for n in range(ncmds):
            where = file.tell()
            # Read command header
            cmd, cmdsize = read_data(file, endian, 2)
            if cmd == LC_LOAD_DYLIB:
                # The first data field in LC_LOAD_DYLIB commands is the
                # offset of the name, starting from the beginning of the
                # command.
                name_offset = read_data(file, endian)
                file.seek(where + name_offset, os.SEEK_SET)
                # Read the NUL terminated string
                load = file.read(cmdsize - name_offset).decode()
                load = load[:load.index('\0')]
                # If the string is what is being replaced, overwrite it.
                if load == what:
                    file.seek(where + name_offset, os.SEEK_SET)
                    file.write(value.encode() + '\0'.encode())
            # Seek to the next command
            file.seek(where + cmdsize, os.SEEK_SET)

    def do_file(file, offset=0, size=maxint):
        file = fileview(file, offset, size)
        # Read magic number
        magic = read_data(file, BIG_ENDIAN)
        if magic == FAT_MAGIC:
            # Fat binaries contain nfat_arch Mach-O binaries
            nfat_arch = read_data(file, BIG_ENDIAN)
            for n in range(nfat_arch):
                # Read arch header
                cputype, cpusubtype, offset, size, align = read_data(file, BIG_ENDIAN, 5)
                do_file(file, offset, size)
        elif magic == MH_MAGIC:
            do_macho(file, 32, BIG_ENDIAN)
        elif magic == MH_CIGAM:
            do_macho(file, 32, LITTLE_ENDIAN)
        elif magic == MH_MAGIC_64:
            do_macho(file, 64, BIG_ENDIAN)
        elif magic == MH_CIGAM_64:
            do_macho(file, 64, LITTLE_ENDIAN)

    assert(len(what) >= len(value))

    with open(path, 'r+b') as f:
        do_file(f)

Response: Replace a given name in any Mach - O command found in the given binary with a new name.


Instruction:
Can you generate the documentation for the following Python 3 function
def _get_bin_dir(self):
        for subdir in ("bin", "Scripts"):
            bin_dir = os.path.join(self.abs_home_dir, subdir)
            if os.path.isdir(bin_dir):
                print("bin dir: %r" % bin_dir)
                return bin_dir
        raise RuntimeError("Can't find 'bin/Scripts' dir in: %r" % self.abs_home_dir)

Response: Get the bin dir of the current virtual environment.


Instruction:
Implement a Python 3 function for
getting the python executable in the virtualenv.

Response:
def _get_python_cmd(self):
        """
        return the python executable in the virtualenv.
        Try first sys.executable but use fallbacks.
        """
        file_names = ["pypy.exe", "python.exe", "python"]
        executable = sys.executable
        if executable is not None:
            executable = os.path.split(executable)[1]
            file_names.insert(0, executable)

        return self._get_bin_file(*file_names)


Instruction:
How would you code a function in Python 3 to
return a string representation of a dictionary.

Response:
def hex_repr(d):
    """
    >>> hex_repr({"A":0x1,"B":0xabc})
    'A=$01 B=$0abc'
    """
    txt = []
    for k, v in sorted(d.items()):
        if isinstance(v, int):
            txt.append("%s=%s" % (k, nice_hex(v)))
        else:
            txt.append("%s=%s" % (k, v))
    return " ".join(txt)


Instruction:
Here you have a function in Python 3, explain what it does
def _run_dragonpy_cli(self, *args):
        verbosity = self.frame_settings.var_verbosity.get()
        verbosity_no = VERBOSITY_DICT2[verbosity]
        log.debug("Verbosity: %i (%s)" % (verbosity_no, verbosity))

        args = (
            "--verbosity", "%s" % verbosity_no
            # "--log_list",
            # "--log",
            # "dragonpy.components.cpu6809,40",
            # "dragonpy.Dragon32.MC6821_PIA,50",
        ) + args
        click.echo("\n")
        run_dragonpy(*args, verbose=True)

Response: Run the dragonpy CLI with given args


Instruction:
Can you tell what is the following Python 3 function doing
def _run_command(self, command):
        machine_name = self.frame_run_buttons.var_machine.get()
        self._run_dragonpy_cli("--machine", machine_name, command)

Response: Run DragonPy CLI with given command like run editor or editor


Instruction:
Can you write a function in Python 3 where it
converts an integer to a 0 - padded hex byte string

Response:
def int_to_padded_hex_byte(integer):
    """
        Convert an int to a 0-padded hex byte string
        example: 65 == 41, 10 == 0A
        Returns: The hex byte as string (ex: "0C")
    """
    to_hex = hex(integer)
    xpos = to_hex.find('x')
    hex_byte = to_hex[xpos+1 : len(to_hex)].upper()

    if len(hex_byte) == 1:
        hex_byte = ''.join(['0', hex_byte])

    return hex_byte


Instruction:
Can you write a function in Python 3 where it
computes the checksum byte of a given S - Record object

Response:
def compute_srec_checksum(srec):
    """
        Compute the checksum byte of a given S-Record
        Returns: The checksum as a string hex byte (ex: "0C")
    """
    # Get the summable data from srec
    # start at 2 to remove the S* record entry
    data = srec[2:len(srec)]

    sum = 0
    # For each byte, convert to int and add.
    # (step each two character to form a byte)
    for position in range(0, len(data), 2):
        current_byte = data[position : position+2]
        int_value = int(current_byte, 16)
        sum += int_value

    # Extract the Least significant byte from the hex form
    hex_sum = hex(sum)
    least_significant_byte = hex_sum[len(hex_sum)-2:]
    least_significant_byte = least_significant_byte.replace('x', '0')

    # turn back to int and find the 8-bit one's complement
    int_lsb = int(least_significant_byte, 16)
    computed_checksum = (~int_lsb) & 0xff

    return computed_checksum


Instruction:
Can you generate a brief explanation for the following Python 3 code
def validate_srec_checksum(srec):
    checksum = srec[len(srec)-2:]

    # Strip the original checksum and compare with the computed one
    if compute_srec_checksum(srec[:len(srec) - 2]) == int(checksum, 16):
        return True
    else:
        return False

Response: Validate if the checksum of the supplied s - record is valid.


Instruction:
Create a Python 3 function for
offsetting a given byte in the provided data payload.

Response:
def offset_byte_in_data(target_data, offset, target_byte_pos, readable = False, wraparound = False):
    """
        Offset a given byte in the provided data payload (kind of rot(x))
        readable will return a human-readable representation of the byte+offset
        wraparound will wrap around 255 to 0 (ex: 257 = 2)
        Returns: the offseted byte
    """
    byte_pos = target_byte_pos * 2
    prefix = target_data[:byte_pos]
    suffix = target_data[byte_pos+2:]
    target_byte = target_data[byte_pos:byte_pos+2]
    int_value = int(target_byte, 16)
    int_value += offset

    # Wraparound
    if int_value > 255 and wraparound:
        int_value -= 256

    # Extract readable char for analysis
    if readable:
        if int_value < 256 and int_value > 0:
            offset_byte = get_readable_string(int_value)
        else:
            offset_byte = int_to_padded_hex_byte(int_value)
    else:
        offset_byte = int_to_padded_hex_byte(int_value)

    return ''.join([prefix, offset_byte, suffix])


Instruction:
Can you generate the documentation for the following Python 3 function
def offset_data(data_section, offset, readable = False, wraparound = False):
    for pos in range(0, len(data_section)/2):
        data_section = offset_byte_in_data(data_section, offset, pos, readable, wraparound)

    return data_section

Response: Offset the entire data section by the given offset.


Instruction:
Explain what the following Python 3 code does
def parse_srec(srec):
    record_type = srec[0:2]
    data_len = srec[2:4]
    addr_len = __ADDR_LEN.get(record_type) * 2
    addr = srec[4:4 + addr_len]
    data = srec[4 + addr_len:len(srec)-2]
    checksum = srec[len(srec) - 2:]
    return record_type, data_len, addr, data, checksum

Response: Parse a given S - Record into a tuple of the record type data length addr data and checksum


Instruction:
How would you implement a function in Python 3 that
converts a wav file to another file.

Response:
def convert(source_file, destination_file, cfg):
    """
    convert in every way.
    """
    source_ext = os.path.splitext(source_file)[1]
    source_ext = source_ext.lower()

    dest_ext = os.path.splitext(destination_file)[1]
    dest_ext = dest_ext.lower()

    if source_ext not in (".wav", ".cas", ".bas"):
        raise AssertionError(
            "Source file type %r not supported." % repr(source_ext)
        )
    if dest_ext not in (".wav", ".cas", ".bas"):
        raise AssertionError(
            "Destination file type %r not supported." % repr(dest_ext)
        )

    print "Convert %s -> %s" % (source_ext, dest_ext)

    c = Cassette(cfg)

    if source_ext == ".wav":
        c.add_from_wav(source_file)
    elif source_ext == ".cas":
        c.add_from_cas(source_file)
    elif source_ext == ".bas":
        c.add_from_bas(source_file)
    else:
        raise RuntimeError # Should never happen

    c.print_debug_info()

    if dest_ext == ".wav":
        c.write_wave(destination_file)
    elif dest_ext == ".cas":
        c.write_cas(destination_file)
    elif dest_ext == ".bas":
        c.write_bas(destination_file)
    else:
        raise RuntimeError


Instruction:
Write a Python 3 script for
getting the initial RAM size

Response:
def get_initial_RAM(self):
        """
        init the Dragon RAM
        See: http://archive.worldofdragon.org/phpBB3/viewtopic.php?f=5&t=4444
        """
        mem_FF = [0xff for _ in xrange(4)]
        mem_00 = [0x00 for _ in xrange(4)]

        mem = []
        for _ in xrange(self.RAM_SIZE // 8):
            mem += mem_FF
            mem += mem_00

        return mem


Instruction:
Here you have a function in Python 3, explain what it does
def save_position(self):
        # save text cursor position:
        self.old_text_pos = self.index(tkinter.INSERT)
        # save scroll position:
        self.old_first, self.old_last = self.yview()

Response: save cursor and scroll position


Instruction:
Can you generate the documentation for the following Python 3 function
def restore_position(self):
        # restore text cursor position:
        self.mark_set(tkinter.INSERT, self.old_text_pos)
        # restore scroll position:
        self.yview_moveto(self.old_first)

Response: restore cursor and scroll position


Instruction:
Can you create a Python 3 function that
highlights the current line

Response:
def __update_interval(self):
        """ highlight the current line """
        self.update()
        self.after_id = self.text.after(250, self.__update_interval)


Instruction:
How would you implement a function in Python 3 that
updates the line number

Response:
def update(self, event=None, force=False):
        """ highlight the current line """
        line_no = self.text.index(tkinter.INSERT).split(".")[0]

        # if not force:
            # if line_no == self.current_line:
#                 log.critical("no highlight line needed.")
#                 return

#         log.critical("highlight line: %s" % line_no)
#         self.current_line = line_no

        self.text.tag_remove(self.tag_current_line.id, "1.0", "end")
        self.text.tag_add(self.tag_current_line.id, "%s.0" % line_no, "%s.0+1lines" % line_no)


Instruction:
Explain what the following Python 3 code does
def download(self):
        if os.path.isfile(self.archive_path):
            print("Use %r" % self.archive_path)
            with open(self.archive_path, "rb") as f:
                content = f.read()
        else:
            print("Request: %r..." % self.URL)
            # Warning: HTTPS requests do not do any verification of the server's certificate.
            f = urlopen(self.URL)
            content = f.read()
            with open(self.archive_path, "wb") as out_file:
                out_file.write(content)

        # Check SHA hash:
        current_sha1 = hashlib.sha1(content).hexdigest()
        assert current_sha1 == self.DOWNLOAD_SHA1, "Download sha1 value is wrong! SHA1 is: %r" % current_sha1
        print("Download SHA1: %r, ok." % current_sha1)

Response: Download the content of the current object into the temp directory.


Instruction:
Here you have a function in Python 3, explain what it does
def paste_clipboard(self, event):
        log.critical("paste clipboard")
        clipboard = self.root.clipboard_get()
        for line in clipboard.splitlines():
            log.critical("paste line: %s", repr(line))
            self.add_user_input(line + "\r")

Response: Pastes the contents of the clipboard into the CPU.


Instruction:
How would you explain what the following Python 3 function does
def display_callback(self, cpu_cycles, op_address, address, value):
        self.display.write_byte(cpu_cycles, op_address, address, value)
        return value

Response: Called via memory write_byte_middleware


Instruction:
Can you tell what is the following Python 3 function doing
def fix_virtualenv_tkinter():
    if "TCL_LIBRARY" in os.environ:
        # Fix not needed (e.g. virtualenv issues #93 fixed?)
        return

    if not hasattr(sys, "real_prefix"):
        # we are not in a activated virtualenv
        return

    if sys.version_info[0] == 2:
        # Python v2
        virtualprefix = sys.prefix
        sys.prefix = sys.real_prefix

        import FixTk

        if "TCL_LIBRARY" not in os.environ:
            reload(FixTk)

        sys.prefix = virtualprefix
    else:
        # Python v3
        virtualprefix = sys.base_prefix
        sys.base_prefix = sys.real_prefix

        from tkinter import _fix

        if "TCL_LIBRARY" not in os.environ:
            from imp import reload
            reload(_fix)

        sys.base_prefix = virtualprefix

Response: This function is used to fix the tkinter init. tcl file in a virtualenv.


Instruction:
Given the following Python 3 function, write the documentation
def internal_reset(self):
        log.critical("PIA internal_reset()")
        self.empty_key_toggle = True
        self.current_input_char = None
        self.input_repead = 0

Response:
internal state reset.
        used e.g. in unittests


Instruction:
Given the following Python 3 function, write the documentation
def read_PIA0_A_data(self, cpu_cycles, op_address, address):
        pia0b = self.pia_0_B_data.value  # $ff02

        # FIXME: Find a way to handle CoCo and Dragon in the same way!
        if self.cfg.CONFIG_NAME == COCO2B:
#            log.critical("\t count: %i", self.input_repead)
            if self.input_repead == 7:
                try:
                    self.current_input_char = self.user_input_queue.get_nowait()
                except queue.Empty:
                    self.current_input_char = None
                else:
                    log.critical(
                        "\tget new key from queue: %s", repr(self.current_input_char))
            elif self.input_repead == 18:
#                log.critical("\tForce send 'no key pressed'")
                self.current_input_char = None
            elif self.input_repead > 20:
                self.input_repead = 0

            self.input_repead += 1
        else:  # Dragon
            if pia0b == self.cfg.PIA0B_KEYBOARD_START:  # FIXME
                if self.empty_key_toggle:
                    # Work-a-round for "poor" dragon keyboard scan routine:
                    # The scan routine in ROM ignores key pressed directly behind
                    # one another if they are in the same row!
                    # See "Inside the Dragon" book, page 203 ;)
                    #
                    # Here with the empty_key_toggle, we always send a "no key pressed"
                    # after every key press back and then we send the next key from
                    # the self.user_input_queue
                    #
                    # TODO: We can check the row of the previous key press and only
                    # force a 'no key pressed' if the row is the same
                    self.empty_key_toggle = False
                    self.current_input_char = None
#                     log.critical("\tForce send 'no key pressed'")
                else:
                    try:
                        self.current_input_char = self.user_input_queue.get_nowait()
                    except queue.Empty:
#                        log.critical("\tinput_queue is empty"))
                        self.current_input_char = None
                    else:
#                        log.critical("\tget new key from queue: %s", repr(self.current_input_char))
                        self.empty_key_toggle = True

        if self.current_input_char is None:
#            log.critical("\tno key pressed")
            result = 0xff
            self.empty_key_toggle = False
        else:
#            log.critical("\tsend %s", repr(self.current_input_char))
            result = self.cfg.pia_keymatrix_result(
                self.current_input_char, pia0b)

#         if not is_bit_set(pia0b, bit=7):
# bit 7 | PA7 | joystick comparison input
#             result = clear_bit(result, bit=7)

#         if self.current_input_char is not None:
#             log.critical(
#                 "%04x| read $%04x ($ff02 is $%02x %s) send $%02x %s back\t|%s",
#                 op_address, address,
#                 pia0b, '{0:08b}'.format(pia0b),
#                 result, '{0:08b}'.format(result),
#                 self.cfg.mem_info.get_shortest(op_address)
#             )
        return result

Response: Read the PIA 0 A side data from the system.


Instruction:
Write a Python 3 function for
writing to 0xff00 -> PIA 0 A side Data reg.

Response:
def write_PIA0_A_data(self, cpu_cycles, op_address, address, value):
        """ write to 0xff00 -> PIA 0 A side Data reg. """
        log.error("%04x| write $%02x (%s) to $%04x -> PIA 0 A side Data reg.\t|%s",
            op_address, value, byte2bit_string(value), address,
            self.cfg.mem_info.get_shortest(op_address)
        )
        self.pia_0_A_register.set(value)


Instruction:
Can you tell what is the following Python 3 function doing
def read_PIA0_A_control(self, cpu_cycles, op_address, address):
        value = 0xb3
        log.error(
            "%04x| read $%04x (PIA 0 A side Control reg.) send $%02x (%s) back.\t|%s",
            op_address, address, value, byte2bit_string(value),
            self.cfg.mem_info.get_shortest(op_address)
        )
        return value

Response: read from 0xff01 -> PIA 0 A side control register


Instruction:
Write a Python 3 script for
writing to 0xff01 -> PIA 0 A side control register.

Response:
def write_PIA0_A_control(self, cpu_cycles, op_address, address, value):
        """
        write to 0xff01 -> PIA 0 A side control register

        TODO: Handle IRQ

        bit 7 | IRQ 1 (HSYNC) flag
        bit 6 | IRQ 2 flag(not used)
        bit 5 | Control line 2 (CA2) is an output = 1
        bit 4 | Control line 2 (CA2) set by bit 3 = 1
        bit 3 | select line LSB of analog multiplexor (MUX): 0 = control line 2 LO / 1 = control line 2 HI
        bit 2 | set data direction: 0 = $FF00 is DDR / 1 = $FF00 is normal data lines
        bit 1 | control line 1 (CA1): IRQ polarity 0 = IRQ on HI to LO / 1 = IRQ on LO to HI
        bit 0 | HSYNC IRQ: 0 = disabled IRQ / 1 = enabled IRQ
        """
        log.error(
            "%04x| write $%02x (%s) to $%04x -> PIA 0 A side Control reg.\t|%s",
            op_address, value, byte2bit_string(value), address,
            self.cfg.mem_info.get_shortest(op_address)
        )
        if not is_bit_set(value, bit=2):
            self.pia_0_A_register.select_pdr()
        else:
            self.pia_0_A_register.deselect_pdr()


Instruction:
How would you code a function in Python 3 to
read from 0xff02 - > PIA 0 B side Data reg.

Response:
def read_PIA0_B_data(self, cpu_cycles, op_address, address):
        """
        read from 0xff02 -> PIA 0 B side Data reg.

        bit 7 | PB7 | keyboard matrix column 8
        bit 6 | PB6 | keyboard matrix column 7 / ram size output
        bit 5 | PB5 | keyboard matrix column 6
        bit 4 | PB4 | keyboard matrix column 5
        bit 3 | PB3 | keyboard matrix column 4
        bit 2 | PB2 | keyboard matrix column 3
        bit 1 | PB1 | keyboard matrix column 2
        bit 0 | PB0 | keyboard matrix column 1

        bits 0-7 also printer data lines
        """
        value = self.pia_0_B_data.value  # $ff02
        log.debug(
            "%04x| read $%04x (PIA 0 B side Data reg.) send $%02x (%s) back.\t|%s",
            op_address, address, value, byte2bit_string(value),
            self.cfg.mem_info.get_shortest(op_address)
        )
        return value


Instruction:
Make a summary of the following Python 3 code
def read_PIA0_B_control(self, cpu_cycles, op_address, address):
        value = self.pia_0_B_control.value
        log.error(
            "%04x| read $%04x (PIA 0 B side Control reg.) send $%02x (%s) back.\t|%s",
            op_address, address, value, byte2bit_string(value),
            self.cfg.mem_info.get_shortest(op_address)
        )
        return value

Response: read from 0xff03 -> PIA 0 B side Control reg.