Instruction:
Implement a function in Python 3 to
return a new node that will be used to debug the current node.

Response:
def debug(dbg_opts=None, start_opts=None, post_mortem=True,
          step_ignore=1, level=0):
    """
Enter the debugger.

Parameters
----------

level : how many stack frames go back. Usually it will be
the default 0. But sometimes though there may be calls in setup to the debugger
that you may want to skip.

step_ignore : how many line events to ignore after the
debug() call. 0 means don't even wait for the debug() call to finish.

param dbg_opts : is an optional "options" dictionary that gets fed
trepan.Debugger(); `start_opts' are the optional "options"
dictionary that gets fed to trepan.Debugger.core.start().

Use like this:

.. code-block:: python

    ... # Possibly some Python code
    import trepan.api # Needed only once
    ... # Possibly some more Python code
    trepan.api.debug() # You can wrap inside conditional logic too
    pass  # Stop will be here.
    # Below is code you want to use the debugger to do things.
    ....  # more Python code
    # If you get to a place in the program where you aren't going
    # want to debug any more, but want to remove debugger trace overhead:
    trepan.api.stop()

Parameter "level" specifies how many stack frames go back. Usually it will be
the default 0. But sometimes though there may be calls in setup to the debugger
that you may want to skip.

Parameter "step_ignore" specifies how many line events to ignore after the
debug() call. 0 means don't even wait for the debug() call to finish.

In situations where you want an immediate stop in the "debug" call
rather than the statement following it ("pass" above), add parameter
step_ignore=0 to debug() like this::

    import trepan.api  # Needed only once
    # ... as before
    trepan.api.debug(step_ignore=0)
    # ... as before

Module variable _debugger_obj_ from module trepan.debugger is used as
the debugger instance variable; it can be subsequently used to change
settings or alter behavior. It should be of type Debugger (found in
module trepan). If not, it will get changed to that type::

   $ python
   >>> from trepan.debugger import debugger_obj
   >>> type(debugger_obj)
   <type 'NoneType'>
   >>> import trepan.api
   >>> trepan.api.debug()
   ...
   (Trepan) c
   >>> from trepan.debugger import debugger_obj
   >>> debugger_obj
   <trepan.debugger.Debugger instance at 0x7fbcacd514d0>
   >>>

If however you want your own separate debugger instance, you can
create it from the debugger _class Debugger()_ from module
trepan.debugger::

  $ python
  >>> from trepan.debugger import Debugger
  >>> dbgr = Debugger()  # Add options as desired
  >>> dbgr
  <trepan.debugger.Debugger instance at 0x2e25320>

`dbg_opts' is an optional "options" dictionary that gets fed
trepan.Debugger(); `start_opts' are the optional "options"
dictionary that gets fed to trepan.Debugger.core.start().
"""
    if not isinstance(Mdebugger.debugger_obj, Mdebugger.Trepan):
        Mdebugger.debugger_obj = Mdebugger.Trepan(dbg_opts)
        Mdebugger.debugger_obj.core.add_ignore(debug, stop)
        pass
    core = Mdebugger.debugger_obj.core
    frame = sys._getframe(0+level)
    core.set_next(frame)
    if start_opts and 'startup-profile' in start_opts and start_opts['startup-profile']:
        dbg_initfiles = start_opts['startup-profile']
        from trepan import options
        options.add_startup_file(dbg_initfiles)
        for init_cmdfile in dbg_initfiles:
            core.processor.queue_startfile(init_cmdfile)

    if not core.is_started():
        core.start(start_opts)
        pass
    if post_mortem:
        debugger_on_post_mortem()
        pass
    if 0 == step_ignore:
        frame                   = sys._getframe(1+level)
        core.stop_reason        = 'at a debug() call'
        old_trace_hook_suspend  = core.trace_hook_suspend
        core.trace_hook_suspend = True
        core.processor.event_processor(frame, 'line', None)
        core.trace_hook_suspend = old_trace_hook_suspend
    else:
        core.step_ignore = step_ignore-1
        pass
    return


Instruction:
Can you write a function in Python 3 where it
lists the command categories and a short description of each.

Response:
def list_categories(self):
        """List the command categories and a short description of each."""
        self.section("Classes of commands:")
        cats = list(categories.keys())
        cats.sort()
        for cat in cats:  # Foo! iteritems() doesn't do sorting
            self.msg("  %-13s -- %s" % (cat, categories[cat]))
            pass
        final_msg = """
Type `help` followed by a class name for a list of commands in that class.
Type `help aliases` for a list of current aliases.
Type `help macros` for a list of current macros.
Type `help syntax *item*` for help on syntax *item*
Type `help *` for the list of all commands.
Type `help` *regexp* for the list of commands matching /^#{*regexp*}/
Type `help` followed by command name for full documentation.
"""
        for line in re.compile('\n').split(final_msg.rstrip('\n')):
            self.rst_msg(line)
            pass
        return


Instruction:
Can you generate the documentation for the following Python 3 function
def show_category(self, category, args):
        n2cmd = self.proc.commands
        names = list(n2cmd.keys())
        if len(args) == 1 and args[0] == '*':
            self.section("Commands in class %s:" % category)
            cmds = [cmd for cmd in names if category == n2cmd[cmd].category]
            cmds.sort()
            self.msg_nocr(self.columnize_commands(cmds))
            return

        self.msg("%s.\n" % categories[category])
        self.section("List of commands:")
        names.sort()
        for name in names:  # Foo! iteritems() doesn't do sorting
            if category != n2cmd[name].category: continue
            self.msg("%-13s -- %s" % (name, n2cmd[name].short_help,))
            pass
        return

Response: Show short help for all commands in category.


Instruction:
Make a summary of the following Python 3 code
def readable(path):
    try:
        st = os.stat(path)
        return 0 != st.st_mode & READABLE_MASK
    except os.error:
        return None
    return True

Response: Test whether a path exists and is readable.


Instruction:
Can you write a function in Python 3 where it
parses the argument as filename module : lineno

Response:
def parse_position(errmsg, arg):
    """parse_position(errmsg, arg)->(fn, name, lineno)

    Parse arg as [filename|module:]lineno
    Make sure it works for C:\foo\bar.py:12
    """
    colon = arg.rfind(':')
    if colon >= 0:
        filename = arg[:colon].rstrip()
        m, f = lookupmodule(filename)
        if not f:
            errmsg("'%s' not found using sys.path" % filename)
            return (None, None, None)
        else:
            filename = pyficache.pyc2py(f)
            arg = arg[colon+1:].lstrip()
            pass
        try:
            lineno = int(arg)
        except TypeError:
            errmsg("Bad line number: %s", str(arg))
            return (None, filename, None)
        return (None, filename, lineno)
    return (None, None, None)


Instruction:
Write a Python 3 script for
finding the first frame that is a debugged frame.

Response:
def find_debugged_frame(frame):
    """Find the first frame that is a debugged frame. We do this
    Generally we want traceback information without polluting it with
    debugger frames. We can tell these because those are frames on the
    top which don't have f_trace set. So we'll look back from the top
    to find the fist frame where f_trace is set.
    """
    f_prev = f = frame
    while f is not None and f.f_trace is None:
        f_prev = f
        f = f.f_back
        pass
    if f_prev:
        val = f_prev.f_locals.get('tracer_func_frame')
        if val == f_prev:
            if f_prev.f_back:
                f_prev = f_prev.f_back
                pass
            pass
        pass
    else:
        return frame
    return f_prev


Instruction:
Explain what the following Python 3 code does
def map_thread_names():
    '''Invert threading._active'''
    name2id = {}
    for thread_id in list(threading._active.keys()):
        thread = threading._active[thread_id]
        name = thread.getName()
        if name not in list(name2id.keys()):
            name2id[name] = thread_id
            pass
        pass
    return name2id

Response: Invert threading. _active and return a dictionary of thread names to thread id


Instruction:
Can you implement a function in Python 3 that
opens the input file.

Response:
def open(self, inp, opts=None):
        """Use this to set where to read from.
        """
        if isinstance(inp, list):
            self.input = inp
        else:
            raise IOError("Invalid input type (%s) for %s" % (type(inp), inp))
        return


Instruction:
Write a Python 3 function for
reading a line of input.

Response:
def readline(self, use_raw=None, prompt=''):
        """Read a line of input. EOFError will be raised on EOF.

        Note that we don't support prompting"""
        if self.closed: raise ValueError
        if 0 == len(self.input):
            self.closed = True
            raise EOFError
        line = self.input[0]
        del self.input[0]
        return line


Instruction:
Implement a function in Python 3 to
use this to set where to write to. output can be a string or a file object.

Response:
def open(self, output):
        """Use this to set where to write to. output can be a
        file object or a string. This code raises IOError on error.

        If another file was previously open upon calling this open,
        that will be stacked and will come back into use after
        a close_write().
        """
        if isinstance(output, types.Listype):
            self.output = output
        else:
            raise IOError("Invalid output type (%s) for %s" % (type(output),
                                                                 output))
        return


Instruction:
Can you write a function in Python 3 where it
reads debugger startup file and add it to dbg_initfiles.

Response:
def add_startup_file(dbg_initfiles):
    """ Read debugger startup file(s): both python code and
    debugger profile to dbg_initfiles."""

    startup_python_file = default_configfile('profile.py')

    if Mfile.readable(startup_python_file):
        with codecs.open(startup_python_file, 'r', encoding='utf8') as fp:
                exec(fp.read())

    startup_trepan_file = default_configfile('profile')
    if Mfile.readable(startup_trepan_file):
        if startup_trepan_file not in dbg_initfiles:
            dbg_initfiles.append(startup_trepan_file)
        pass
    return


Instruction:
How would you explain what the following Python 3 function does
def process_options(debugger_name, pkg_version, sys_argv, option_list=None):
    usage_str="""%prog [debugger-options] [python-script [script-options...]]

    Runs the extended python debugger"""

    # serverChoices = ('TCP','FIFO', None)

    optparser = OptionParser(usage=usage_str, option_list=option_list,
                             version="%%prog version %s" % pkg_version)

    optparser.add_option("-X", "--trace", dest="linetrace",
                         action="store_true", default=False,
                         help="Show lines before executing them. "
                         "This option also sets --batch")
    optparser.add_option("-F", "--fntrace", dest="fntrace",
                         action="store_true", default=False,
                         help="Show functions before executing them. "
                         "This option also sets --batch")
    optparser.add_option("--basename", dest="basename",
                         action="store_true", default=False,
                         help="Filenames strip off basename, "
                         "(e.g. for regression tests)"
                         )
    #     optparser.add_option("--batch", dest="noninteractive",
    #                          action="store_true", default=False,
    #                          help="Don't run interactive commands shell on "+
    #                          "stops.")
    optparser.add_option("--client", dest="client",
                         action='store_true',
                         help="Connect to an existing debugger process "
                         "started with the --server option. "
                         "See options for client.")
    optparser.add_option("-x", "--command", dest="command",
                         action="store", type='string', metavar='FILE',
                         help="Execute commands from FILE.")
    optparser.add_option("--cd", dest="cd",
                         action="store", type='string', metavar='DIR',
                         help="Change current directory to DIR.")
    optparser.add_option("--confirm", dest="confirm",
                         action="store_true", default=True,
                         help="Confirm potentially dangerous operations")
    optparser.add_option("--dbg_trepan", dest="dbg_trepan",
                         action="store_true", default=False,
                         help="Debug the debugger")
    optparser.add_option("--different", dest="different",
                         action="store_true", default=True,
                         help="Consecutive stops should have "
                         "different positions")
    #     optparser.add_option("--error", dest="errors", metavar='FILE',
    #                          action="store", type='string',
    #                          help="Write debugger's error output "
    #                          + "(stderr) to FILE")
    optparser.add_option("-e", "--exec", dest="execute", type="string",
                         help="list of debugger commands to " +
                         "execute. Separate the commands with ;;")

    optparser.add_option("-H", "--host", dest="host", default='127.0.0.1',
                         action="store", type='string', metavar='IP-OR-HOST',
                         help="connect IP or host name. "
                         "Only valid if --client option given.")

    optparser.add_option("--highlight", dest="highlight",
                         action="store", type='string',
                         metavar='{light|dark|plain}',
                         default='light',
                         help="Use syntax and terminal highlight output. "
                         "'plain' is no highlight")

    optparser.add_option("--private", dest="private",
                         action='store_true', default=False,
                         help="Don't register this as a global debugger")

    optparser.add_option("--main", dest="main",
                         action="store_true", default=True,
                         help="First stop should be in __main__"
                         )
    optparser.add_option("--no-main", dest="main",
                         action="store_false", default=True,
                         help="First stop should be in __main__"
                         )
    optparser.add_option("--post-mortem", dest="post_mortem",
                         action='store_true', default=True,
                         help=("Enter debugger on an uncaught (fatal) "
                               "exception"))

    optparser.add_option("--no-post-mortem", dest="post_mortem",
                         action='store_false', default=True,
                         help=("Don't enter debugger on an uncaught (fatal) "
                               "exception"))

    optparser.add_option("-n", "--nx", dest="noexecute",
                         action="store_true", default=False,
                         help=("Don't execute commands found in any "
                               "initialization files"))

    optparser.add_option("-o", "--output", dest="output", metavar='FILE',
                         action="store", type='string',
                         help=("Write debugger's output (stdout) "
                               "to FILE"))
    optparser.add_option("-P", "--port", dest="port", default=1027,
                         action="store", type='int',
                         help="Use TCP port number NUMBER for "
                         "out-of-process connections.")

    optparser.add_option("--server", dest="server",
                         action='store_true',
                         help="Out-of-process server connection mode")

    # optparser.add_option("--style", dest="style",
    #                      action="store", type='string',
    #                      metavar='*pygments-style*',
    #                      default=None,
    #                      help=("Pygments style; 'none' "
    #                            "uses 8-color rather than 256-color terminal"))

    optparser.add_option("--sigcheck", dest="sigcheck",
                         action="store_true", default=False,
                         help="Set to watch for signal handler changes")
    optparser.add_option("-t", "--target", dest="target",
                         help=("Specify a target to connect to. Arguments"
                               " should be of form, 'protocol address'.")),
    optparser.add_option("--from_ipython", dest='from_ipython', action='store_true',
                         default=False, help="Called from inside ipython")

    # annotate option produces annotations, used in trepan.el for a
    # better emacs integration. Annotations are similar in purpose to
    # those of GDB (see that manual for a description), although the
    # syntax is different.  they have the following format:
    #
    # ^Z^Zannotation-name
    # <arbitrary text>
    # ^Z^Z
    #
    # where ^Z is the ctrl-Z character, and "annotname" is the name of the
    # annotation. A line with only two ^Z ends the annotation (no nesting
    # allowed). See trepan.el for the usage
    optparser.add_option("--annotate", default=0, type="int",
                         help="Use annotations to work inside emacs")

    # Set up to stop on the first non-option because that's the name
    # of the script to be debugged on arguments following that are
    # that scripts options that should be left untouched.  We would
    # not want to interpret and option for the script, e.g. --help, as
    # one one of our own, e.g. --help.

    optparser.disable_interspersed_args()

    sys.argv = list(sys_argv)
    # FIXME: why does this mess up integration tests?
    # (opts, sys.argv) = optparser.parse_args(sys_argv)
    (opts, sys.argv) = optparser.parse_args()
    dbg_opts = {'from_ipython': opts.from_ipython}

    # Handle debugger startup command files: --nx (-n) and --command.
    dbg_initfiles = []
    if not opts.noexecute:
        add_startup_file(dbg_initfiles)

    # As per gdb, first we execute user initialization files and then
    # we execute any file specified via --command.
    if opts.command:
        dbg_initfiles.append(opts.command)
        pass

    dbg_opts['proc_opts'] = {'initfile_list': dbg_initfiles}

    if opts.cd:
        os.chdir(opts.cd)
        pass

    if opts.output:
        try:
            dbg_opts['output'] = Moutput.DebuggerUserOutput(opts.output)
        except IOError:
            _, xxx_todo_changeme, _ = sys.exc_info()
            (errno, strerror) = xxx_todo_changeme.args
            print("I/O in opening debugger output file %s" % opts.output)
            print("error(%s): %s" % (errno, strerror))
        except:
            print("Unexpected error in opening debugger output file %s" %
                  opts.output)
            print(sys.exc_info()[0])
            sys.exit(2)
            pass
        pass

    return opts, dbg_opts, sys.argv

Response:
Handle debugger options. Set `option_list' if you are writing
    another main program and want to extend the existing set of debugger
    options.

    The options dicionary from optparser is returned. sys_argv is
    also updated.


Instruction:
How would you implement a function in Python 3 that
handles the options that feed into the debugger and sets the appropriate settings.

Response:
def _postprocess_options(dbg, opts):
    ''' Handle options (`opts') that feed into the debugger (`dbg')'''
    # Set dbg.settings['printset']
    print_events = []
    if opts.fntrace:   print_events = ['c_call', 'c_return', 'call', 'return']
    if opts.linetrace: print_events += ['line']
    if len(print_events):
        dbg.settings['printset'] = frozenset(print_events)
        pass

    for setting in ('annotate', 'basename', 'different'):
        dbg.settings[setting] = getattr(opts, setting)
        pass

    if getattr(opts, 'highlight'):
        dbg.settings['highlight'] = opts.highlight
    else:
        dbg.settings['highlight'] = 'plain'

    # if getattr(opts, 'style') and opts.style != 'none':
    #     dbg.settings['style'] = opts.style
    # else:
    #     dbg.settings['style'] = None
    dbg.settings['style'] = None

    # Normally we want to set Mdebugger.debugger_obj so that one can
    # put trepan.debugger breakpoints in a program and not have more
    # than one debugger running. More than one debugger may confuse
    # users, e.g. set different might stop at the same line once for
    # each debugger.
    if not opts.private:
        Mdebugger.debugger_obj = dbg
        pass

    #     if opts.errors:
    #         try:
    #             dbg.stderr = open(opts.errors, 'w')
    #         except IOError, (errno, strerror):
    #             print "I/O in opening debugger output file %s" % opts.errors
    #             print "error(%s): %s" % (errno, strerror)
    #         except ValueError:
    #             print "Could not convert data to an integer."
    #         except:
    #             print "Unexpected error in opening debugger output "
    #                   "file %s" % opts.errors
    #             print sys.exc_info()[0]
    #             sys.exit(2)

    #     if opts.execute:
    #         dbg.cmdqueue = list(opts.execute.split(';;'))

    if opts.post_mortem:
        Mapi.debugger_on_post_mortem()
        pass
    return


Instruction:
Implement a function in Python 3 to
send a message back to the server.

Response:
def read_remote(self):
        '''Send a message back to the server (in contrast to
        the local user output channel).'''
        coded_line = self.inout.read_msg()
        if isinstance(coded_line, bytes):
            coded_line = coded_line.decode("utf-8")
        control = coded_line[0]
        remote_line = coded_line[1:]
        return (control, remote_line)


Instruction:
Given the following Python 3 function, write the documentation
def get_int(errmsg, arg, default=1, cmdname=None):
    if arg:
        try:
            # eval() is used so we will allow arithmetic expressions,
            # variables etc.
            default = int(eval(arg))
        except (SyntaxError, NameError, ValueError):
            if cmdname:
                errmsg("Command '%s' expects an integer; got: %s." %
                       (cmdname, str(arg)))
            else:
                errmsg('Expecting an integer, got: %s.' % str(arg))
                pass
            raise ValueError
    return default

Response: Get an integer from the availabe.


Instruction:
Given the following Python 3 function, write the documentation
def get_onoff(errmsg, arg, default=None, print_error=True):
    if not arg:
        if default is None:
            if print_error:
                errmsg("Expecting 'on', 1, 'off', or 0. Got nothing.")
                pass
            raise ValueError
        return default
    if arg == '1' or arg == 'on': return True
    if arg == '0' or arg =='off': return False

    if print_error:
        errmsg("Expecting 'on', 1, 'off', or 0. Got: %s." % str(arg))
    raise ValueError

Response: Return True if arg is on and False if arg is off.


Instruction:
Implement a function in Python 3 to
set a Boolean - valued debugger setting. obj is a generally a subcommand that has name and debugger. settings attributes. args is a list of strings that can be passed to the debugger.

Response:
def run_set_bool(obj, args):
    """set a Boolean-valued debugger setting. 'obj' is a generally a
    subcommand that has 'name' and 'debugger.settings' attributes"""
    try:
        if 0 == len(args): args = ['on']
        obj.debugger.settings[obj.name] = get_onoff(obj.errmsg, args[0])
    except ValueError:
        pass
    return


Instruction:
Can you implement a function in Python 3 that
sets an Integer -valued debugger setting. obj is a generally a that has name and debugger. settings attributes. msg_on_error is True if the argument is not empty and the value is less than min_value and max_value. msg_on_error is True if the argument is not empty.

Response:
def run_set_int(obj, arg, msg_on_error, min_value=None, max_value=None):
    """set an Integer-valued debugger setting. 'obj' is a generally a
    subcommand that has 'name' and 'debugger.settings' attributes"""
    if '' == arg.strip():
        obj.errmsg("You need to supply a number.")
        return
    obj.debugger.settings[obj.name] = \
        get_an_int(obj.errmsg, arg, msg_on_error, min_value, max_value)
    return obj.debugger.settings[obj.name]


Instruction:
Can you generate a brief explanation for the following Python 3 code
def run_show_bool(obj, what=None):
    val = show_onoff(obj.debugger.settings[obj.name])
    if not what: what = obj.name
    return obj.msg("%s is %s." % (what, val))

Response: Generic subcommand showing a boolean - valued debugger setting.


Instruction:
How would you explain what the following Python 3 function does
def run_show_int(obj, what=None):
    val = obj.debugger.settings[obj.name]
    if not what: what = obj.name
    return obj.msg("%s is %d." % (what, val))

Response: Generic subcommand integer value display


Instruction:
Explain what the following Python 3 code does
def next_opcode(code, offset):
    '''Return the next opcode and offset as a tuple. Tuple (-100,
    -1000) is returned when reaching the end.'''
    n = len(code)
    while offset < n:
        op = code[offset]
        offset += 1
        if op >= HAVE_ARGUMENT:
            offset += 2
            pass
        yield op, offset
        pass
    yield -100, -1000
    pass

Response: Return the next opcode and offset as a tuple. Tuple - 100 is returned when reaching the end. Tuple - 1000 is returned when reaching the end.


Instruction:
How would you code a function in Python 3 to
return True if we are looking at a def statement.

Response:
def is_def_stmt(line, frame):
    """Return True if we are looking at a def statement"""
    # Should really also check that operand of 'LOAD_CONST' is a code object
    return (line and _re_def.match(line) and op_at_frame(frame)=='LOAD_CONST'
            and stmt_contains_opcode(frame.f_code, frame.f_lineno,
                                          'MAKE_FUNCTION'))


Instruction:
Can you implement a function in Python 3 that
returns True if we are looking at a class definition statement.

Response:
def is_class_def(line, frame):
    """Return True if we are looking at a class definition statement"""
    return (line and _re_class.match(line)
            and stmt_contains_opcode(frame.f_code, frame.f_lineno,
                                     'BUILD_CLASS'))


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

        self.debugger.core.stop()
        self.debugger.core.execution_status = 'Quit command'
        raise Mexcept.DebuggerQuit

Response: quit command when there s just one thread


Instruction:
Write a Python 3 script to
quit command when several threads are involved.

Response:
def threaded_quit(self, arg):
        """ quit command when several threads are involved. """
        threading_list = threading.enumerate()
        mythread =  threading.currentThread()
        for t in threading_list:
            if t != mythread:
                ctype_async_raise(t, Mexcept.DebuggerQuit)
                pass
            pass
        raise Mexcept.DebuggerQuit


Instruction:
Make a summary of the following Python 3 code
def set_default_bg():
    term = environ.get('TERM', None)
    if term:
        if (term.startswith('xterm',) or term.startswith('eterm')
            or term == 'dtterm'):
            return False
    return True

Response: Set default background color based on the TERM environment variable


Instruction:
Can you generate a brief explanation for the following Python 3 code
def is_dark_rgb(r, g, b):

    try:
        midpoint = int(environ.get('TERMINAL_COLOR_MIDPOINT', None))
    except:
        pass
    if not midpoint:
        term = environ.get('TERM', None)
        # 117963 = (* .6 (+ 65535 65535 65535))
        # 382.5 = (* .6 (+ 65535 65535 65535))
        print("midpoint", midpoint, 'vs',  (16*5 + 16*g + 16*b))
        midpoint = 383 if term and term == 'xterm-256color' else 117963

    if ( (16*5 + 16*g + 16*b) < midpoint ):
        return True
    else:
        return False

Response: Check if color is dark.


Instruction:
Given the following Python 3 function, write the documentation
def is_dark_color_fg_bg():
    dark_bg = environ.get('DARK_BG', None)
    if dark_bg is not None:
        return dark_bg != '0'
    color_fg_bg = environ.get('COLORFGBG', None)
    if color_fg_bg:
        if color_fg_bg in ('15;0', '15;default;0'):
            return True
        elif color_fg_bg in ('0;15', '0;default;15' ):
            return False
    else:
        return True
    return None

Response: Consult ( environment ) variables DARK_BG and COLORFGBG On return variable is_dark_bg is set


Instruction:
Write a Python 3 script for
handling debugger options. Set `option_list' if you are writing another main program and want to extend the existing set of debugger options. The options dicionary from opt_parser is return. sys_argv is also updated.

Response:
def process_options(debugger_name, pkg_version, sys_argv, option_list=None):
    """Handle debugger options. Set `option_list' if you are writing
    another main program and want to extend the existing set of debugger
    options.

    The options dicionary from opt_parser is return. sys_argv is
    also updated."""
    usage_str="""%prog [debugger-options] [python-script [script-options...]]

       Runs the extended python debugger"""

    # serverChoices = ('TCP','FIFO', None)

    optparser = OptionParser(usage=usage_str, option_list=option_list,
                             version="%%prog version %s" % pkg_version)

    optparser.add_option("-F", "--fntrace", dest="fntrace",
                         action="store_true", default=False,
                         help="Show functions before executing them. " +
                         "This option also sets --batch")
    optparser.add_option("--basename", dest="basename",
                         action="store_true", default=False,
                         help="Filenames strip off basename, "
                         "(e.g. for regression tests)")
    optparser.add_option("--different", dest="different",
                         action="store_true", default=True,
                         help="Consecutive stops should have different "
                         "positions")
    optparser.disable_interspersed_args()

    sys.argv = list(sys_argv)
    (opts, sys.argv) = optparser.parse_args()
    dbg_opts = {}

    return opts, dbg_opts, sys.argv


Instruction:
Explain what the following Python 3 code does
def _postprocess_options(dbg, opts):
    ''' Handle options (`opts') that feed into the debugger (`dbg')'''
    # Set dbg.settings['printset']
    print_events = []
    if opts.fntrace:   print_events = ['c_call', 'c_return', 'call', 'return']
    # if opts.linetrace: print_events += ['line']
    if len(print_events):
        dbg.settings['printset'] = frozenset(print_events)
        pass

    for setting in ('basename', 'different',):
        dbg.settings[setting] = getattr(opts, setting)
        pass

    dbg.settings['highlight'] = 'plain'

    Mdebugger.debugger_obj = dbg
    return

Response: Postprocess options that feed into the debugger.


Instruction:
Implement a Python 3 function for
getting the name of the caller s caller.

Response:
def get_name():
    """Get the name caller's caller.
    NB: f_code.co_filenames and thus this code kind of broken for
    zip'ed eggs circa Jan 2009
    """
    caller = sys._getframe(2)
    filename = caller.f_code.co_filename
    filename = os.path.normcase(os.path.basename(filename))
    return os.path.splitext(filename)[0]


Instruction:
Can you generate the documentation for the following Python 3 function
def signature(frame):
    '''return suitable frame signature to key display expressions off of.'''
    if not frame: return None
    code = frame.f_code
    return (code.co_name, code.co_filename, code.co_firstlineno)

Response: return suitable frame signature to key display expressions off of.


Instruction:
Write a Python 3 script for
listing all display items ; return 0 if none

Response:
def all(self):
        """List all display items; return 0 if none"""
        found = False
        s = []
        for display in self.list:
            if not found:
                s.append("""Auto-display expressions now in effect:
Num Enb Expression""")
                found = True
                pass
            s.append(display.format())
        return s


Instruction:
Can you tell what is the following Python 3 function doing
def delete_index(self, display_number):
        old_size = len(self.list)
        self.list = [disp for disp in self.list
                     if display_number != disp.number]
        return old_size != len(self.list)

Response: Delete the index of a display expression.


Instruction:
How would you explain what the following Python 3 function does
def display(self, frame):
        '''display any items that are active'''
        if not frame: return
        s = []
        sig = signature(frame)
        for display in self.list:
            if display.signature == sig and display.enabled:
                s.append(display.to_s(frame))
                pass
            pass
        return s

Response: display any items that are active


Instruction:
Can you tell what is the following Python 3 function doing
def read_msg(self):
        if self.state == 'connected':
            if 0 == len(self.buf):
                self.buf = self.inout.recv(Mtcpfns.TCP_MAX_PACKET)
                if 0 == (self.buf):
                    self.state = 'disconnected'
                    raise EOFError
                pass
            self.buf, data = Mtcpfns.unpack_msg(self.buf)
            return data.decode('utf-8')
        else:
            raise IOError("read_msg called in state: %s." % self.state)

Response: Read one message unit from the connection.


Instruction:
Write a Python 3 script for
returning the current debugger instance if any.

Response:
def debugger():
    """Return the current debugger instance (if any),
    or creates a new one."""
    dbg = _current[0]
    if dbg is None or not dbg.active:
        dbg = _current[0] = RemoteCeleryTrepan()
    return dbg


Instruction:
Can you implement a function in Python 3 that
sets breakpoint at current location or a specified frame

Response:
def debug(frame=None):
    """Set breakpoint at current location, or a specified frame"""
    # ???
    if frame is None:
        frame = _frame().f_back

    dbg = RemoteCeleryTrepan()
    dbg.say(BANNER.format(self=dbg))
    # dbg.say(SESSION_STARTED.format(self=dbg))
    trepan.api.debug(dbg_opts=dbg.dbg_opts)


Instruction:
Create a Python 3 function for
giving a path to a. py file return the path to its. pyc. pyo file.

Response:
def cache_from_source(path, debug_override=None):
    """Given the path to a .py file, return the path to its .pyc/.pyo file.

    The .py file does not need to exist; this simply returns the path to the
    .pyc/.pyo file calculated as if the .py file were imported.  The extension
    will be .pyc unless sys.flags.optimize is non-zero, then it will be .pyo.

    If debug_override is not None, then it must be a boolean and is used in
    place of sys.flags.optimize.

    If sys.implementation.cache_tag is None then NotImplementedError is raised.

    """
    debug = not sys.flags.optimize if debug_override is None else debug_override
    if debug:
        suffixes = DEBUG_BYTECODE_SUFFIXES
    else:
        suffixes = OPTIMIZED_BYTECODE_SUFFIXES
        pass
    head, tail = os.path.split(path)
    base_filename, sep, _ = tail.partition('.')
    if not hasattr(sys, 'implementation'):
        # Python <= 3.2
        raise NotImplementedError('No sys.implementation')
    tag = sys.implementation.cache_tag
    if tag is None:
        raise NotImplementedError('sys.implementation.cache_tag is None')
    filename = ''.join([base_filename, sep, tag, suffixes[0]])
    return os.path.join(head, _PYCACHE, filename)


Instruction:
Write a Python 3 script to
load all the debugger commands for the given name.

Response:
def _load_debugger_subcommands(self, name):
        """ Create an instance of each of the debugger
        subcommands. Commands are found by importing files in the
        directory 'name' + 'sub'. Some files are excluded via an array set
        in __init__.  For each of the remaining files, we import them
        and scan for class names inside those files and for each class
        name, we will create an instance of that class. The set of
        DebuggerCommand class instances form set of possible debugger
        commands."""

        # Initialization
        cmd_instances     = []
        class_prefix      = capitalize(name)  # e.g. Info, Set, or Show
        module_dir        = 'trepan.processor.command.%s_subcmd' % name
        mod               = __import__(module_dir, None, None, ['*'])
        eval_cmd_template = 'command_mod.%s(self)'

        # Import, instantiate, and add classes for each of the
        # modules found in module_dir imported above.
        for module_name in mod.__modules__:
            import_name = module_dir + '.' + module_name
            try:
                command_mod = importlib.import_module(import_name)
            except ImportError:
                print(("Error importing name %s module %s: %s" %
                      (import_name, module_name, sys.exc_info()[0])))
                continue

            # Even though we tend not to do this, it is possible to
            # put more than one class into a module/file.  So look for
            # all of them.
            classnames = [ classname for classname, classvalue in
                           inspect.getmembers(command_mod, inspect.isclass)
                           if ('DebuggerCommand' != classname and
                               classname.startswith(class_prefix)) ]

            for classname in classnames:
                eval_cmd = eval_cmd_template % classname
                try:
                    instance = eval(eval_cmd)
                    self.cmds.add(instance)
                except:
                    print("Error eval'ing class %s" % classname)
                    pass
                pass
            pass
        return cmd_instances


Instruction:
Here you have a function in Python 3, explain what it does
def help(self, args):
        if len(args) <= 2:
            # "help cmd". Give the general help for the command part.
            doc = self.__doc__ or self.run.__doc__
            if doc:
                self.rst_msg(doc.rstrip('\n'))
            else:
                self.proc.intf[-1].errmsg('Sorry - author mess up. ' +
                                          'No help registered for command' +
                                          self.name)
                pass
            return

        subcmd_name = args[2]

        if '*' == subcmd_name:
            self.section("List of subcommands for command '%s':" % self.name)
            self.msg(self.columnize_commands(self.cmds.list()))
            return

        # "help cmd subcmd". Give help specific for that subcommand.
        cmd = self.cmds.lookup(subcmd_name)
        if cmd:
            doc = cmd.__doc__ or cmd.run.__doc__
            if doc:
                self.proc.rst_msg(doc.rstrip('\n'))
            else:
                self.proc.intf[-1] \
                  .errmsg('Sorry - author mess up. No help registered for '
                          'subcommand %s of command %s' %
                          (subcmd_name, self.name))
                pass
        else:
            cmds = [c for c in self.cmds.list()
                    if re.match('^' + subcmd_name, c) ]
            if cmds == []:
                self.errmsg("No %s subcommands found matching /^%s/. "
                            "Try \"help\"." % (self.name, subcmd_name))
            else:
                self.section("Subcommand(s) of \"%s\" matching /^%s/:" %
                         (self.name, subcmd_name,))
                self.msg_nocr(self.columnize_commands(cmds))
                pass
            pass
        return

Response: Gives help for a command which has subcommands.


Instruction:
Can you tell what is the following Python 3 function doing
def undefined_subcmd(self, cmd, subcmd):
        self.proc.intf[-1].errmsg(('Undefined "%s" subcommand: "%s". ' +
                                  'Try "help %s *".') % (cmd, subcmd, cmd))
        return

Response: Error message when a subcommand is not defined


Instruction:
Implement a function in Python 3 to
execute a code object.

Response:
def runcode(obj, code_obj):
    """Execute a code object.

    When an exception occurs, self.showtraceback() is called to
    display a traceback.  All exceptions are caught except
    SystemExit, which is reraised.

    A note about KeyboardInterrupt: this exception may occur
    elsewhere in this code, and may not always be caught.  The
    caller should be prepared to deal with it.

    """
    try:
        exec(code_obj, obj.locals, obj.globals)
    except SystemExit:
        raise
    except:
        info = sys.exc_info()
        print("%s; %s" % (info[0], info[1]))
    else:
        pass
    return


Instruction:
Explain what the following Python 3 code does
def run(self, args):

        Mframe.adjust_relative(self.proc, self.name, args, self.signum)
        return False

Response: Move the current frame down in the stack trace.


Instruction:
Write a Python 3 function for
resolving a location namedtuple.

Response:
def resolve_location(proc, location):
    """Expand fields in Location namedtuple. If:
       '.':  get fields from stack
       function/module: get fields from evaluation/introspection
       location file and line number: use that
    """
    curframe = proc.curframe
    if location == '.':
        if not curframe:
            proc.errmsg("Don't have a stack to get location from")
            return INVALID_LOCATION
        filename = Mstack.frame2file(proc.core, curframe, canonic=False)
        lineno   = inspect.getlineno(curframe)
        return Location(filename, lineno, False, None)

    assert isinstance(location, Location)
    is_address = False
    if proc.curframe:
        g = curframe.f_globals
        l = curframe.f_locals
    else:
        g = globals()
        l = locals()
        pass
    if location.method:
        # Validate arguments that can't be done in parsing
        filename = lineno = None
        msg = ('Object %s is not known yet as a function, ' % location.method)
        try:
            modfunc = eval(location.method, g, l)
        except:
            proc.errmsg(msg)
            return INVALID_LOCATION

        try:
            # Check if the converted string is a function or instance method
            if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'):
                pass
            else:
                proc.errmsg(msg)
                return INVALID_LOCATION
        except:
            proc.errmsg(msg)
            return INVALID_LOCATION
        filename = proc.core.canonic(modfunc.__code__.co_filename)
        # FIXME: we may want to check lineno and
        # respect that in the future
        lineno   = modfunc.__code__.co_firstlineno
    elif location.path:
        filename = proc.core.canonic(location.path)
        lineno  =  location.line_number
        modfunc  = None
        msg = "%s is not known as a file" % location.path
        if not osp.isfile(filename):
            # See if argument is a module
            try:
                modfunc = eval(location.path, g, l)
            except:
                msg = ("Don't see '%s' as a existing file or as an module"
                       % location.path)
                proc.errmsg(msg)
                return INVALID_LOCATION
            pass
            is_address = location.is_address
            if inspect.ismodule(modfunc):
                if hasattr(modfunc, '__file__'):
                    filename = pyficache.pyc2py(modfunc.__file__)
                    filename = proc.core.canonic(filename)
                    if not lineno:
                        # use first line of module file
                        lineno = 1
                        is_address = False
                    return Location(filename, lineno, is_address, modfunc)
                else:
                    msg = ("module '%s' doesn't have a file associated with it" %
                            location.path)

            proc.errmsg(msg)
            return INVALID_LOCATION
        maxline = pyficache.maxline(filename)
        if maxline and lineno > maxline:
            # NB: we use the gdb wording here
            proc.errmsg("Line number %d out of range; %s has %d lines."
                        % (lineno, filename, maxline))
            return INVALID_LOCATION
    elif location.line_number:
        filename   = Mstack.frame2file(proc.core, curframe, canonic=False)
        lineno     = location.line_number
        is_address = location.is_address
        modfunc  = None
    return Location(filename, lineno, is_address, modfunc)


Instruction:
Can you generate the documentation for the following Python 3 function
def resolve_address_location(proc, location):
    curframe = proc.curframe
    if location == '.':
        filename = Mstack.frame2file(proc.core, curframe, canonic=False)
        offset   = curframe.f_lasti
        is_address = True
        return Location(filename, offset, False, None)

    assert isinstance(location, Location)
    is_address = True
    if proc.curframe:
        g = curframe.f_globals
        l = curframe.f_locals
    else:
        g = globals()
        l = locals()
        pass
    if location.method:
        # Validate arguments that can't be done in parsing
        filename = offset = None
        msg = ('Object %s is not known yet as a function, ' % location.method)
        try:
            modfunc = eval(location.method, g, l)
        except:
            proc.errmsg(msg)
            return INVALID_LOCATION

        try:
            # Check if the converted string is a function or instance method
            if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'):
                pass
            else:
                proc.errmsg(msg)
                return INVALID_LOCATION
        except:
            proc.errmsg(msg)
            return INVALID_LOCATION
        filename = proc.core.canonic(modfunc.func_code.co_filename)
        # FIXME: we may want to check offset and
        # respect that in the future
        offset   = 0
    elif location.path:
        filename = proc.core.canonic(location.path)
        offset  =  location.line_number
        is_address = location.is_address
        modfunc  = None
        msg = "%s is not known as a file" % location.path
        if not osp.isfile(filename):
            # See if argument is a module
            try:
                modfunc = eval(location.path, g, l)
            except:
                msg = ("Don't see '%s' as a existing file or as an module"
                       % location.path)
                proc.errmsg(msg)
                return INVALID_LOCATION
            pass
            is_address = location.is_address
            if inspect.ismodule(modfunc):
                if hasattr(modfunc, '__file__'):
                    filename = pyficache.pyc2py(modfunc.__file__)
                    filename = proc.core.canonic(filename)
                    if not offset:
                        # use first offset of module file
                        offset = 0
                        is_address = True
                    return Location(filename, offset, is_address, modfunc)
                else:
                    msg = ("module '%s' doesn't have a file associated with it" %
                            location.path)

            proc.errmsg(msg)
            return INVALID_LOCATION
        maxline = pyficache.maxline(filename)
        if maxline and offset > maxline:
            # NB: we use the gdb wording here
            proc.errmsg("Line number %d out of range; %s has %d lines."
                        % (offset, filename, maxline))
            return INVALID_LOCATION
    elif location.line_number is not None:
        filename   = Mstack.frame2file(proc.core, curframe, canonic=False)
        offset     = location.line_number
        is_address = location.is_address
        modfunc    = proc.list_object
    return Location(filename, offset, is_address, modfunc)

Response: Resolve the address location in the named tuple.


Instruction:
Implement a function in Python 3 to
find and set the debugger frame state to the frame which is in the current thread.

Response:
def find_and_set_debugged_frame(self, frame, thread_id):
        '''The dance we have to do to set debugger frame state to
        *frame*, which is in the thread with id *thread_id*. We may
        need to the hide initial debugger frames.
        '''
        thread = threading._active[thread_id]
        thread_name = thread.getName()
        if (not self.settings['dbg_trepan'] and
            thread_name == Mthread.current_thread_name()):
            # The frame we came in on ('current_thread_name') is
            # the same as the one we want to switch to. In this case
            # we need to some debugger frames are in this stack so
            # we need to remove them.
            newframe = Mthread.find_debugged_frame(frame)
            if newframe is not None:  frame = newframe
            pass
        # FIXME: else: we might be blocked on other threads which are
        # about to go into the debugger it not for the fact this one got there
        # first. Possibly in the future we want
        # to hide the blocks into threading of that locking code as well.

        # Set stack to new frame
        self.stack, self.curindex = Mcmdproc.get_stack(frame, None,
                                                       self.proc)
        self.proc.stack, self.proc.curindex = self.stack, self.curindex
        self.proc.frame_thread_name = thread_name
        return


Instruction:
Create a Python 3 function for
seeing if *name_or_id* is either a thread name or a thread id.

Response:
def get_from_thread_name_or_id(self, name_or_id, report_error=True):
        '''See if *name_or_id* is either a thread name or a thread id.
        The frame of that id/name is returned, or None if name_or_id is
        invalid.'''
        thread_id = self.proc.get_int_noerr(name_or_id)
        if thread_id is None:
            # Must be a "frame" command with frame name, not a frame
            # number (or invalid command).
            name2id = Mthread.map_thread_names()
            if name_or_id == '.':
                name_or_id = Mthread.current_thread_name()
                pass
            thread_id = name2id.get(name_or_id)
            if thread_id is None:
                self.errmsg("I don't know about thread name %s." %
                            name_or_id)
                return None, None
            pass
        # Above we should have set thread_id. Now see if we can
        # find it.
        threads   = sys._current_frames()
        frame     = threads.get(thread_id)
        if frame is None and report_error:
            self.errmsg("I don't know about thread number %s (%d)." %
                        name_or_id, thread_id)
            # self.info_thread_terse()
            return None, None
        return frame, thread_id


Instruction:
Can you create a Python 3 function that
runs a frame command. This routine is a little complex because we allow a number parameter variations.

Response:
def run(self, args):
        '''Run a frame command. This routine is a little complex
        because we allow a number parameter variations.'''

        if len(args) == 1:
            # Form is: "frame" which means "frame 0"
            position_str = '0'
        elif len(args) == 2:
            # Form is: "frame {position | thread}
            name_or_id = args[1]
            frame, thread_id = self.get_from_thread_name_or_id(name_or_id,
                                                               False)
            if frame is None:
                # Form should be: frame position
                position_str = name_or_id
            else:
                # Form should be: "frame thread" which means
                # "frame thread 0"
                position_str = '0'
                self.find_and_set_debugged_frame(frame, thread_id)
                pass
        elif len(args) == 3:
            # Form is: frame <thread> <position>
            name_or_id = args[1]
            position_str = args[2]
            frame, thread_id = self.get_from_thread_name_or_id(name_or_id)
            if frame is None:
                # Error message was given in routine
                return
            self.find_and_set_debugged_frame(frame, thread_id)
            pass
        self.one_arg_run(position_str)
        return False


Instruction:
Create a Python 3 function to
try to pretty print a simple array.

Response:
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''):
    '''Try to pretty print a simple case where a list is not nested.
    Return True if we can do it and False if not. '''

    if type(val) != list:
        return False

    numeric = True
    for i in range(len(val)):
        if not (type(val[i]) in [bool, float, int]):
            numeric = False
            if not (type(val[i]) in [bool, float, int, bytes]):
                return False
            pass
        pass
    mess = columnize([repr(v) for v in val],
                     opts={"arrange_array": True,
                           "lineprefix": lineprefix,
                           "displaywidth": int(displaywidth)-3,
                           'ljust': not numeric})
    msg_nocr(mess)
    return True


Instruction:
Can you generate a brief explanation for the following Python 3 code
def main(dbg=None, sys_argv=list(sys.argv)):
    global __title__

    # Save the original just for use in the restart that works via exec.
    orig_sys_argv = list(sys_argv)
    opts, dbg_opts, sys_argv  = Moptions.process_options(__title__,
                                                         VERSION,
                                                         sys_argv)

    if opts.server is not None:
        if opts.server == 'tcp':
            connection_opts={'IO': 'TCP', 'PORT': opts.port}
        else:
            connection_opts={'IO': 'FIFO'}
        intf = Mserver.ServerInterface(connection_opts=connection_opts)
        dbg_opts['interface'] = intf
        if 'FIFO' == intf.server_type:
            print('Starting FIFO server for process %s.' % os.getpid())
        elif 'TCP' == intf.server_type:
            print('Starting TCP server listening on port %s.' %
                  intf.inout.PORT)
            pass
    elif opts.client:
        Mclient.run(opts, sys_argv)
        return

    dbg_opts['orig_sys_argv'] = orig_sys_argv

    if dbg is None:
        dbg = Mdebugger.Trepan(dbg_opts)
        dbg.core.add_ignore(main)
        pass
    Moptions._postprocess_options(dbg, opts)

    # process_options has munged sys.argv to remove any options that
    # options that belong to this debugger. The original options to
    # invoke the debugger and script are in global sys_argv

    if len(sys_argv) == 0:
        # No program given to debug. Set to go into a command loop
        # anyway
        mainpyfile = None
    else:
        mainpyfile = sys_argv[0]  # Get script filename.
        if not osp.isfile(mainpyfile):
            mainpyfile=Mclifns.whence_file(mainpyfile)
            is_readable = Mfile.readable(mainpyfile)
            if is_readable is None:
                print("%s: Python script file '%s' does not exist"
                      % (__title__, mainpyfile,))
                sys.exit(1)
            elif not is_readable:
                print("%s: Can't read Python script file '%s'"
                      % (__title__, mainpyfile, ))
                sys.exit(1)
                return

        if Mfile.is_compiled_py(mainpyfile):
            try:
                from xdis import load_module, PYTHON_VERSION, IS_PYPY
                (python_version, timestamp, magic_int, co, is_pypy,
                 source_size) = load_module(mainpyfile, code_objects=None,
                                            fast_load=True)
                assert is_pypy == IS_PYPY
                assert python_version == PYTHON_VERSION, \
                    "bytecode is for version %s but we are version %s" % (
                        python_version, PYTHON_VERSION)
                # We should we check version magic_int

                py_file = co.co_filename
                if osp.isabs(py_file):
                    try_file = py_file
                else:
                    mainpydir = osp.dirname(mainpyfile)
                    tag = sys.implementation.cache_tag
                    dirnames = [osp.join(mainpydir, tag),
                                mainpydir] + os.environ['PATH'].split(osp.pathsep) + ['.']
                    try_file = Mclifns.whence_file(py_file, dirnames)

                if osp.isfile(try_file):
                    mainpyfile = try_file
                    pass
                else:
                    # Move onto the except branch
                    raise IOError("Python file name embedded in code %s not found" % try_file)
            except IOError:
                try:
                    from uncompyle6 import decompile_file
                except ImportError:
                    print("%s: Compiled python file '%s', but uncompyle6 not found"
                        % (__title__, mainpyfile), file=sys.stderr)
                    sys.exit(1)
                    return

                short_name = osp.basename(mainpyfile).strip('.pyc')
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix=short_name + "_",
                                                 delete=False)
                old_write = fd.file.write

                def write_wrapper(*args, **kwargs):
                    if isinstance(args[0], str):
                        new_args = list(args)
                        new_args[0] = args[0].encode('utf-8')
                        old_write(*new_args, **kwargs)
                    else:
                        old_write(*args, **kwargs)
                fd.file.write = write_wrapper

                # from io import StringIO
                # linemap_io = StringIO()
                try:
                   decompile_file(mainpyfile, fd.file, mapstream=fd)
                except:
                    print("%s: error decompiling '%s'"
                          % (__title__, mainpyfile), file=sys.stderr)
                    sys.exit(1)
                    return

                # # Get the line associations between the original and
                # # decompiled program
                # mapline = linemap_io.getvalue()
                # fd.write(mapline + "\n\n")
                # linemap = eval(mapline[3:])
                mainpyfile = fd.name
                fd.close()

                # Since we are actually running the recreated source,
                # there is little no need to remap line numbers.
                # The mapping is given at the end of the file.
                # However we should consider adding this information
                # and original file name.

                print("%s: couldn't find Python source so we recreated it at '%s'"
                      % (__title__, mainpyfile), file=sys.stderr)

                pass

        # If mainpyfile is an optimized Python script try to find and
        # use non-optimized alternative.
        mainpyfile_noopt = pyficache.pyc2py(mainpyfile)
        if mainpyfile != mainpyfile_noopt \
               and Mfile.readable(mainpyfile_noopt):
            print("%s: Compiled Python script given and we can't use that."
                  % __title__)
            print("%s: Substituting non-compiled name: %s" % (
                __title__, mainpyfile_noopt,))
            mainpyfile = mainpyfile_noopt
            pass

        # Replace trepan's dir with script's dir in front of
        # module search path.
        sys.path[0] = dbg.main_dirname = osp.dirname(mainpyfile)

    # XXX If a signal has been received we continue in the loop, otherwise
    # the loop exits for some reason.
    dbg.sig_received = False

    # if not mainpyfile:
    #     print('For now, you need to specify a Python script name!')
    #     sys.exit(2)
    #     pass

    while True:

        # Run the debugged script over and over again until we get it
        # right.

        try:
            if dbg.program_sys_argv and mainpyfile:
                normal_termination = dbg.run_script(mainpyfile)
                if not normal_termination: break
            else:
                dbg.core.execution_status = 'No program'
                dbg.core.processor.process_commands()
                pass

            dbg.core.execution_status = 'Terminated'
            dbg.intf[-1].msg("The program finished - quit or restart")
            dbg.core.processor.process_commands()
        except Mexcept.DebuggerQuit:
            break
        except Mexcept.DebuggerRestart:
            dbg.core.execution_status = 'Restart requested'
            if dbg.program_sys_argv:
                sys.argv = list(dbg.program_sys_argv)
                part1 = ('Restarting %s with arguments:' %
                         dbg.core.filename(mainpyfile))
                args  = ' '.join(dbg.program_sys_argv[1:])
                dbg.intf[-1].msg(
                    Mmisc.wrapped_lines(part1, args,
                                        dbg.settings['width']))
            else: break
        except SystemExit:
            # In most cases SystemExit does not warrant a post-mortem session.
            break
        pass

    # Restore old sys.argv
    sys.argv = orig_sys_argv
    return

Response: Main function for the main function of the debugger.


Instruction:
Implement a function in Python 3 to
use this to set where to write to. output can be a string or a TextIOWrapper object. This code raises IOError on error.

Response:
def open(self, output, opts=None):
        """Use this to set where to write to. output can be a
        file object or a string. This code raises IOError on error."""
        if isinstance(output, io.TextIOWrapper) or \
           isinstance(output, io.StringIO) or \
           output == sys.stdout:
            pass
        elif isinstance(output, 'string'.__class__):  # FIXME
            output = open(output, 'w')
        else:
            raise IOError("Invalid output type (%s) for %s" %
                          (output.__class__.__name__, output))
            # raise IOError("Invalid output type (%s) for %s" % (type(output),
            #                                                     output))
        self.output = output
        return


Instruction:
How would you code a function in Python 3 to
find the corresponding signal name for num. Return None if num is invalid. Return None if num is invalid.

Response:
def lookup_signame(num):
    """Find the corresponding signal name for 'num'. Return None
    if 'num' is invalid."""
    signames = signal.__dict__
    num = abs(num)
    for signame in list(signames.keys()):
        if signame.startswith('SIG') and signames[signame] == num:
            return signame
        pass
    # Something went wrong. Should have returned above
    return None


Instruction:
Write a Python 3 function that can
find the corresponding signal number for name. Return None if name is invalid.

Response:
def lookup_signum(name):
    """Find the corresponding signal number for 'name'. Return None
    if 'name' is invalid."""
    uname = name.upper()
    if (uname.startswith('SIG') and hasattr(signal, uname)):
        return getattr(signal, uname)
    else:
        uname = "SIG"+uname
        if hasattr(signal, uname):
            return getattr(signal, uname)
        return None
    return


Instruction:
Create a Python 3 function to
return a signal name for a signal name or signal number.

Response:
def canonic_signame(name_num):
    """Return a signal name for a signal name or signal
    number.  Return None is name_num is an int but not a valid signal
    number and False if name_num is a not number. If name_num is a
    signal name or signal number, the canonic if name is returned."""
    signum = lookup_signum(name_num)
    if signum is None:
        # Maybe signame is a number?
        try:
            num = int(name_num)
            signame = lookup_signame(num)
            if signame is None:
                return None
        except:
            return False
        return signame

    signame = name_num.upper()
    if not signame.startswith('SIG'): return 'SIG'+signame
    return signame


Instruction:
Given the following Python 3 function, write the documentation
def check_and_adjust_sighandler(self, signame, sigs):

        signum = lookup_signum(signame)

        try:
            old_handler = signal.getsignal(signum)
        except ValueError:
            # On some OS's (Redhat 8), SIGNUM's are listed (like
            # SIGRTMAX) that getsignal can't handle.
            if signame in self.sigs:
                sigs.pop(signame)
                pass
            return None
        if old_handler != self.sigs[signame].handle:
            if old_handler not in [signal.SIG_IGN, signal.SIG_DFL]:
                # save the program's signal handler
                sigs[signame].old_handler = old_handler
                pass
            # set/restore _our_ signal handler
            try:
                # signal.signal(signum, self.sigs[signame].handle)
                self._orig_set_signal(signum, self.sigs[signame].handle)
            except ValueError:
                # Probably not in main thread
                return False
            except KeyError:
                # May be weird keys from 3.3
                return False
            pass
        return True

Response: Check to see if a single signal handler that we are interested in has changed or has not been set initially.


Instruction:
Explain what the following Python 3 code does
def check_and_adjust_sighandlers(self):
        for signame in list(self.sigs.keys()):
            if not self.check_and_adjust_sighandler(signame, self.sigs):
                break
            pass
        return

Response:
Check to see if any of the signal handlers we are interested in have
        changed or is not initially set.


Instruction:
How would you code a function in Python 3 to
print status for a single signal name.

Response:
def print_info_signal_entry(self, signame):
        """Print status for a single signal name (signame)"""
        if signame in signal_description:
            description=signal_description[signame]
        else:
            description=""
            pass
        if signame not in list(self.sigs.keys()):
            # Fake up an entry as though signame were in sigs.
            self.dbgr.intf[-1].msg(self.info_fmt
                                   % (signame, 'No', 'No', 'No', 'Yes',
                                      description))
            return

        sig_obj = self.sigs[signame]
        self.dbgr.intf[-1].msg(self.info_fmt %
                               (signame,
                                YN(sig_obj.b_stop),
                                YN(sig_obj.print_method is not None),
                                YN(sig_obj.print_stack),
                                YN(sig_obj.pass_along),
                                description))
        return


Instruction:
How would you explain what the following Python 3 function does
def info_signal(self, args):
        if len(args) == 0: return None
        signame = args[0]
        if signame in ['handle', 'signal']:
            # This has come from dbgr's info command
            if len(args) == 1:
                # Show all signal handlers
                self.dbgr.core.processor.section(self.header)
                for signame in self.siglist:
                    self.print_info_signal_entry(signame)
                return True
            else:
                signame = args[1]
                pass
            pass

        signame = self.is_name_or_number(signame)
        self.dbgr.core.processor.section(self.header)
        self.print_info_signal_entry(signame)
        return True

Response: Print information about a signal


Instruction:
Can you write a function in Python 3 where it
delegates the actions specified in arg to another method.

Response:
def action(self, arg):
        """Delegate the actions specified in 'arg' to another
        method.
        """
        if not arg:
            self.info_signal(['handle'])
            return True
        args = arg.split()
        signame = args[0]
        signame = self.is_name_or_number(args[0])
        if not signame: return

        if len(args) == 1:
            self.info_signal([signame])
            return True
        # We can display information about 'fatal' signals, but not
        # change their actions.
        if signame in fatal_signals:
            return None

        if signame not in list(self.sigs.keys()):
            if not self.initialize_handler(signame): return None
            pass

        # multiple commands might be specified, i.e. 'nopass nostop'
        for attr in args[1:]:
            if attr.startswith('no'):
                on = False
                attr = attr[2:]
            else:
                on = True
            if 'stop'.startswith(attr):
                self.handle_stop(signame, on)
            elif 'print'.startswith(attr) and len(attr) >= 2:
                self.handle_print(signame, on)
            elif 'pass'.startswith(attr):
                self.handle_pass(signame, on)
            elif 'ignore'.startswith(attr):
                self.handle_ignore(signame, on)
            elif 'stack'.startswith(attr):
                self.handle_print_stack(signame, on)
            else:
                self.dbgr.intf[-1].errmsg('Invalid arguments')
                pass
            pass
        return self.check_and_adjust_sighandler(signame, self.sigs)


Instruction:
Make a summary of the following Python 3 code
def handle_print_stack(self, signame, print_stack):
        self.sigs[signame].print_stack = print_stack
        return print_stack

Response: Set whether we stop when this signal is caught.


Instruction:
Write a Python 3 function for
setting whether we stop when this signal is caught.

Response:
def handle_stop(self, signame, set_stop):
        """Set whether we stop or not when this signal is caught.
        If 'set_stop' is True your program will stop when this signal
        happens."""
        if set_stop:
            self.sigs[signame].b_stop       = True
            # stop keyword implies print AND nopass
            self.sigs[signame].print_method = self.dbgr.intf[-1].msg
            self.sigs[signame].pass_along   = False
        else:
            self.sigs[signame].b_stop       = False
            pass
        return set_stop


Instruction:
Can you tell what is the following Python 3 function doing
def handle_pass(self, signame, set_pass):
        self.sigs[signame].pass_along = set_pass
        if set_pass:
            # Pass implies nostop
            self.sigs[signame].b_stop = False
            pass
        return set_pass

Response: Set whether we should pass this signal to the program or not.


Instruction:
Can you implement a function in Python 3 that
sets whether we print or not when this signal is caught.

Response:
def handle_print(self, signame, set_print):
        """Set whether we print or not when this signal is caught."""
        if set_print:
            self.sigs[signame].print_method = self.dbgr.intf[-1].msg
        else:
            self.sigs[signame].print_method = None
            pass
        return set_print


Instruction:
How would you code a function in Python 3 to
check whether line is a line of a breakpoint.

Response:
def is_ok_line_for_breakpoint(filename, lineno, errmsg_fn):
    """Check whether specified line seems to be executable.

    Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank
    line or EOF). Warning: testing is not comprehensive.
    """
    line = linecache.getline(filename, lineno)
    if not line:
        errmsg_fn('End of file')
        return False
    line = line.strip()
    # Don't allow setting breakpoint at a blank line
    if (not line or (line[0] == '#') or
         (line[:3] == '"""') or line[:3] == "'''"):
        errmsg_fn('Blank or comment')
        return False
    return True


Instruction:
Can you generate the documentation for the following Python 3 function
def file2module(filename):
    basename = osp.basename(filename)
    if '.' in basename:
        pos = basename.rfind('.')
        return basename[:pos]
    else:
        return basename
    return None

Response: Given a filename extract the most likely module name.


Instruction:
Can you write a function in Python 3 where it
searches a file in a list of directories and return a full pathname for filename if we can find one.

Response:
def search_file(filename, directories, cdir):
    """Return a full pathname for filename if we can find one. path
    is a list of directories to prepend to filename. If no file is
    found we'll return None"""

    for trydir in directories:

        # Handle $cwd and $cdir
        if trydir =='$cwd': trydir='.'
        elif trydir == '$cdir': trydir = cdir

        tryfile = osp.realpath(osp.join(trydir, filename))
        if osp.isfile(tryfile):
            return tryfile
    return None


Instruction:
How would you code a function in Python 3 to
try to find a file in a directory and return the results.

Response:
def whence_file(py_script, dirnames=None):
    """Do a shell-like path lookup for py_script and return the results.
    If we can't find anything return py_script"""
    if py_script.find(os.sep) != -1:
        # Don't search since this name has path separator components
        return py_script
    if dirnames is None:
        dirnames = os.environ['PATH'].split(os.pathsep)
    for dirname in dirnames:
        py_script_try = osp.join(dirname, py_script)
        if osp.exists(py_script_try):
            return py_script_try
    # Failure
    return py_script


Instruction:
Make a summary of the following Python 3 code
def print_obj(arg, frame, format=None, short=False):
    try:
        if not frame:
            # ?? Should we have set up a dummy globals
            # to have persistence?
            obj = eval(arg, None, None)
        else:
            obj = eval(arg, frame.f_globals, frame.f_locals)
            pass
    except:
        return 'No symbol "' + arg + '" in current context.'
    # format and print
    what = arg
    if format:
        what = format + ' ' + arg
        obj = printf(obj, format)
    s = '%s = %s' % (what, obj)
    if not short:
        s += '\ntype = %s' % type(obj)
        if callable(obj):
            argspec = print_argspec(obj, arg)
            if argspec:
                s += ':\n\t'
                if inspect.isclass(obj):
                    s += 'Class constructor information:\n\t'
                    obj = obj.__init__
                elif isinstance(obj, types.InstanceType):
                    obj = obj.__call__
                    pass
                s+= argspec
            pass

        # Try to list the members of a class.
        # Not sure if this is correct or the
        # best way to do.
        s = print_dict(s, obj, "object variables")
        if hasattr(obj, "__class__"):
            s = print_dict(s, obj.__class__, "class variables")
            pass
    return s

Response: Return a string representation of an object.


Instruction:
Can you tell what is the following Python 3 function doing
def adjust_frame(self, pos, absolute_pos):
        if not self.curframe:
            Mmsg.errmsg(self, "No stack.")
            return

        # Below we remove any negativity. At the end, pos will be
        # the new value of self.curindex.
        if absolute_pos:
            if pos >= 0:
                pos = len(self.stack)-pos-1
            else:
                pos = -pos-1
        else:
            pos += self.curindex

        if pos < 0:
            Mmsg.errmsg(self,
                        "Adjusting would put us beyond the oldest frame.")
            return
        elif pos >= len(self.stack):
            Mmsg.errmsg(self,
                        "Adjusting would put us beyond the newest frame.")
            return

        self.curindex = pos
        self.curframe = self.stack[self.curindex][0]
        self.print_location()
        self.list_lineno = None
        return

Response: Adjust stack frame by pos positions.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def ok_for_running(self, cmd_obj, name, cmd_hash):
        '''We separate some of the common debugger command checks here:
        whether it makes sense to run the command in this execution state,
        if the command has the right number of arguments and so on.
        '''
        if hasattr(cmd_obj, 'execution_set'):
            if not (self.core.execution_status in cmd_obj.execution_set):
                part1 = ("Command '%s' is not available for execution "
                         "status:" % name)
                Mmsg.errmsg(self,
                            Mmisc.
                            wrapped_lines(part1,
                                            self.core.execution_status,
                                            self.debugger.settings['width']))
                return False
            pass
        if self.frame is None and cmd_obj.need_stack:
            self.intf[-1].errmsg("Command '%s' needs an execution stack."
                                 % name)
            return False
        return True

Response: Check if the command is available for execution.


Instruction:
Explain what the following Python 3 code does
def _populate_commands(self):
        cmd_instances = []
        from trepan.bwprocessor import command as Mcommand
        eval_cmd_template = 'command_mod.%s(self)'
        for mod_name in Mcommand.__modules__:
            import_name = "command." + mod_name
            try:
                command_mod = getattr(__import__(import_name), mod_name)
            except:
                print('Error importing %s: %s' % (mod_name, sys.exc_info()[0]))
                continue

            classnames = [ tup[0] for tup in
                           inspect.getmembers(command_mod, inspect.isclass)
                           if ('DebuggerCommand' != tup[0] and
                               tup[0].endswith('Command')) ]
            for classname in classnames:
                eval_cmd = eval_cmd_template % classname
                try:
                    instance = eval(eval_cmd)
                    cmd_instances.append(instance)
                except:
                    print('Error loading %s from %s: %s' %
                          (classname, mod_name, sys.exc_info()[0]))
                    pass
                pass
            pass
        return cmd_instances

Response:
Create a list of DebuggerCommand instances for each possible debugger
       .


Instruction:
Implement a function in Python 3 to
populate self. commands with the command list.

Response:
def _populate_cmd_lists(self):
        """ Populate self.commands"""
        self.commands = {}
        for cmd_instance in self.cmd_instances:
            cmd_name = cmd_instance.name
            self.commands[cmd_name] = cmd_instance
            pass
        return


Instruction:
Create a Python 3 function for
formatting the location of the currently selected item in the cache.

Response:
def format_location(proc_obj):
    """Show where we are. GUI's and front-end interfaces often
    use this to update displays. So it is helpful to make sure
    we give at least some place that's located in a file.
    """
    i_stack = proc_obj.curindex
    if i_stack is None or proc_obj.stack is None:
        return False
    location = {}
    core_obj = proc_obj.core
    dbgr_obj = proc_obj.debugger

    # Evaluation routines like "exec" don't show useful location
    # info. In these cases, we will use the position before that in
    # the stack.  Hence the looping below which in practices loops
    # once and sometimes twice.
    while i_stack >= 0:
        frame_lineno = proc_obj.stack[i_stack]
        i_stack -= 1
        frame, lineno = frame_lineno

        filename = Mstack.frame2file(core_obj, frame)

        location['filename'] = filename
        location['fn_name']  = frame.f_code.co_name
        location['lineno']   = lineno

        if '<string>' == filename and dbgr_obj.eval_string:
            filename = pyficache.unmap_file(filename)
            if '<string>' == filename:
                fd = tempfile.NamedTemporaryFile(suffix='.py',
                                                 prefix='eval_string',
                                                 delete=False)
                fd.write(bytes(dbgr_obj.eval_string, 'UTF-8'))
                fd.close()
                pyficache.remap_file(fd.name, '<string>')
                filename = fd.name
                pass
            pass

        opts = {
            'reload_on_change' : proc_obj.settings('reload'),
            'output'           : 'plain'
            }
        line = pyficache.getline(filename, lineno, opts)
        if not line:
            line = linecache.getline(filename, lineno,
                                     proc_obj.curframe.f_globals)
            pass

        if line and len(line.strip()) != 0:
            location['text'] = line
            pass
        if '<string>' != filename: break
        pass

    return location


Instruction:
Write a Python 3 script for
using to write to a debugger that is connected to this server ; str written will have a newline added to it

Response:
def msg(self, msg):
        """ used to write to a debugger that is connected to this
        server; `str' written will have a newline added to it
        """
        if hasattr(self.output, 'writeline'):
            self.output.writeline(msg)
        elif hasattr(self.output, 'writelines'):
            self.output.writelines(msg + "\n")
            pass
        return


Instruction:
Given the following Python 3 function, write the documentation
def run(self, args):
        mainfile = self.core.filename(None)
        if self.core.is_running():
            if mainfile:
                part1 = "Python program '%s' is stopped" % mainfile
            else:
                part1 = 'Program is stopped'
                pass
            if self.proc.event:
                msg = 'via a %s event.' % self.proc.event
            else:
                msg = '.'
            self.msg(Mmisc.wrapped_lines(part1, msg,
                                         self.settings['width']))
            if self.proc.curframe:
                self.msg("PC offset is %d." % self.proc.curframe.f_lasti)

            if self.proc.event == 'return':
                val = self.proc.event_arg
                part1 = 'Return value is'
                self.msg(Mmisc.wrapped_lines(part1, self.proc._saferepr(val),
                                             self.settings['width']))
                pass
            elif self.proc.event == 'exception':
                exc_type, exc_value, exc_tb = self.proc.event_arg
                self.msg('Exception type: %s' %
                         self.proc._saferepr(exc_type))
                if exc_value:
                    self.msg('Exception value: %s' %
                             self.proc._saferepr(exc_value))
                    pass
                pass
            self.msg('It stopped %s.' % self.core.stop_reason)
            if self.proc.event in ['signal', 'exception', 'c_exception']:
                self.msg('Note: we are stopped *after* running the '
                         'line shown.')
                pass
        else:
            if mainfile:
                part1 = "Python program '%s'" % mainfile
                msg   = "is not currently running. "
                self.msg(Mmisc.wrapped_lines(part1, msg,
                                             self.settings['width']))
            else:
                self.msg('No Python program is currently running.')
                pass
            self.msg(self.core.execution_status)
            pass
        return False

Response: This method is called by the main thread when the program is started.


Instruction:
Can you generate the documentation for the following Python 3 function
def columnize_commands(self, commands):
        commands.sort()
        width = self.debugger.settings['width']
        return columnize.columnize(commands, displaywidth=width,
                                   lineprefix='    ')

Response: Return a list of aligned columns


Instruction:
Given the following Python 3 function, write the documentation
def errmsg(self, msg, opts={}):
        try:
            return(self.debugger.intf[-1].errmsg(msg))
        except EOFError:
            # FIXME: what do we do here?
            pass
        return None

Response: Convenience method for debugging.


Instruction:
Make a summary of the following Python 3 code
def msg(self, msg, opts={}):
        try:
            return(self.debugger.intf[-1].msg(msg))
        except EOFError:
            # FIXME: what do we do here?
            pass
        return None

Response: Convenience method to return the message from the debugger.


Instruction:
Create a Python 3 function for
returning the message ID if it was sent to the nova.

Response:
def msg_nocr(self, msg, opts={}):
        """ Convenience short-hand for self.debugger.intf[-1].msg_nocr """
        try:
            return(self.debugger.intf[-1].msg_nocr(msg))
        except EOFError:
            # FIXME: what do we do here?
            pass
        return None


Instruction:
Write a Python 3 function for
converting ReStructuredText and run through msg

Response:
def rst_msg(self, text, opts={}):
        """Convert ReStructuredText and run through msg()"""
        text = Mformat.rst_text(text,
                                'plain' == self.debugger.settings['highlight'],
                                self.debugger.settings['width'])
        return self.msg(text)


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

    try:
        if inspect.istraceback(sys.last_traceback):
            # We do have a traceback so prefer that.
            return sys.last_type, sys.last_value, sys.last_traceback
    except AttributeError:
        pass
    return sys.exc_info()

Response: Intended to be used in post mortem routines.


Instruction:
Explain what the following Python 3 code does
def post_mortem(exc=None, frameno=1, dbg=None):

    if dbg is None:
        # Check for a global debugger object
        if Mdebugger.debugger_obj is None:
            Mdebugger.debugger_obj = Mdebugger.Trepan()
            pass
        dbg = Mdebugger.debugger_obj
        pass
    re_bogus_file = re.compile("^<.+>$")

    if exc[0] is None:
        # frameno+1 because we are about to add one more level of call
        # in get_last_or_frame_exception
        exc = get_last_or_frame_exception()
        if exc[0] is None:
            print("Can't find traceback for post_mortem "
                  "in sys.last_traceback or sys.exec_info()")
            return
        pass
    exc_type, exc_value, exc_tb = exc
    dbg.core.execution_status = ('Terminated with unhandled exception %s'
                                 % exc_type)

    # tb has least-recent traceback entry first. We want the most-recent
    # entry. Also we'll pick out a mainpyfile name if it hasn't previously
    # been set.
    if exc_tb is not None:
        while exc_tb.tb_next is not None:
            filename = exc_tb.tb_frame.f_code.co_filename
            if (dbg.mainpyfile and 0 == len(dbg.mainpyfile)
                and not re_bogus_file.match(filename)):
                dbg.mainpyfile = filename
                pass
            exc_tb = exc_tb.tb_next
            pass
        dbg.core.processor.curframe = exc_tb.tb_frame
        pass

    if 0 == len(dbg.program_sys_argv):
        # Fake program (run command) args since we weren't called with any
        dbg.program_sys_argv = list(sys.argv[1:])
        dbg.program_sys_argv[:0] = [dbg.mainpyfile]

    # if 0 == len(dbg._sys_argv):
    #     # Fake script invocation (restart) args since we don't have any
    #     dbg._sys_argv = list(dbg.program_sys_argv)
    #     dbg._sys_argv[:0] = [__title__]

    try:
        # # FIXME: This can be called from except hook in which case we
        # # need this. Dunno why though.
        # try:
        #     _pydb_trace.set_trace(t.tb_frame)
        # except:
        #     pass

        # Possibly a bug in Python 2.5. Why f.f_lineno is
        # not always equal to t.tb_lineno, I don't know.
        f = exc_tb.tb_frame
        if f and f.f_lineno != exc_tb.tb_lineno : f = f.f_back
        dbg.core.processor.event_processor(f, 'exception', exc, 'Trepan3k:pm')
    except DebuggerRestart:
        while True:
            sys.argv = list(dbg._program_sys_argv)
            dbg.msg("Restarting %s with arguments:\n\t%s"
                  % (dbg.filename(dbg.mainpyfile),
                     " ".join(dbg._program_sys_argv[1:])))
            try:
                dbg.run_script(dbg.mainpyfile)
            except DebuggerRestart:
                pass
            pass
    except DebuggerQuit:
        pass
    return

Response: Enter the debugger read loop after a program has crashed.


Instruction:
Make a summary of the following Python 3 code
def close(self):
        self.state = 'closing'
        if self.inout:
            self.inout.close()
            pass
        self.state = 'closing connection'
        if self.conn:
            self.conn.close()
        self.state = 'disconnected'
        return

Response: Closes both socket and server connection.


Instruction:
Can you generate the documentation for the following Python 3 function
def complete_token_filtered(aliases, prefix, expanded):

    """Find all starting matches in dictionary *aliases* that start
    with *prefix*, but filter out any matches already in
    *expanded*."""

    complete_ary = list(aliases.keys())
    results = [cmd for cmd in
               complete_ary if cmd.startswith(prefix)] and not (
                   cmd in aliases and expanded not in aliases[cmd])
    return sorted(results, key=lambda pair: pair[0])

Response:
Find all starting matches in dictionary aliases that start with prefix but filter out any matches already in
    expanded.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def complete_identifier(cmd, prefix):
    '''Complete an arbitrary expression.'''
    if not cmd.proc.curframe: return [None]
    # Collect globals and locals.  It is usually not really sensible to also
    # complete builtins, and they clutter the namespace quite heavily, so we
    # leave them out.
    ns = cmd.proc.curframe.f_globals.copy()
    ns.update(cmd.proc.curframe.f_locals)
    if '.' in prefix:
        # Walk an attribute chain up to the last part, similar to what
        # rlcompleter does.  This will bail if any of the parts are not
        # simple attribute access, which is what we want.
        dotted = prefix.split('.')
        try:
            obj = ns[dotted[0]]
            for part in dotted[1:-1]:
                obj = getattr(obj, part)
        except (KeyError, AttributeError):
            return []
        pre_prefix = '.'.join(dotted[:-1]) + '.'
        return [pre_prefix + n for n in dir(obj) if
                n.startswith(dotted[-1])]
    else:
        # Complete a simple name.
        return Mcomplete.complete_token(ns.keys(), prefix)

Response: Complete an arbitrary expression.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def errmsg(self, message, opts={}):
        if 'plain' != self.debugger.settings['highlight']:
            message = colorize('standout', message)
            pass
        return(self.intf[-1].errmsg(message))

Response: Convenience short - hand for self. intf. errmsg


Instruction:
Here you have a function in Python 3, explain what it does
def rst_msg(self, text, opts={}):
        from trepan.lib.format import rst_text
        text = rst_text(text,
                        'plain' == self.debugger.settings['highlight'],
                        self.debugger.settings['width'])
        return self.msg(text)

Response: Convert ReStructuredText and run through msg


Instruction:
Make a summary of the following Python 3 code
def dbgr(self, string):
        '''Invoke a debugger command from inside a python shell called inside
        the debugger.
        '''
        print('')
        self.proc.cmd_queue.append(string)
        self.proc.process_command()
        return

Response:
Invoke a debugger command from inside a python shell called inside
        the debugger.


Instruction:
Can you create a Python 3 function that
quits command when there s just one thread.

Response:
def nothread_quit(self, arg):
        """ quit command when there's just one thread. """

        self.debugger.core.stop()
        self.debugger.core.execution_status = 'Quit command'
        self.proc.response['event'] = 'terminated'
        self.proc.response['name']  = 'status'
        self.proc.intf[-1].msg(self.proc.response)
        raise Mexcept.DebuggerQuit


Instruction:
Given the following Python 3 function, write the documentation
def parse_addr_list_cmd(proc, args, listsize=40):

    text = proc.current_command[len(args[0])+1:].strip()

    if text in frozenset(('', '.', '+', '-')):
        if text == '.':
            location = resolve_address_location(proc, '.')
            return (location.path, location.line_number, True,
                    location.line_number + listsize, True,
                    location.method)

        if proc.list_offset is None:
            proc.errmsg("Don't have previous list location")
            return INVALID_PARSE_LIST

        filename = proc.list_filename
        if text == '+':
            first = max(0, proc.list_offset-1)
        elif text == '-':
            # FIXME: not quite right for offsets
            if proc.list_lineno == 1 + listsize:
                proc.errmsg("Already at start of %s." % proc.list_filename)
                return INVALID_PARSE_LIST
            first = max(1, proc.list_lineno - (2*listsize) - 1)
        elif text == '':
            # Continue from where we last left off
            first = proc.list_offset + 1
            last = first + listsize - 1
            return filename, first, True, last, True, proc.list_object
        last = first + listsize - 1
        return filename, first, True, last, True, proc.list_object
    else:
        try:
            list_range = build_arange(text)
        except LocationError as e:
            proc.errmsg("Error in parsing list range at or around:")
            proc.errmsg(e.text)
            proc.errmsg(e.text_cursor)
            return INVALID_PARSE_LIST
        except ScannerError as e:
            proc.errmsg("Lexical error in parsing list range at or around:")
            proc.errmsg(e.text)
            proc.errmsg(e.text_cursor)
            return INVALID_PARSE_LIST

        if list_range.first is None:
            # Last must have been given
            assert isinstance(list_range.last, Location)
            location = resolve_address_location(proc, list_range.last)
            if not location:
                return INVALID_PARSE_LIST
            last     = location.line_number
            if location.is_address:
                raise RuntimeError("We don't handle ending offsets")
            else:
                first    = max(1, last - listsize)
            return location.path, first, False, last, False, location.method
        elif isinstance(list_range.first, int):
            first    = list_range.first
            location = resolve_address_location(proc, list_range.last)
            if not location:
                return INVALID_PARSE_LIST
            filename = location.path
            last     = location.line_number

            if not location.is_address and last < first:
                # Treat as a count rather than an absolute location
                last = first + last
            return location.path, first, False, last, location.is_address, location.method
        else:
            # First is location. Last may be empty or a number/address
            assert isinstance(list_range.first, Location)
            location = resolve_address_location(proc, list_range.first)
            if not location:
                return INVALID_PARSE_LIST
            first    = location.line_number
            first_is_addr = location.is_address
            last_is_addr  = False
            last     = list_range.last
            if isinstance(last, str):
                # Is an offset +number
                assert last[0] in ('+', '*')
                last_is_addr = last[0] == '*'
                if last_is_addr:
                    last = int(last[1:])
                else:
                    last = first + int(last[1:])
            elif not last:
                last_is_addr = True
                last = first + listsize
            elif last < first:
                # Treat as a count rather than an absolute location
                last = first + last

            return location.path, first, first_is_addr, last, last_is_addr, location.method
        pass
    return

Response: Parses the arguments for the list command and returns the tuple that is returned.


Instruction:
Can you tell what is the following Python 3 function doing
def add_ignore(self, *frames_or_fns):
        for frame_or_fn in frames_or_fns:
            rc = self.ignore_filter.add_include(frame_or_fn)
            pass
        return rc

Response:
Add frame_or_fn to the list of functions that are not to
            be debugged