Instruction:
Can you create a Python 3 function that
checks if a directory is eligible for test discovery

Response:
def wantDirectory(self, dirname):
        """Check if directory is eligible for test discovery"""
        if dirname in self.exclude_dirs:
            log.debug("excluded: %s" % dirname)
            return False
        else:
            return None


Instruction:
Write a Python 3 function that can
return true if ext links to a dynamic lib in the same package

Response:
def links_to_dynamic(self, ext):
        """Return true if 'ext' links to a dynamic lib in the same package"""
        # XXX this should check to ensure the lib is actually being built
        # XXX as dynamic, and not just using a locally-found version or a
        # XXX static-compiled version
        libnames = dict.fromkeys([lib._full_name for lib in self.shlibs])
        pkg = '.'.join(ext._full_name.split('.')[:-1]+[''])
        for libname in ext.libraries:
            if pkg+libname in libnames: return True
        return False


Instruction:
Given the following Python 3 function, write the documentation
def call_each(funcs: list, *args, **kwargs):
    '''
    call each func from func list.

    return the last func value or None if func list is empty.
    '''
    ret = None
    for func in funcs:
        ret = func(*args, **kwargs)
    return ret

Response:
call each func from func list.
    return the last func value or None


Instruction:
Write a Python 3 function for
calling each func from reversed func list. return the last value or None

Response:
def call_each_reversed(funcs: list, *args, **kwargs):
    '''
    call each func from reversed func list.

    return the last func value or None if func list is empty.
    '''
    ret = None
    for func in reversed(funcs):
        ret = func(*args, **kwargs)
    return ret


Instruction:
Make a summary of the following Python 3 code
def append_func(self, func, *args, **kwargs):
        '''
        append func with given arguments and keywords.
        '''
        wraped_func = partial(func, *args, **kwargs)
        self.append(wraped_func)

Response:
append func with given arguments and keywords.
        append func with given arguments and keywords.


Instruction:
Can you implement a function in Python 3 that
formats the usage message

Response:
def format_usage(self, usage):
        """
        ensure there is only one newline between usage and the first heading
        if there is no description
        """
        msg = 'Usage: %s' % usage
        if self.parser.description:
            msg += '\n'
        return msg


Instruction:
Can you tell what is the following Python 3 function doing
def write_pid_file(self, overwrite=False):
        pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
        if os.path.isfile(pid_file):
            pid = self.get_pid_from_file()
            if not overwrite:
                raise PIDFileError(
                    'The pid file [%s] already exists. \nThis could mean that this '
                    'server is already running with [pid=%s].' % (pid_file, pid)
                )
        with open(pid_file, 'w') as f:
            self.log.info("Creating pid file: %s" % pid_file)
            f.write(repr(os.getpid())+'\n')

Response: Create a. pid file in the pid_dir with my pid.


Instruction:
Can you implement a function in Python 3 that
removes the pid file.

Response:
def remove_pid_file(self):
        """Remove the pid file.

        This should be called at shutdown by registering a callback with
        :func:`reactor.addSystemEventTrigger`. This needs to return
        ``None``.
        """
        pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
        if os.path.isfile(pid_file):
            try:
                self.log.info("Removing pid file: %s" % pid_file)
                os.remove(pid_file)
            except:
                self.log.warn("Error removing the pid file: %s" % pid_file)


Instruction:
Here you have a function in Python 3, explain what it does
def get_pid_from_file(self):
        pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid')
        if os.path.isfile(pid_file):
            with open(pid_file, 'r') as f:
                s = f.read().strip()
                try:
                    pid = int(s)
                except:
                    raise PIDFileError("invalid pid file: %s (contents: %r)"%(pid_file, s))
                return pid
        else:
            raise PIDFileError('pid file not found: %s' % pid_file)

Response: Get the pid from the pid file.


Instruction:
How would you code a function in Python 3 to
construct an argument parser using the function decorations.

Response:
def construct_parser(magic_func):
    """ Construct an argument parser using the function decorations.
    """
    kwds = getattr(magic_func, 'argcmd_kwds', {})
    if 'description' not in kwds:
        kwds['description'] = getattr(magic_func, '__doc__', None)
    arg_name = real_name(magic_func)
    parser = MagicArgumentParser(arg_name, **kwds)
    # Reverse the list of decorators in order to apply them in the
    # order in which they appear in the source.
    group = None
    for deco in magic_func.decorators[::-1]:
        result = deco.add_to_parser(parser, group)
        if result is not None:
            group = result

    # Replace the starting 'usage: ' with IPython's %.
    help_text = parser.format_help()
    if help_text.startswith('usage: '):
        help_text = help_text.replace('usage: ', '%', 1)
    else:
        help_text = '%' + help_text

    # Replace the magic function's docstring with the full help text.
    magic_func.__doc__ = help_text

    return parser


Instruction:
Implement a function in Python 3 to
find the real name of the magic.

Response:
def real_name(magic_func):
    """ Find the real name of the magic.
    """
    magic_name = magic_func.__name__
    if magic_name.startswith('magic_'):
        magic_name = magic_name[len('magic_'):]
    return getattr(magic_func, 'argcmd_name', magic_name)


Instruction:
Given the following Python 3 function, write the documentation
def add_to_parser(self, parser, group):
        if group is not None:
            parser = group
        parser.add_argument(*self.args, **self.kwds)
        return None

Response: Add this object s information to the parser.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def add_to_parser(self, parser, group):
        return parser.add_argument_group(*self.args, **self.kwds)

Response: Add this object s information to the parser.


Instruction:
Can you write a function in Python 3 where it
highlights a block of text. Reimplemented to highlight selectively.

Response:
def highlightBlock(self, string):
        """ Highlight a block of text. Reimplemented to highlight selectively.
        """
        if not self.highlighting_on:
            return

        # The input to this function is a unicode string that may contain
        # paragraph break characters, non-breaking spaces, etc. Here we acquire
        # the string as plain text so we can compare it.
        current_block = self.currentBlock()
        string = self._frontend._get_block_plain_text(current_block)

        # Decide whether to check for the regular or continuation prompt.
        if current_block.contains(self._frontend._prompt_pos):
            prompt = self._frontend._prompt
        else:
            prompt = self._frontend._continuation_prompt

        # Only highlight if we can identify a prompt, but make sure not to
        # highlight the prompt.
        if string.startswith(prompt):
            self._current_offset = len(prompt)
            string = string[len(prompt):]
            super(FrontendHighlighter, self).highlightBlock(string)


Instruction:
Explain what the following Python 3 code does
def rehighlightBlock(self, block):
        old = self.highlighting_on
        self.highlighting_on = True
        super(FrontendHighlighter, self).rehighlightBlock(block)
        self.highlighting_on = old

Response: Reimplemented to temporarily enable highlighting if disabled.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def setFormat(self, start, count, format):
        start += self._current_offset
        super(FrontendHighlighter, self).setFormat(start, count, format)

Response: Set the format of the current node.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def copy(self):
        if self._page_control is not None and self._page_control.hasFocus():
            self._page_control.copy()
        elif self._control.hasFocus():
            text = self._control.textCursor().selection().toPlainText()
            if text:
                lines = map(self._transform_prompt, text.splitlines())
                text = '\n'.join(lines)
                QtGui.QApplication.clipboard().setText(text)
        else:
            self.log.debug("frontend widget : unknown copy target")

Response: Copies the currently selected text to the clipboard removing prompts.


Instruction:
Here you have a function in Python 3, explain what it does
def _is_complete(self, source, interactive):
        complete = self._input_splitter.push(source)
        if interactive:
            complete = not self._input_splitter.push_accepts_more()
        return complete

Response:
Returns whether the source can be completely processed and a new
            prompt created.


Instruction:
Create a Python 3 function for
executing the source message.

Response:
def _execute(self, source, hidden):
        """ Execute 'source'. If 'hidden', do not show any output.

        See parent class :meth:`execute` docstring for full details.
        """
        msg_id = self.kernel_manager.shell_channel.execute(source, hidden)
        self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user')
        self._hidden = hidden
        if not hidden:
            self.executing.emit(source)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _prompt_finished_hook(self):
        # Flush all state from the input splitter so the next round of
        # reading input starts with a clean buffer.
        self._input_splitter.reset()

        if not self._reading:
            self._highlighter.highlighting_on = False

Response: Called immediately after a prompt is finished.


Instruction:
Make a summary of the following Python 3 code
def _tab_pressed(self):
        # Perform tab completion if:
        # 1) The cursor is in the input buffer.
        # 2) There is a non-whitespace character before the cursor.
        text = self._get_input_buffer_cursor_line()
        if text is None:
            return False
        complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
        if complete:
            self._complete()
        return not complete

Response:
Called when the tab key is pressed. Returns whether to continue
            processing the event.


Instruction:
Can you tell what is the following Python 3 function doing
def _event_filter_console_keypress(self, event):
        key = event.key()
        if self._control_key_down(event.modifiers(), include_command=False):

            if key == QtCore.Qt.Key_C and self._executing:
                self.request_interrupt_kernel()
                return True

            elif key == QtCore.Qt.Key_Period:
                self.request_restart_kernel()
                return True

        elif not event.modifiers() & QtCore.Qt.AltModifier:

            # Smart backspace: remove four characters in one backspace if:
            # 1) everything left of the cursor is whitespace
            # 2) the four characters immediately left of the cursor are spaces
            if key == QtCore.Qt.Key_Backspace:
                col = self._get_input_buffer_cursor_column()
                cursor = self._control.textCursor()
                if col > 3 and not cursor.hasSelection():
                    text = self._get_input_buffer_cursor_line()[:col]
                    if text.endswith('    ') and not text.strip():
                        cursor.movePosition(QtGui.QTextCursor.Left,
                                            QtGui.QTextCursor.KeepAnchor, 4)
                        cursor.removeSelectedText()
                        return True

        return super(FrontendWidget, self)._event_filter_console_keypress(event)

Response: Reimplemented for execution interruption and smart backspace.


Instruction:
Implement a Python 3 function for
handling replies for tab completion.

Response:
def _handle_complete_reply(self, rep):
        """ Handle replies for tab completion.
        """
        self.log.debug("complete: %s", rep.get('content', ''))
        cursor = self._get_cursor()
        info = self._request_info.get('complete')
        if info and info.id == rep['parent_header']['msg_id'] and \
                info.pos == cursor.position():
            text = '.'.join(self._get_context())
            cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))
            self._complete_with_items(cursor, rep['content']['matches'])


Instruction:
Make a summary of the following Python 3 code
def _silent_exec_callback(self, expr, callback):

        # generate uuid, which would be used as an indication of whether or
        # not the unique request originated from here (can use msg id ?)
        local_uuid = str(uuid.uuid1())
        msg_id = self.kernel_manager.shell_channel.execute('',
            silent=True, user_expressions={ local_uuid:expr })
        self._callback_dict[local_uuid] = callback
        self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')

Response: Silently execute expr in the kernel and call callback with reply


Instruction:
Create a Python 3 function for
executing callback corresponding to msg

Response:
def _handle_exec_callback(self, msg):
        """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``

        Parameters
        ----------
        msg : raw message send by the kernel containing an `user_expressions`
                and having a 'silent_exec_callback' kind.

        Notes
        -----
        This function will look for a `callback` associated with the
        corresponding message id. Association has been made by
        `_silent_exec_callback`. `callback` is then called with the `repr()`
        of the value of corresponding `user_expressions` as argument.
        `callback` is then removed from the known list so that any message
        coming again with the same id won't trigger it.

        """

        user_exp = msg['content'].get('user_expressions')
        if not user_exp:
            return
        for expression in user_exp:
            if expression in self._callback_dict:
                self._callback_dict.pop(expression)(user_exp[expression])


Instruction:
Create a Python 3 function for
handling the reply from the execute command.

Response:
def _handle_execute_reply(self, msg):
        """ Handles replies for code execution.
        """
        self.log.debug("execute: %s", msg.get('content', ''))
        msg_id = msg['parent_header']['msg_id']
        info = self._request_info['execute'].get(msg_id)
        # unset reading flag, because if execute finished, raw_input can't
        # still be pending.
        self._reading = False
        if info and info.kind == 'user' and not self._hidden:
            # Make sure that all output from the SUB channel has been processed
            # before writing a new prompt.
            self.kernel_manager.sub_channel.flush()

            # Reset the ANSI style information to prevent bad text in stdout
            # from messing up our colors. We're not a true terminal so we're
            # allowed to do this.
            if self.ansi_codes:
                self._ansi_processor.reset_sgr()

            content = msg['content']
            status = content['status']
            if status == 'ok':
                self._process_execute_ok(msg)
            elif status == 'error':
                self._process_execute_error(msg)
            elif status == 'aborted':
                self._process_execute_abort(msg)

            self._show_interpreter_prompt_for_reply(msg)
            self.executed.emit(msg)
            self._request_info['execute'].pop(msg_id)
        elif info and info.kind == 'silent_exec_callback' and not self._hidden:
            self._handle_exec_callback(msg)
            self._request_info['execute'].pop(msg_id)
        else:
            super(FrontendWidget, self)._handle_execute_reply(msg)


Instruction:
Can you tell what is the following Python 3 function doing
def _handle_input_request(self, msg):
        self.log.debug("input: %s", msg.get('content', ''))
        if self._hidden:
            raise RuntimeError('Request for raw input during hidden execution.')

        # Make sure that all output from the SUB channel has been processed
        # before entering readline mode.
        self.kernel_manager.sub_channel.flush()

        def callback(line):
            self.kernel_manager.stdin_channel.input(line)
        if self._reading:
            self.log.debug("Got second input request, assuming first was interrupted.")
            self._reading = False
        self._readline(msg['content']['prompt'], callback=callback)

Response: Handle incoming raw_input request.


Instruction:
Implement a function in Python 3 to
handle the kernel s death by asking if the user wants to restart the kernel.

Response:
def _handle_kernel_died(self, since_last_heartbeat):
        """ Handle the kernel's death by asking if the user wants to restart.
        """
        self.log.debug("kernel died: %s", since_last_heartbeat)
        if self.custom_restart:
            self.custom_restart_kernel_died.emit(since_last_heartbeat)
        else:
            message = 'The kernel heartbeat has been inactive for %.2f ' \
                'seconds. Do you want to restart the kernel? You may ' \
                'first want to check the network connection.' % \
                since_last_heartbeat
            self.restart_kernel(message, now=True)


Instruction:
Write a Python 3 script for
handling the reply for object info.

Response:
def _handle_object_info_reply(self, rep):
        """ Handle replies for call tips.
        """
        self.log.debug("oinfo: %s", rep.get('content', ''))
        cursor = self._get_cursor()
        info = self._request_info.get('call_tip')
        if info and info.id == rep['parent_header']['msg_id'] and \
                info.pos == cursor.position():
            # Get the information for a call tip.  For now we format the call
            # line as string, later we can pass False to format_call and
            # syntax-highlight it ourselves for nicer formatting in the
            # calltip.
            content = rep['content']
            # if this is from pykernel, 'docstring' will be the only key
            if content.get('ismagic', False):
                # Don't generate a call-tip for magics. Ideally, we should
                # generate a tooltip, but not on ( like we do for actual
                # callables.
                call_info, doc = None, None
            else:
                call_info, doc = call_tip(content, format_call=True)
            if call_info or doc:
                self._call_tip_widget.show_call_info(call_info, doc)


Instruction:
Write a Python 3 function for
handling display hook output.

Response:
def _handle_pyout(self, msg):
        """ Handle display hook output.
        """
        self.log.debug("pyout: %s", msg.get('content', ''))
        if not self._hidden and self._is_from_this_session(msg):
            text = msg['content']['data']
            self._append_plain_text(text + '\n', before_prompt=True)


Instruction:
Can you tell what is the following Python 3 function doing
def _handle_stream(self, msg):
        self.log.debug("stream: %s", msg.get('content', ''))
        if not self._hidden and self._is_from_this_session(msg):
            # Most consoles treat tabs as being 8 space characters. Convert tabs
            # to spaces so that output looks as expected regardless of this
            # widget's tab width.
            text = msg['content']['data'].expandtabs(8)

            self._append_plain_text(text, before_prompt=True)
            self._control.moveCursor(QtGui.QTextCursor.End)

Response: Handle the stream message.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def _handle_shutdown_reply(self, msg):
        self.log.debug("shutdown: %s", msg.get('content', ''))
        if not self._hidden and not self._is_from_this_session(msg):
            if self._local_kernel:
                if not msg['content']['restart']:
                    self.exit_requested.emit(self)
                else:
                    # we just got notified of a restart!
                    time.sleep(0.25) # wait 1/4 sec to reset
                                     # lest the request for a new prompt
                                     # goes to the old kernel
                    self.reset()
            else: # remote kernel, prompt on Kernel shutdown/reset
                title = self.window().windowTitle()
                if not msg['content']['restart']:
                    reply = QtGui.QMessageBox.question(self, title,
                        "Kernel has been shutdown permanently. "
                        "Close the Console?",
                        QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        self.exit_requested.emit(self)
                else:
                    # XXX: remove message box in favor of using the
                    # clear_on_kernel_restart setting?
                    reply = QtGui.QMessageBox.question(self, title,
                        "Kernel has been reset. Clear the Console?",
                        QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
                    if reply == QtGui.QMessageBox.Yes:
                        time.sleep(0.25) # wait 1/4 sec to reset
                                         # lest the request for a new prompt
                                         # goes to the old kernel
                        self.reset()

Response: Handle a shutdown signal from the kernel and the kernel itself.


Instruction:
Given the following Python 3 function, write the documentation
def execute_file(self, path, hidden=False):
        self.execute('execfile(%r)' % path, hidden=hidden)

Response: Attempts to execute a file with path.


Instruction:
Write a Python 3 function for
attempting to interrupt the running kernel.

Response:
def interrupt_kernel(self):
        """ Attempts to interrupt the running kernel.

        Also unsets _reading flag, to avoid runtime errors
        if raw_input is called again.
        """
        if self.custom_interrupt:
            self._reading = False
            self.custom_interrupt_requested.emit()
        elif self.kernel_manager.has_kernel:
            self._reading = False
            self.kernel_manager.interrupt_kernel()
        else:
            self._append_plain_text('Kernel process is either remote or '
                                    'unspecified. Cannot interrupt.\n')


Instruction:
Here you have a function in Python 3, explain what it does
def reset(self, clear=False):
        if self._executing:
            self._executing = False
            self._request_info['execute'] = {}
        self._reading = False
        self._highlighter.highlighting_on = False

        if self.clear_on_kernel_restart or clear:
            self._control.clear()
            self._append_plain_text(self.banner)
        else:
            self._append_plain_text("# restarting kernel...")
            self._append_html("

")
            # XXX: Reprinting the full banner may be too much, but once #1680 is
            # addressed, that will mitigate it.
            #self._append_plain_text(self.banner)
        # update output marker for stdout/stderr, so that startup
        # messages appear after banner:
        self._append_before_prompt_pos = self._get_cursor().position()
        self._show_interpreter_prompt()

Response: Resets the widget to its initial state.


Instruction:
Implement a Python 3 function for
attempting to restart the running kernel.

Response:
def restart_kernel(self, message, now=False):
        """ Attempts to restart the running kernel.
        """
        # FIXME: now should be configurable via a checkbox in the dialog.  Right
        # now at least the heartbeat path sets it to True and the manual restart
        # to False.  But those should just be the pre-selected states of a
        # checkbox that the user could override if so desired.  But I don't know
        # enough Qt to go implementing the checkbox now.

        if self.custom_restart:
            self.custom_restart_requested.emit()

        elif self.kernel_manager.has_kernel:
            # Pause the heart beat channel to prevent further warnings.
            self.kernel_manager.hb_channel.pause()

            # Prompt the user to restart the kernel. Un-pause the heartbeat if
            # they decline. (If they accept, the heartbeat will be un-paused
            # automatically when the kernel is restarted.)
            if self.confirm_restart:
                buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
                result = QtGui.QMessageBox.question(self, 'Restart kernel?',
                                                    message, buttons)
                do_restart = result == QtGui.QMessageBox.Yes
            else:
                # confirm_restart is False, so we don't need to ask user
                # anything, just do the restart
                do_restart = True
            if do_restart:
                try:
                    self.kernel_manager.restart_kernel(now=now)
                except RuntimeError:
                    self._append_plain_text('Kernel started externally. '
                                            'Cannot restart.\n',
                                            before_prompt=True
                                            )
                else:
                    self.reset()
            else:
                self.kernel_manager.hb_channel.unpause()

        else:
            self._append_plain_text('Kernel process is either remote or '
                                    'unspecified. Cannot restart.\n',
                                    before_prompt=True
                                    )


Instruction:
Given the following Python 3 function, write the documentation
def _call_tip(self):
        # Decide if it makes sense to show a call tip
        if not self.enable_calltips:
            return False
        cursor = self._get_cursor()
        cursor.movePosition(QtGui.QTextCursor.Left)
        if cursor.document().characterAt(cursor.position()) != '(':
            return False
        context = self._get_context(cursor)
        if not context:
            return False

        # Send the metadata request to the kernel
        name = '.'.join(context)
        msg_id = self.kernel_manager.shell_channel.object_info(name)
        pos = self._get_cursor().position()
        self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
        return True

Response: Shows a call tip at the current cursor location.


Instruction:
Here you have a function in Python 3, explain what it does
def _complete(self):
        context = self._get_context()
        if context:
            # Send the completion request to the kernel
            msg_id = self.kernel_manager.shell_channel.complete(
                '.'.join(context),                       # text
                self._get_input_buffer_cursor_line(),    # line
                self._get_input_buffer_cursor_column(),  # cursor_pos
                self.input_buffer)                       # block
            pos = self._get_cursor().position()
            info = self._CompletionRequest(msg_id, pos)
            self._request_info['complete'] = info

Response: Sends a completion request to the kernel.


Instruction:
How would you implement a function in Python 3 that
gets the context for the specified cursor.

Response:
def _get_context(self, cursor=None):
        """ Gets the context for the specified cursor (or the current cursor
            if none is specified).
        """
        if cursor is None:
            cursor = self._get_cursor()
        cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
                            QtGui.QTextCursor.KeepAnchor)
        text = cursor.selection().toPlainText()
        return self._completion_lexer.get_context(text)


Instruction:
Explain what the following Python 3 code does
def _process_execute_error(self, msg):
        content = msg['content']
        # If a SystemExit is passed along, this means exit() was called - also
        # all the ipython %exit magic syntax of '-k' to be used to keep
        # the kernel running
        if content['ename']=='SystemExit':
            keepkernel = content['evalue']=='-k' or content['evalue']=='True'
            self._keep_kernel_on_exit = keepkernel
            self.exit_requested.emit(self)
        else:
            traceback = ''.join(content['traceback'])
            self._append_plain_text(traceback)

Response: Process a reply to an execute error.


Instruction:
Can you tell what is the following Python 3 function doing
def _process_execute_ok(self, msg):
        payload = msg['content']['payload']
        for item in payload:
            if not self._process_execute_payload(item):
                warning = 'Warning: received unknown payload of type %s'
                print(warning % repr(item['source']))

Response: Process a reply for a successful execution request.


Instruction:
Write a Python 3 function that can
call whenever the document s content changes.

Response:
def _document_contents_change(self, position, removed, added):
        """ Called whenever the document's content changes. Display a call tip
            if appropriate.
        """
        # Calculate where the cursor should be *after* the change:
        position += added

        document = self._control.document()
        if position == self._get_cursor().position():
            self._call_tip()


Instruction:
How would you code a function in Python 3 to
add a plugin to my list of plugins to call if it has the attribute I m bound to.

Response:
def addPlugin(self, plugin, call):
        """Add plugin to my list of plugins to call, if it has the attribute
        I'm bound to.
        """
        meth = getattr(plugin, call, None)
        if meth is not None:
            if call == 'loadTestsFromModule' and \
                    len(inspect.getargspec(meth)[0]) == 2:
                orig_meth = meth
                meth = lambda module, path, **kwargs: orig_meth(module)
            self.plugins.append((plugin, meth))


Instruction:
Can you create a Python 3 function that
calls plugins in a chain where the result of each plugin call is sent to the next plugin as input.

Response:
def chain(self, *arg, **kw):
        """Call plugins in a chain, where the result of each plugin call is
        sent to the next plugin as input. The final output result is returned.
        """
        result = None
        # extract the static arguments (if any) from arg so they can
        # be passed to each plugin call in the chain
        static = [a for (static, a)
                  in zip(getattr(self.method, 'static_args', []), arg)
                  if static]
        for p, meth in self.plugins:
            result = meth(*arg, **kw)
            arg = static[:]
            arg.append(result)
        return result


Instruction:
Create a Python 3 function for
generating all non - None items in each non - None result.

Response:
def generate(self, *arg, **kw):
        """Call all plugins, yielding each item in each non-None result.
        """
        for p, meth in self.plugins:
            result = None
            try:
                result = meth(*arg, **kw)
                if result is not None:
                    for r in result:
                        yield r
            except (KeyboardInterrupt, SystemExit):
                raise
            except:
                exc = sys.exc_info()
                yield Failure(*exc)
                continue


Instruction:
How would you implement a function in Python 3 that
calls all plugins and return the first non - None result.

Response:
def simple(self, *arg, **kw):
        """Call all plugins, returning the first non-None result.
        """
        for p, meth in self.plugins:
            result = meth(*arg, **kw)
            if result is not None:
                return result


Instruction:
Can you write a function in Python 3 where it
adds plugins to the manager.

Response:
def addPlugins(self, plugins=(), extraplugins=()):
        """extraplugins are maintained in a separate list and
        re-added by loadPlugins() to prevent their being overwritten
        by plugins added by a subclass of PluginManager
        """
        self._extraplugins = extraplugins
        for plug in iterchain(plugins, extraplugins):
            self.addPlugin(plug)


Instruction:
Implement a function in Python 3 to
configure the set of plugins with the given options and config instance.

Response:
def configure(self, options, config):
        """Configure the set of plugins with the given options
        and config instance. After configuration, disabled plugins
        are removed from the plugins list.
        """
        log.debug("Configuring plugins")
        self.config = config
        cfg = PluginProxy('configure', self._plugins)
        cfg(options, config)
        enabled = [plug for plug in self._plugins if plug.enabled]
        self.plugins = enabled
        self.sort()
        log.debug("Plugins enabled: %s", enabled)


Instruction:
Make a summary of the following Python 3 code
def loadPlugins(self):
        from pkg_resources import iter_entry_points
        loaded = {}
        for entry_point, adapt in self.entry_points:
            for ep in iter_entry_points(entry_point):
                if ep.name in loaded:
                    continue
                loaded[ep.name] = True
                log.debug('%s load plugin %s', self.__class__.__name__, ep)
                try:
                    plugcls = ep.load()
                except KeyboardInterrupt:
                    raise
                except Exception, e:
                    # never want a plugin load to kill the test run
                    # but we can't log here because the logger is not yet
                    # configured
                    warn("Unable to load plugin %s: %s" % (ep, e),
                         RuntimeWarning)
                    continue
                if adapt:
                    plug = adapt(plugcls())
                else:
                    plug = plugcls()
                self.addPlugin(plug)
        super(EntryPointPluginManager, self).loadPlugins()

Response: Load plugins by iterating the entry point.


Instruction:
Here you have a function in Python 3, explain what it does
def loadPlugins(self):
        from nose.plugins import builtin
        for plug in builtin.plugins:
            self.addPlugin(plug())
        super(BuiltinPluginManager, self).loadPlugins()

Response: Load plugins in nose. plugins. builtin


Instruction:
Can you implement a function in Python 3 that
renders a LaTeX string to PNG.

Response:
def latex_to_png(s, encode=False, backend='mpl'):
    """Render a LaTeX string to PNG.

    Parameters
    ----------
    s : str
        The raw string containing valid inline LaTeX.
    encode : bool, optional
        Should the PNG data bebase64 encoded to make it JSON'able.
    backend : {mpl, dvipng}
        Backend for producing PNG data.

    None is returned when the backend cannot be used.

    """
    if backend == 'mpl':
        f = latex_to_png_mpl
    elif backend == 'dvipng':
        f = latex_to_png_dvipng
    else:
        raise ValueError('No such backend {0}'.format(backend))
    bin_data = f(s)
    if encode and bin_data:
        bin_data = encodestring(bin_data)
    return bin_data


Instruction:
Explain what the following Python 3 code does
def latex_to_html(s, alt='image'):
    base64_data = latex_to_png(s, encode=True)
    if base64_data:
        return _data_uri_template_png  % (base64_data, alt)

Response: Render LaTeX to HTML with embedded PNG data using data URIs.


Instruction:
Create a Python 3 function for
rendering a math expression into a closely - clipped bounding box and saves it to an image file.

Response:
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None):
    """
    Given a math expression, renders it in a closely-clipped bounding
    box to an image file.

    *s*
       A math expression.  The math portion should be enclosed in
       dollar signs.

    *filename_or_obj*
       A filepath or writable file-like object to write the image data
       to.

    *prop*
       If provided, a FontProperties() object describing the size and
       style of the text.

    *dpi*
       Override the output dpi, otherwise use the default associated
       with the output format.

    *format*
       The output format, eg. 'svg', 'pdf', 'ps' or 'png'.  If not
       provided, will be deduced from the filename.
    """
    from matplotlib import figure
    # backend_agg supports all of the core output formats
    from matplotlib.backends import backend_agg
    from matplotlib.font_manager import FontProperties
    from matplotlib.mathtext import MathTextParser

    if prop is None:
        prop = FontProperties()

    parser = MathTextParser('path')
    width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop)

    fig = figure.Figure(figsize=(width / 72.0, height / 72.0))
    fig.text(0, depth/height, s, fontproperties=prop)
    backend_agg.FigureCanvasAgg(fig)
    fig.savefig(filename_or_obj, dpi=dpi, format=format)

    return depth


Instruction:
Can you create a Python 3 function that
parses an editable requirement into a requirement and a URL

Response:
def parse_editable(editable_req, default_vcs=None):
    """Parses svn+http://blahblah@rev#egg=Foobar into a requirement
    (Foobar) and a URL"""

    url = editable_req
    extras = None

    # If a file path is specified with extras, strip off the extras.
    m = re.match(r'^(.+)(\[[^\]]+\])$', url)
    if m:
        url_no_extras = m.group(1)
        extras = m.group(2)
    else:
        url_no_extras = url

    if os.path.isdir(url_no_extras):
        if not os.path.exists(os.path.join(url_no_extras, 'setup.py')):
            raise InstallationError("Directory %r is not installable. File 'setup.py' not found.", url_no_extras)
        # Treating it as code that has already been checked out
        url_no_extras = path_to_url(url_no_extras)

    if url_no_extras.lower().startswith('file:'):
        if extras:
            return None, url_no_extras, pkg_resources.Requirement.parse('__placeholder__' + extras).extras
        else:
            return None, url_no_extras, None

    for version_control in vcs:
        if url.lower().startswith('%s:' % version_control):
            url = '%s+%s' % (version_control, url)
    if '+' not in url:
        if default_vcs:
            url = default_vcs + '+' + url
        else:
            raise InstallationError(
                '--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL' % editable_req)
    vc_type = url.split('+', 1)[0].lower()
    if not vcs.get_backend(vc_type):
        error_message = 'For --editable=%s only ' % editable_req + \
            ', '.join([backend.name + '+URL' for backend in vcs.backends]) + \
            ' is currently supported'
        raise InstallationError(error_message)
    match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req)
    if (not match or not match.group(1)) and vcs.get_backend(vc_type):
        parts = [p for p in editable_req.split('#', 1)[0].split('/') if p]
        if parts[-2] in ('tags', 'branches', 'tag', 'branch'):
            req = parts[-3]
        elif parts[-1] == 'trunk':
            req = parts[-2]
        else:
            raise InstallationError(
                '--editable=%s is not the right format; it must have #egg=Package'
                % editable_req)
    else:
        req = match.group(1)
    ## FIXME: use package_to_requirement?
    match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req)
    if match:
        # Strip off -dev, -0.2, etc.
        req = match.group(1)
    return req, url, None


Instruction:
Make a summary of the following Python 3 code
def check_if_exists(self):
        if self.req is None:
            return False
        try:
            self.satisfied_by = pkg_resources.get_distribution(self.req)
        except pkg_resources.DistributionNotFound:
            return False
        except pkg_resources.VersionConflict:
            existing_dist = pkg_resources.get_distribution(self.req.project_name)
            if self.use_user_site:
                if dist_in_usersite(existing_dist):
                    self.conflicts_with = existing_dist
                elif running_under_virtualenv() and dist_in_site_packages(existing_dist):
                    raise InstallationError("Will not install to the user site because it will lack sys.path precedence to %s in %s"
                                            %(existing_dist.project_name, existing_dist.location))
            else:
                self.conflicts_with = existing_dist
        return True

Response:
Find an installed distribution that satisfies or conflicts
            with this requirement and set self. satisfied_by or self. conflicts_with appropriately.


Instruction:
Explain what the following Python 3 code does
def cleanup_files(self, bundle=False):
        logger.notify('Cleaning up...')
        logger.indent += 2
        for req in self.reqs_to_cleanup:
            req.remove_temporary_source()

        remove_dir = []
        if self._pip_has_created_build_dir():
            remove_dir.append(self.build_dir)

        # The source dir of a bundle can always be removed.
        # FIXME: not if it pre-existed the bundle!
        if bundle:
            remove_dir.append(self.src_dir)

        for dir in remove_dir:
            if os.path.exists(dir):
                logger.info('Removing temporary dir %s...' % dir)
                rmtree(dir)

        logger.indent -= 2

Response: Clean up files remove builds.


Instruction:
Make a summary of the following Python 3 code
def install(self, install_options, global_options=()):
        to_install = [r for r in self.requirements.values()
                      if not r.satisfied_by]

        if to_install:
            logger.notify('Installing collected packages: %s' % ', '.join([req.name for req in to_install]))
        logger.indent += 2
        try:
            for requirement in to_install:
                if requirement.conflicts_with:
                    logger.notify('Found existing installation: %s'
                                  % requirement.conflicts_with)
                    logger.indent += 2
                    try:
                        requirement.uninstall(auto_confirm=True)
                    finally:
                        logger.indent -= 2
                try:
                    requirement.install(install_options, global_options)
                except:
                    # if install did not succeed, rollback previous uninstall
                    if requirement.conflicts_with and not requirement.install_succeeded:
                        requirement.rollback_uninstall()
                    raise
                else:
                    if requirement.conflicts_with and requirement.install_succeeded:
                        requirement.commit_uninstall()
                requirement.remove_temporary_source()
        finally:
            logger.indent -= 2
        self.successfully_installed = to_install

Response: Install all packages in this set.


Instruction:
Create a Python 3 function to
return a generator yielding a Process class instance for all the processes running on the local machine.

Response:
def process_iter():
    """Return a generator yielding a Process class instance for all
    running processes on the local machine.

    Every new Process instance is only created once and then cached
    into an internal table which is updated every time this is used.

    The sorting order in which processes are yielded is based on
    their PIDs.
    """
    def add(pid):
        proc = Process(pid)
        _pmap[proc.pid] = proc
        return proc

    def remove(pid):
        _pmap.pop(pid, None)

    a = set(get_pid_list())
    b = set(_pmap.keys())
    new_pids = a - b
    gone_pids = b - a

    for pid in gone_pids:
        remove(pid)
    for pid, proc in sorted(list(_pmap.items()) + \
                            list(dict.fromkeys(new_pids).items())):
        try:
            if proc is None:  # new process
                yield add(pid)
            else:
                # use is_running() to check whether PID has been reused by
                # another process in which case yield a new Process instance
                if proc.is_running():
                    yield proc
                else:
                    yield add(pid)
        except NoSuchProcess:
            remove(pid)
        except AccessDenied:
            # Process creation time can't be determined hence there's
            # no way to tell whether the pid of the cached process
            # has been reused. Just return the cached version.
            yield proc


Instruction:
Can you generate a brief explanation for the following Python 3 code
def cpu_percent(interval=0.1, percpu=False):
    global _last_cpu_times
    global _last_per_cpu_times
    blocking = interval is not None and interval > 0.0

    def calculate(t1, t2):
        t1_all = sum(t1)
        t1_busy = t1_all - t1.idle

        t2_all = sum(t2)
        t2_busy = t2_all - t2.idle

        # this usually indicates a float precision issue
        if t2_busy <= t1_busy:
            return 0.0

        busy_delta = t2_busy - t1_busy
        all_delta = t2_all - t1_all
        busy_perc = (busy_delta / all_delta) * 100
        return round(busy_perc, 1)

    # system-wide usage
    if not percpu:
        if blocking:
            t1 = cpu_times()
            time.sleep(interval)
        else:
            t1 = _last_cpu_times
        _last_cpu_times = cpu_times()
        return calculate(t1, _last_cpu_times)
    # per-cpu usage
    else:
        ret = []
        if blocking:
            tot1 = cpu_times(percpu=True)
            time.sleep(interval)
        else:
            tot1 = _last_per_cpu_times
        _last_per_cpu_times = cpu_times(percpu=True)
        for t1, t2 in zip(tot1, _last_per_cpu_times):
            ret.append(calculate(t1, t2))
        return ret

Response: Return a float representing the current system - wide CPU utilization as a percentage.


Instruction:
Can you generate the documentation for the following Python 3 function
def disk_io_counters(perdisk=False):
    rawdict = _psplatform.disk_io_counters()
    if not rawdict:
        raise RuntimeError("couldn't find any physical disk")
    if perdisk:
        for disk, fields in rawdict.items():
            rawdict[disk] = _nt_disk_iostat(*fields)
        return rawdict
    else:
        return _nt_disk_iostat(*[sum(x) for x in zip(*rawdict.values())])

Response: Return system disk I / O statistics as a namedtuple including the following attributes.


Instruction:
Write a Python 3 function that can
return network I/O statistics as a namedtuple including network interface names and statistics.

Response:
def network_io_counters(pernic=False):
    """Return network I/O statistics as a namedtuple including
    the following attributes:

     - bytes_sent:   number of bytes sent
     - bytes_recv:   number of bytes received
     - packets_sent: number of packets sent
     - packets_recv: number of packets received
     - errin:        total number of errors while receiving
     - errout:       total number of errors while sending
     - dropin:       total number of incoming packets which were dropped
     - dropout:      total number of outgoing packets which were dropped
                     (always 0 on OSX and BSD)

    If pernic is True return the same information for every
    network interface installed on the system as a dictionary
    with network interface names as the keys and the namedtuple
    described above as the values.
    """
    rawdict = _psplatform.network_io_counters()
    if not rawdict:
        raise RuntimeError("couldn't find any network interface")
    if pernic:
        for nic, fields in rawdict.items():
            rawdict[nic] = _nt_net_iostat(*fields)
        return rawdict
    else:
        return _nt_net_iostat(*[sum(x) for x in zip(*rawdict.values())])


Instruction:
Can you implement a function in Python 3 that
returns the amount of total used and free physical memory on the system in bytes plus the percentage usage.

Response:
def phymem_usage():
    """Return the amount of total, used and free physical memory
    on the system in bytes plus the percentage usage.
    Deprecated by psutil.virtual_memory().
    """
    mem = virtual_memory()
    return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent)


Instruction:
Write a Python 3 script for
returning the children of this process as a list of Process objects.

Response:
def get_children(self, recursive=False):
        """Return the children of this process as a list of Process
        objects.
        If recursive is True return all the parent descendants.

        Example (A == this process):

         A ─┐
            │
            ├─ B (child) ─┐
            │             └─ X (grandchild) ─┐
            │                                └─ Y (great grandchild)
            ├─ C (child)
            └─ D (child)

        >>> p.get_children()
        B, C, D
        >>> p.get_children(recursive=True)
        B, X, Y, C, D

        Note that in the example above if process X disappears
        process Y won't be returned either as the reference to
        process A is lost.
        """
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)

        ret = []
        if not recursive:
            for p in process_iter():
                try:
                    if p.ppid == self.pid:
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        if self.create_time <= p.create_time:
                            ret.append(p)
                except NoSuchProcess:
                    pass
        else:
            # construct a dict where 'values' are all the processes
            # having 'key' as their parent
            table = defaultdict(list)
            for p in process_iter():
                try:
                    table[p.ppid].append(p)
                except NoSuchProcess:
                    pass
            # At this point we have a mapping table where table[self.pid]
            # are the current process's children.
            # Below, we look for all descendants recursively, similarly
            # to a recursive function call.
            checkpids = [self.pid]
            for pid in checkpids:
                for child in table[pid]:
                    try:
                        # if child happens to be older than its parent
                        # (self) it means child's PID has been reused
                        intime = self.create_time <= child.create_time
                    except NoSuchProcess:
                        pass
                    else:
                        if intime:
                            ret.append(child)
                            if child.pid not in checkpids:
                                checkpids.append(child.pid)
        return ret


Instruction:
Explain what the following Python 3 code does
def get_cpu_percent(self, interval=0.1):
        blocking = interval is not None and interval > 0.0
        if blocking:
            st1 = sum(cpu_times())
            pt1 = self._platform_impl.get_cpu_times()
            time.sleep(interval)
            st2 = sum(cpu_times())
            pt2 = self._platform_impl.get_cpu_times()
        else:
            st1 = self._last_sys_cpu_times
            pt1 = self._last_proc_cpu_times
            st2 = sum(cpu_times())
            pt2 = self._platform_impl.get_cpu_times()
            if st1 is None or pt1 is None:
                self._last_sys_cpu_times = st2
                self._last_proc_cpu_times = pt2
                return 0.0

        delta_proc = (pt2.user - pt1.user) + (pt2.system - pt1.system)
        delta_time = st2 - st1
        # reset values for next call in case of interval == None
        self._last_sys_cpu_times = st2
        self._last_proc_cpu_times = pt2

        try:
            # the utilization split between all CPUs
            overall_percent = (delta_proc / delta_time) * 100
        except ZeroDivisionError:
            # interval was too low
            return 0.0
        # the utilization of a single CPU
        single_cpu_percent = overall_percent * NUM_CPUS
        # on posix a percentage > 100 is legitimate
        # http://stackoverflow.com/questions/1032357/comprehending-top-cpu-usage
        # on windows we use this ugly hack to avoid troubles with float
        # precision issues
        if os.name != 'posix':
            if single_cpu_percent > 100.0:
                return 100.0
        return round(single_cpu_percent, 1)

Response:
Return a float representing the current process CPU
            utilization as a percentage.


Instruction:
How would you explain what the following Python 3 function does
def get_memory_percent(self):
        rss = self._platform_impl.get_memory_info()[0]
        try:
            return (rss / float(TOTAL_PHYMEM)) * 100
        except ZeroDivisionError:
            return 0.0

Response:
Compare physical system memory to process resident memory and
            calculate process memory utilization as a percentage.


Instruction:
Make a summary of the following Python 3 code
def get_memory_maps(self, grouped=True):
        it = self._platform_impl.get_memory_maps()
        if grouped:
            d = {}
            for tupl in it:
                path = tupl[2]
                nums = tupl[3:]
                try:
                    d[path] = map(lambda x, y: x+y, d[path], nums)
                except KeyError:
                    d[path] = nums
            nt = self._platform_impl.nt_mmap_grouped
            return [nt(path, *d[path]) for path in d]
        else:
            nt = self._platform_impl.nt_mmap_ext
            return [nt(*x) for x in it]

Response:
Return process s mapped memory regions as a list of nameduples
        whose fields are variable depending on the platform.


Instruction:
Write a Python 3 function for
returning whether this process is running.

Response:
def is_running(self):
        """Return whether this process is running."""
        if self._gone:
            return False
        try:
            # Checking if pid is alive is not enough as the pid might
            # have been reused by another process.
            # pid + creation time, on the other hand, is supposed to
            # identify a process univocally.
            return self.create_time == \
                   self._platform_impl.get_process_create_time()
        except NoSuchProcess:
            self._gone = True
            return False


Instruction:
Create a Python 3 function for
sending a signal to the current process.

Response:
def send_signal(self, sig):
        """Send a signal to process (see signal module constants).
        On Windows only SIGTERM is valid and is treated as an alias
        for kill().
        """
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        if os.name == 'posix':
            try:
                os.kill(self.pid, sig)
            except OSError:
                err = sys.exc_info()[1]
                name = self._platform_impl._process_name
                if err.errno == errno.ESRCH:
                    raise NoSuchProcess(self.pid, name)
                if err.errno == errno.EPERM:
                    raise AccessDenied(self.pid, name)
                raise
        else:
            if sig == signal.SIGTERM:
                self._platform_impl.kill_process()
            else:
                raise ValueError("only SIGTERM is supported on Windows")


Instruction:
Can you generate the documentation for the following Python 3 function
def suspend(self):
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        # windows
        if hasattr(self._platform_impl, "suspend_process"):
            self._platform_impl.suspend_process()
        else:
            # posix
            self.send_signal(signal.SIGSTOP)

Response: Suspends the process execution.


Instruction:
Write a Python 3 function that can
resume the process execution.

Response:
def resume(self):
        """Resume process execution."""
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        # windows
        if hasattr(self._platform_impl, "resume_process"):
            self._platform_impl.resume_process()
        else:
            # posix
            self.send_signal(signal.SIGCONT)


Instruction:
Write a Python 3 function for
killing the current process.

Response:
def kill(self):
        """Kill the current process."""
        # safety measure in case the current process has been killed in
        # meantime and the kernel reused its PID
        if not self.is_running():
            name = self._platform_impl._process_name
            raise NoSuchProcess(self.pid, name)
        if os.name == 'posix':
            self.send_signal(signal.SIGKILL)
        else:
            self._platform_impl.kill_process()


Instruction:
Can you tell what is the following Python 3 function doing
def wait(self, timeout=None):
        if timeout is not None and not timeout >= 0:
            raise ValueError("timeout must be a positive integer")
        return self._platform_impl.process_wait(timeout)

Response: Wait for the current process to terminate and return its exit code.


Instruction:
Can you write a function in Python 3 where it
gets or set process niceness ( priority.

Response:
def nice(self):
        """Get or set process niceness (priority).
        Deprecated, use get_nice() instead.
        """
        msg = "this property is deprecated; use Process.get_nice() method instead"
        warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
        return self.get_nice()


Instruction:
Explain what the following Python 3 code does
def _wire_kernel(self):
        self.gtk_main, self.gtk_main_quit = self._hijack_gtk()
        gobject.timeout_add(int(1000*self.kernel._poll_interval),
                            self.iterate_kernel)
        return False

Response: Initializes the kernel inside GTK.


Instruction:
Can you tell what is the following Python 3 function doing
def _hijack_gtk(self):
        def dummy(*args, **kw):
            pass
        # save and trap main and main_quit from gtk
        orig_main, gtk.main = gtk.main, dummy
        orig_main_quit, gtk.main_quit = gtk.main_quit, dummy
        return orig_main, orig_main_quit

Response: Hijack a few key functions in GTK for IPython integration.


Instruction:
Implement a function in Python 3 to
am the given identifier defined in one of the namespaces which shadow the alias and magic namespaces?

Response:
def is_shadowed(identifier, ip):
    """Is the given identifier defined in one of the namespaces which shadow
    the alias and magic namespaces?  Note that an identifier is different
    than ifun, because it can not contain a '.' character."""
    # This is much safer than calling ofind, which can change state
    return (identifier in ip.user_ns \
            or identifier in ip.user_global_ns \
            or identifier in ip.ns_table['builtin'])


Instruction:
Given the following Python 3 function, write the documentation
def init_transformers(self):
        self._transformers = []
        for transformer_cls in _default_transformers:
            transformer_cls(
                shell=self.shell, prefilter_manager=self, config=self.config
            )

Response: Create the default transformers.


Instruction:
Can you tell what is the following Python 3 function doing
def register_transformer(self, transformer):
        if transformer not in self._transformers:
            self._transformers.append(transformer)
            self.sort_transformers()

Response: Register a transformer instance.


Instruction:
Explain what the following Python 3 code does
def unregister_transformer(self, transformer):
        if transformer in self._transformers:
            self._transformers.remove(transformer)

Response: Unregister a transformer instance.


Instruction:
Can you generate the documentation for the following Python 3 function
def init_checkers(self):
        self._checkers = []
        for checker in _default_checkers:
            checker(
                shell=self.shell, prefilter_manager=self, config=self.config
            )

Response: Create the default checkers.


Instruction:
Make a summary of the following Python 3 code
def register_checker(self, checker):
        if checker not in self._checkers:
            self._checkers.append(checker)
            self.sort_checkers()

Response: Register a checker instance.


Instruction:
Write a Python 3 function that can
create the default handlers.

Response:
def init_handlers(self):
        """Create the default handlers."""
        self._handlers = {}
        self._esc_handlers = {}
        for handler in _default_handlers:
            handler(
                shell=self.shell, prefilter_manager=self, config=self.config
            )


Instruction:
Can you tell what is the following Python 3 function doing
def register_handler(self, name, handler, esc_strings):
        self._handlers[name] = handler
        for esc_str in esc_strings:
            self._esc_handlers[esc_str] = handler

Response: Register a handler instance by name with esc_strings.


Instruction:
How would you code a function in Python 3 to
find a handler for the line_info by trying checkers.

Response:
def find_handler(self, line_info):
        """Find a handler for the line_info by trying checkers."""
        for checker in self.checkers:
            if checker.enabled:
                handler = checker.check(line_info)
                if handler:
                    return handler
        return self.get_handler_by_name('normal')


Instruction:
Given the following Python 3 function, write the documentation
def transform_line(self, line, continue_prompt):
        for transformer in self.transformers:
            if transformer.enabled:
                line = transformer.transform(line, continue_prompt)
        return line

Response: Calls the transformers in order of increasing priority.


Instruction:
Make a summary of the following Python 3 code
def check(self, line_info):
        "Instances of IPyAutocall in user_ns get autocalled immediately"
        obj = self.shell.user_ns.get(line_info.ifun, None)
        if isinstance(obj, IPyAutocall):
            obj.set_ip(self.shell)
            return self.prefilter_manager.get_handler_by_name('auto')
        else:
            return None

Response: Instances of IPyAutocall in user_ns get autocalled immediately


Instruction:
Implement a Python 3 function for
allowing and!! in multi - line statements if multi_line_specials is on

Response:
def check(self, line_info):
        "Allow ! and !! in multi-line statements if multi_line_specials is on"
        # Note that this one of the only places we check the first character of
        # ifun and *not* the pre_char.  Also note that the below test matches
        # both ! and !!.
        if line_info.continue_prompt \
            and self.prefilter_manager.multi_line_specials:
                if line_info.esc == ESC_MAGIC:
                    return self.prefilter_manager.get_handler_by_name('magic')
        else:
            return None


Instruction:
Here you have a function in Python 3, explain what it does
def check(self, line_info):
        if line_info.line[-1] == ESC_HELP \
               and line_info.esc != ESC_SHELL \
               and line_info.esc != ESC_SH_CAP:
            # the ? can be at the end, but *not* for either kind of shell escape,
            # because a ? can be a vaild final char in a shell cmd
            return self.prefilter_manager.get_handler_by_name('help')
        else:
            if line_info.pre:
                return None
            # This returns None like it should if no handler exists
            return self.prefilter_manager.get_handler_by_esc(line_info.esc)

Response: Check for escape character and return either a handler to handle it or None.


Instruction:
Write a Python 3 function that can
check if the ifun is magic and if automagic is on run it.

Response:
def check(self, line_info):
        """If the ifun is magic, and automagic is on, run it.  Note: normal,
        non-auto magic would already have been triggered via '%' in
        check_esc_chars. This just checks for automagic.  Also, before
        triggering the magic handler, make sure that there is nothing in the
        user namespace which could shadow it."""
        if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
            return None

        # We have a likely magic method.  Make sure we should actually call it.
        if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
            return None

        head = line_info.ifun.split('.',1)[0]
        if is_shadowed(head, self.shell):
            return None

        return self.prefilter_manager.get_handler_by_name('magic')


Instruction:
Can you generate the documentation for the following Python 3 function
def check(self, line_info):
        "Check if the initital identifier on the line is an alias."
        # Note: aliases can not contain '.'
        head = line_info.ifun.split('.',1)[0]
        if line_info.ifun not in self.shell.alias_manager \
               or head not in self.shell.alias_manager \
               or is_shadowed(head, self.shell):
            return None

        return self.prefilter_manager.get_handler_by_name('alias')

Response: Check if the initital identifier on the line is an alias.


Instruction:
Can you tell what is the following Python 3 function doing
def check(self, line_info):
        if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
            return self.prefilter_manager.get_handler_by_name('normal')
        else:
            return None

Response:
Check if the line starts with a function call or pretty much
        any python operator.


Instruction:
Create a Python 3 function to
check if the initial word / function is callable and autocall is on.

Response:
def check(self, line_info):
        "Check if the initial word/function is callable and autocall is on."
        if not self.shell.autocall:
            return None

        oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
        if not oinfo['found']:
            return None

        if callable(oinfo['obj']) \
               and (not self.exclude_regexp.match(line_info.the_rest)) \
               and self.function_name_regexp.match(line_info.ifun):
            return self.prefilter_manager.get_handler_by_name('auto')
        else:
            return None


Instruction:
How would you explain what the following Python 3 function does
def handle(self, line_info):
        # print "normal: ", line_info
        """Handle normal input lines. Use as a template for handlers."""

        # With autoindent on, we need some way to exit the input loop, and I
        # don't want to force the user to have to backspace all the way to
        # clear the line.  The rule will be in this case, that either two
        # lines of pure whitespace in a row, or a line of pure whitespace but
        # of a size different to the indent level, will exit the input loop.
        line = line_info.line
        continue_prompt = line_info.continue_prompt

        if (continue_prompt and
            self.shell.autoindent and
            line.isspace() and
            0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
            line = ''

        return line

Response: Handle normal input lines. Use as a template for handlers.


Instruction:
Write a Python 3 function for
handling alias input lines.

Response:
def handle(self, line_info):
        """Handle alias input lines. """
        transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest)
        # pre is needed, because it carries the leading whitespace.  Otherwise
        # aliases won't work in indented sections.
        line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, transformed)

        return line_out


Instruction:
How would you implement a function in Python 3 that
executes the line in a shell

Response:
def handle(self, line_info):
        """Execute the line in a shell, empty return value"""
        magic_handler = self.prefilter_manager.get_handler_by_name('magic')

        line = line_info.line
        if line.lstrip().startswith(ESC_SH_CAP):
            # rewrite LineInfo's line, ifun and the_rest to properly hold the
            # call to %sx and the actual command to be executed, so
            # handle_magic can work correctly.  Note that this works even if
            # the line is indented, so it handles multi_line_specials
            # properly.
            new_rest = line.lstrip()[2:]
            line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest)
            line_info.ifun = 'sx'
            line_info.the_rest = new_rest
            return magic_handler.handle(line_info)
        else:
            cmd = line.lstrip().lstrip(ESC_SHELL)
            line_out = '%sget_ipython().system(%r)' % (line_info.pre_whitespace, cmd)
        return line_out


Instruction:
Implement a Python 3 function for
handling lines which can be auto - executed quoting if requested.

Response:
def handle(self, line_info):
        """Handle lines which can be auto-executed, quoting if requested."""
        line    = line_info.line
        ifun    = line_info.ifun
        the_rest = line_info.the_rest
        pre     = line_info.pre
        esc     = line_info.esc
        continue_prompt = line_info.continue_prompt
        obj = line_info.ofind(self.shell)['obj']
        #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest)  # dbg

        # This should only be active for single-line input!
        if continue_prompt:
            return line

        force_auto = isinstance(obj, IPyAutocall)

        # User objects sometimes raise exceptions on attribute access other
        # than AttributeError (we've seen it in the past), so it's safest to be
        # ultra-conservative here and catch all.
        try:
            auto_rewrite = obj.rewrite
        except Exception:
            auto_rewrite = True

        if esc == ESC_QUOTE:
            # Auto-quote splitting on whitespace
            newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
        elif esc == ESC_QUOTE2:
            # Auto-quote whole string
            newcmd = '%s("%s")' % (ifun,the_rest)
        elif esc == ESC_PAREN:
            newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
        else:
            # Auto-paren.
            if force_auto:
                # Don't rewrite if it is already a call.
                do_rewrite = not the_rest.startswith('(')
            else:
                if not the_rest:
                    # We only apply it to argument-less calls if the autocall
                    # parameter is set to 2.
                    do_rewrite = (self.shell.autocall >= 2)
                elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
                    # Don't autocall in this case: item access for an object
                    # which is BOTH callable and implements __getitem__.
                    do_rewrite = False
                else:
                    do_rewrite = True

            # Figure out the rewritten command
            if do_rewrite:
                if the_rest.endswith(';'):
                    newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
                else:
                    newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
            else:
                normal_handler = self.prefilter_manager.get_handler_by_name('normal')
                return normal_handler.handle(line_info)

        # Display the rewritten call
        if auto_rewrite:
            self.shell.auto_rewrite_input(newcmd)

        return newcmd


Instruction:
Given the following Python 3 function, write the documentation
def handle(self, line_info):
        normal_handler = self.prefilter_manager.get_handler_by_name('normal')
        line = line_info.line
        # We need to make sure that we don't process lines which would be
        # otherwise valid python, such as "x=1 # what?"
        try:
            codeop.compile_command(line)
        except SyntaxError:
            # We should only handle as help stuff which is NOT valid syntax
            if line[0]==ESC_HELP:
                line = line[1:]
            elif line[-1]==ESC_HELP:
                line = line[:-1]
            if line:
                #print 'line:<%r>' % line  # dbg
                self.shell.magic('pinfo %s' % line_info.ifun)
            else:
                self.shell.show_usage()
            return '' # Empty string is needed here!
        except:
            raise
            # Pass any other exceptions through to the normal handler
            return normal_handler.handle(line_info)
        else:
            # If the code compiles ok, we should handle it normally
            return normal_handler.handle(line_info)

Response: Handle a single line of the log file.


Instruction:
Explain what the following Python 3 code does
def enterEvent(self, event):
        super(CallTipWidget, self).enterEvent(event)
        self._hide_timer.stop()

Response: Reimplemented to cancel the hide timer.


Instruction:
Make a summary of the following Python 3 code
def paintEvent(self, event):
        painter = QtGui.QStylePainter(self)
        option = QtGui.QStyleOptionFrame()
        option.initFrom(self)
        painter.drawPrimitive(QtGui.QStyle.PE_PanelTipLabel, option)
        painter.end()

        super(CallTipWidget, self).paintEvent(event)

Response: Reimplemented to paint the background panel.


Instruction:
Create a Python 3 function to
show the call line and docstring at the current cursor position.

Response:
def show_call_info(self, call_line=None, doc=None, maxlines=20):
        """ Attempts to show the specified call line and docstring at the
            current cursor location. The docstring is possibly truncated for
            length.
        """
        if doc:
            match = re.match("(?:[^\n]*\n){%i}" % maxlines, doc)
            if match:
                doc = doc[:match.end()] + '\n[Documentation continues...]'
        else:
            doc = ''

        if call_line:
            doc = '\n\n'.join([call_line, doc])
        return self.show_tip(doc)


Instruction:
Make a summary of the following Python 3 code
def show_tip(self, tip):
        # Attempt to find the cursor position at which to show the call tip.
        text_edit = self._text_edit
        document = text_edit.document()
        cursor = text_edit.textCursor()
        search_pos = cursor.position() - 1
        self._start_position, _ = self._find_parenthesis(search_pos,
                                                         forward=False)
        if self._start_position == -1:
            return False

        # Set the text and resize the widget accordingly.
        self.setText(tip)
        self.resize(self.sizeHint())

        # Locate and show the widget. Place the tip below the current line
        # unless it would be off the screen.  In that case, decide the best
        # location based trying to minimize the  area that goes off-screen.
        padding = 3 # Distance in pixels between cursor bounds and tip box.
        cursor_rect = text_edit.cursorRect(cursor)
        screen_rect = QtGui.qApp.desktop().screenGeometry(text_edit)
        point = text_edit.mapToGlobal(cursor_rect.bottomRight())
        point.setY(point.y() + padding)
        tip_height = self.size().height()
        tip_width = self.size().width()

        vertical = 'bottom'
        horizontal = 'Right'
        if point.y() + tip_height > screen_rect.height():
            point_ = text_edit.mapToGlobal(cursor_rect.topRight())
            # If tip is still off screen, check if point is in top or bottom
            # half of screen.
            if point_.y() - tip_height < padding:
                # If point is in upper half of screen, show tip below it.
                # otherwise above it.
                if 2*point.y() < screen_rect.height():
                    vertical = 'bottom'
                else:
                    vertical = 'top'
            else:
                vertical = 'top'
        if point.x() + tip_width > screen_rect.width():
            point_ = text_edit.mapToGlobal(cursor_rect.topRight())
            # If tip is still off-screen, check if point is in the right or
            # left half of the screen.
            if point_.x() - tip_width < padding:
                if 2*point.x() < screen_rect.width():
                    horizontal = 'Right'
                else:
                    horizontal = 'Left'
            else:
                horizontal = 'Left'
        pos = getattr(cursor_rect, '%s%s' %(vertical, horizontal))
        point = text_edit.mapToGlobal(pos())
        if vertical == 'top':
            point.setY(point.y() - tip_height - padding)
        if horizontal == 'Left':
            point.setX(point.x() - tip_width - padding)

        self.move(point)
        self.show()
        return True

Response: Show the specified tip at the current cursor location.


Instruction:
Here you have a function in Python 3, explain what it does
def _find_parenthesis(self, position, forward=True):
        commas = depth = 0
        document = self._text_edit.document()
        char = document.characterAt(position)
        # Search until a match is found or a non-printable character is
        # encountered.
        while category(char) != 'Cc' and position > 0:
            if char == ',' and depth == 0:
                commas += 1
            elif char == ')':
                if forward and depth == 0:
                    break
                depth += 1
            elif char == '(':
                if not forward and depth == 0:
                    break
                depth -= 1
            position += 1 if forward else -1
            char = document.characterAt(position)
        else:
            position = -1
        return position, commas

Response: Find the next parenthesis in the line that contains the given position.


Instruction:
Write a Python 3 script for
hiding the tooltip after some time has passed.

Response:
def _leave_event_hide(self):
        """ Hides the tooltip after some time has passed (assuming the cursor is
            not over the tooltip).
        """
        if (not self._hide_timer.isActive() and
            # If Enter events always came after Leave events, we wouldn't need
            # this check. But on Mac OS, it sometimes happens the other way
            # around when the tooltip is created.
            QtGui.qApp.topLevelAt(QtGui.QCursor.pos()) != self):
            self._hide_timer.start(300, self)


Instruction:
Make a summary of the following Python 3 code
def _cursor_position_changed(self):
        cursor = self._text_edit.textCursor()
        if cursor.position() <= self._start_position:
            self.hide()
        else:
            position, commas = self._find_parenthesis(self._start_position + 1)
            if position != -1:
                self.hide()

Response: Updates the tip based on user cursor position.


Instruction:
Write a Python 3 function for
creating a property that proxies the local attribute proxied_attr through the local attribute local_attr.

Response:
def proxied_attribute(local_attr, proxied_attr, doc):
    """Create a property that proxies attribute ``proxied_attr`` through
    the local attribute ``local_attr``.
    """
    def fget(self):
        return getattr(getattr(self, local_attr), proxied_attr)
    def fset(self, value):
        setattr(getattr(self, local_attr), proxied_attr, value)
    def fdel(self):
        delattr(getattr(self, local_attr), proxied_attr)
    return property(fget, fset, fdel, doc)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def canonicalize_path(cwd, path):

    if not os.path.isabs(path):
        path = os.path.join(cwd, path)

    return os.path.abspath(path)

Response: Canonicalizes a path relative to a given working directory.


Instruction:
Explain what the following Python 3 code does
def schema_validate(instance, schema, exc_class, *prefix, **kwargs):

    try:
        # Do the validation
        jsonschema.validate(instance, schema)
    except jsonschema.ValidationError as exc:
        # Assemble the path
        path = '/'.join((a if isinstance(a, six.string_types) else '[%d]' % a)
                        for a in itertools.chain(prefix, exc.path))

        # Construct the message
        message = 'Failed to validate "%s": %s' % (path, exc.message)

        # Raise the target exception
        raise exc_class(message, **kwargs)

Response: Validate the object with the given schema.


Instruction:
Can you implement a function in Python 3 that
iterates over a priority dictionary.

Response:
def iter_prio_dict(prio_dict):
    """
    Iterate over a priority dictionary.  A priority dictionary is a
    dictionary keyed by integer priority, with the values being lists
    of objects.  This generator will iterate over the dictionary in
    priority order (from lowest integer value to highest integer
    value), yielding each object in the lists in turn.

    :param prio_dict: A priority dictionary, as described above.

    :returns: An iterator that yields each object in the correct
              order, based on priority and ordering within the
              priority values.
    """

    for _prio, objs in sorted(prio_dict.items(), key=lambda x: x[0]):
        for obj in objs:
            yield obj


Instruction:
How would you code a function in Python 3 to
retrieve a read - only subordinate mapping.

Response:
def masked(self):
        """
        Retrieve a read-only subordinate mapping.  All values are
        stringified, and sensitive values are masked.  The subordinate
        mapping implements the context manager protocol for
        convenience.
        """

        if self._masked is None:
            self._masked = MaskedDict(self)

        return self._masked


Instruction:
Write a Python 3 function that can
build a file path from *paths* and return the contents.

Response:
def read(*paths):
    """Build a file path from *paths* and return the contents."""
    with open(os.path.join(*paths), 'r') as file_handler:
        return file_handler.read()


Instruction:
Can you generate a brief explanation for the following Python 3 code
def virtualenv_no_global():
    #this mirrors the logic in virtualenv.py for locating the no-global-site-packages.txt file
    site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
    no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
    if running_under_virtualenv() and os.path.isfile(no_global_file):
        return True

Response: Return True if in a virtualenv and no system site packages.


Instruction:
Can you write a function in Python 3 where it
parallels word frequency counter.

Response:
def pwordfreq(view, fnames):
    """Parallel word frequency counter.

    view - An IPython DirectView
    fnames - The filenames containing the split data.
    """
    assert len(fnames) == len(view.targets)
    view.scatter('fname', fnames, flatten=True)
    ar = view.apply(wordfreq, Reference('fname'))
    freqs_list = ar.get()
    word_set = set()
    for f in freqs_list:
        word_set.update(f.keys())
    freqs = dict(zip(word_set, repeat(0)))
    for f in freqs_list:
        for word, count in f.iteritems():
            freqs[word] += count
    return freqs


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

	def simple_decorator(View):
		View.dispatch = method_decorator(function_decorator)(View.dispatch)
		return View

	return simple_decorator

Response:
Convert a function based decorator into a class based decorator usable
	on class based Views.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def default_aliases():
    # Note: the aliases defined here should be safe to use on a kernel
    # regardless of what frontend it is attached to.  Frontends that use a
    # kernel in-process can define additional aliases that will only work in
    # their case.  For example, things like 'less' or 'clear' that manipulate
    # the terminal should NOT be declared here, as they will only work if the
    # kernel is running inside a true terminal, and not over the network.

    if os.name == 'posix':
        default_aliases = [('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
                           ('mv', 'mv -i'), ('rm', 'rm -i'), ('cp', 'cp -i'),
                           ('cat', 'cat'),
                           ]
        # Useful set of ls aliases.  The GNU and BSD options are a little
        # different, so we make aliases that provide as similar as possible
        # behavior in ipython, by passing the right flags for each platform
        if sys.platform.startswith('linux'):
            ls_aliases = [('ls', 'ls -F --color'),
                          # long ls
                          ('ll', 'ls -F -o --color'),
                          # ls normal files only
                          ('lf', 'ls -F -o --color %l | grep ^-'),
                          # ls symbolic links
                          ('lk', 'ls -F -o --color %l | grep ^l'),
                          # directories or links to directories,
                          ('ldir', 'ls -F -o --color %l | grep /$'),
                          # things which are executable
                          ('lx', 'ls -F -o --color %l | grep ^-..x'),
                          ]
        else:
            # BSD, OSX, etc.
            ls_aliases = [('ls', 'ls -F'),
                          # long ls
                          ('ll', 'ls -F -l'),
                          # ls normal files only
                          ('lf', 'ls -F -l %l | grep ^-'),
                          # ls symbolic links
                          ('lk', 'ls -F -l %l | grep ^l'),
                          # directories or links to directories,
                          ('ldir', 'ls -F -l %l | grep /$'),
                          # things which are executable
                          ('lx', 'ls -F -l %l | grep ^-..x'),
                          ]
        default_aliases = default_aliases + ls_aliases
    elif os.name in ['nt', 'dos']:
        default_aliases = [('ls', 'dir /on'),
                           ('ddir', 'dir /ad /on'), ('ldir', 'dir /ad /on'),
                           ('mkdir', 'mkdir'), ('rmdir', 'rmdir'),
                           ('echo', 'echo'), ('ren', 'ren'), ('copy', 'copy'),
                           ]
    else:
        default_aliases = []

    return default_aliases

Response: Return a list of shell aliases to auto - define.


Instruction:
Given the following Python 3 function, write the documentation
def soft_define_alias(self, name, cmd):
        try:
            self.define_alias(name, cmd)
        except AliasError, e:
            error("Invalid alias: %s" % e)

Response: Define an alias but don t raise on an AliasError.


Instruction:
Make a summary of the following Python 3 code
def define_alias(self, name, cmd):
        nargs = self.validate_alias(name, cmd)
        self.alias_table[name] = (nargs, cmd)

Response: Define a new alias after validating it.


Instruction:
Here you have a function in Python 3, explain what it does
def validate_alias(self, name, cmd):
        if name in self.no_alias:
            raise InvalidAliasError("The name %s can't be aliased "
                                    "because it is a keyword or builtin." % name)
        if not (isinstance(cmd, basestring)):
            raise InvalidAliasError("An alias command must be a string, "
                                    "got: %r" % cmd)
        nargs = cmd.count('%s')
        if nargs>0 and cmd.find('%l')>=0:
            raise InvalidAliasError('The %s and %l specifiers are mutually '
                                    'exclusive in alias definitions.')
        return nargs

Response: Validate an alias and return the its number of arguments.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def call_alias(self, alias, rest=''):
        cmd = self.transform_alias(alias, rest)
        try:
            self.shell.system(cmd)
        except:
            self.shell.showtraceback()

Response: Call an alias given its name and the rest of the line.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def transform_alias(self, alias,rest=''):
        nargs, cmd = self.alias_table[alias]

        if ' ' in cmd and os.path.isfile(cmd):
            cmd = '"%s"' % cmd

        # Expand the %l special to be the user's input line
        if cmd.find('%l') >= 0:
            cmd = cmd.replace('%l', rest)
            rest = ''
        if nargs==0:
            # Simple, argument-less aliases
            cmd = '%s %s' % (cmd, rest)
        else:
            # Handle aliases with positional arguments
            args = rest.split(None, nargs)
            if len(args) < nargs:
                raise AliasError('Alias <%s> requires %s arguments, %s given.' %
                      (alias, nargs, len(args)))
            cmd = '%s %s' % (cmd % tuple(args[:nargs]),' '.join(args[nargs:]))
        return cmd

Response: Transform an alias to a system command string.


Instruction:
Write a Python 3 function for
expanding an alias in the command line

Response:
def expand_alias(self, line):
        """ Expand an alias in the command line

        Returns the provided command line, possibly with the first word
        (command) translated according to alias expansion rules.

        [ipython]|16> _ip.expand_aliases("np myfile.txt")
                 <16> 'q:/opt/np/notepad++.exe myfile.txt'
        """

        pre,_,fn,rest = split_user_input(line)
        res = pre + self.expand_aliases(fn, rest)
        return res


Instruction:
Write a Python 3 function for
expanding multiple levels of aliases

Response:
def expand_aliases(self, fn, rest):
        """Expand multiple levels of aliases:

        if:

        alias foo bar /tmp
        alias baz foo

        then:

        baz huhhahhei -> bar /tmp huhhahhei
        """
        line = fn + " " + rest

        done = set()
        while 1:
            pre,_,fn,rest = split_user_input(line, shell_line_split)
            if fn in self.alias_table:
                if fn in done:
                    warn("Cyclic alias definition, repeated '%s'" % fn)
                    return ""
                done.add(fn)

                l2 = self.transform_alias(fn, rest)
                if l2 == line:
                    break
                # ls -> ls -F should not recurse forever
                if l2.split(None,1)[0] == line.split(None,1)[0]:
                    line = l2
                    break
                line=l2
            else:
                break

        return line


Instruction:
Given the following Python 3 function, write the documentation
def shquote(arg):
    for c in '"', "'", "\\", "#":
        if c in arg: return repr(arg)
    if arg.split()<>[arg]:
        return repr(arg)
    return arg

Response: Quote an argument for later parsing by shlex. split


Instruction:
Create a Python 3 function for
producing rst from nose help

Response:
def autohelp_directive(dirname, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    """produces rst from nose help"""
    config = Config(parserClass=OptBucket,
                    plugins=BuiltinPluginManager())
    parser = config.getParser(TestProgram.usage())
    rst = ViewList()
    for line in parser.format_help().split('\n'):
        rst.append(line, '<autodoc>')

    rst.append('Options', '<autodoc>')
    rst.append('-------', '<autodoc>')
    rst.append('', '<autodoc>')
    for opt in parser:
        rst.append(opt.options(), '<autodoc>')
        rst.append('   \n', '<autodoc>')
        rst.append('   ' + opt.help + '\n', '<autodoc>')
        rst.append('\n', '<autodoc>')
    node = nodes.section()
    node.document = state.document
    surrounding_title_styles = state.memo.title_styles
    surrounding_section_level = state.memo.section_level
    state.memo.title_styles = []
    state.memo.section_level = 0
    state.nested_parse(rst, 0, node, match_titles=1)
    state.memo.title_styles = surrounding_title_styles
    state.memo.section_level = surrounding_section_level

    return node.children


Instruction:
Explain what the following Python 3 code does
def reset_sgr(self):
        self.intensity = 0
        self.italic = False
        self.bold = False
        self.underline = False
        self.foreground_color = None
        self.background_color = None

Response: Reset the graphics attributs to their default values.


Instruction:
Can you write a function in Python 3 where it
yields substrings for which the same escape code applies.

Response:
def split_string(self, string):
        """ Yields substrings for which the same escape code applies.
        """
        self.actions = []
        start = 0

        # strings ending with \r are assumed to be ending in \r\n since
        # \n is appended to output strings automatically.  Accounting
        # for that, here.
        last_char = '\n' if len(string) > 0 and string[-1] == '\n' else None
        string = string[:-1] if last_char is not None else string

        for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):
            raw = string[start:match.start()]
            substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
            if substring or self.actions:
                yield substring
                self.actions = []
            start = match.end()

            groups = filter(lambda x: x is not None, match.groups())
            g0 = groups[0]
            if g0 == '\a':
                self.actions.append(BeepAction('beep'))
                yield None
                self.actions = []
            elif g0 == '\r':
                self.actions.append(CarriageReturnAction('carriage-return'))
                yield None
                self.actions = []
            elif g0 == '\b':
                self.actions.append(BackSpaceAction('backspace'))
                yield None
                self.actions = []
            elif g0 == '\n' or g0 == '\r\n':
                self.actions.append(NewLineAction('newline'))
                yield g0
                self.actions = []
            else:
                params = [ param for param in groups[1].split(';') if param ]
                if g0.startswith('['):
                    # Case 1: CSI code.
                    try:
                        params = map(int, params)
                    except ValueError:
                        # Silently discard badly formed codes.
                        pass
                    else:
                        self.set_csi_code(groups[2], params)

                elif g0.startswith(']'):
                    # Case 2: OSC code.
                    self.set_osc_code(params)

        raw = string[start:]
        substring = SPECIAL_PATTERN.sub(self._replace_special, raw)
        if substring or self.actions:
            yield substring

        if last_char is not None:
            self.actions.append(NewLineAction('newline'))
            yield last_char


Instruction:
Explain what the following Python 3 code does
def set_csi_code(self, command, params=[]):
        if command == 'm':   # SGR - Select Graphic Rendition
            if params:
                self.set_sgr_code(params)
            else:
                self.set_sgr_code([0])

        elif (command == 'J' or # ED - Erase Data
              command == 'K'):  # EL - Erase in Line
            code = params[0] if params else 0
            if 0 <= code <= 2:
                area = 'screen' if command == 'J' else 'line'
                if code == 0:
                    erase_to = 'end'
                elif code == 1:
                    erase_to = 'start'
                elif code == 2:
                    erase_to = 'all'
                self.actions.append(EraseAction('erase', area, erase_to))

        elif (command == 'S' or # SU - Scroll Up
              command == 'T'):  # SD - Scroll Down
            dir = 'up' if command == 'S' else 'down'
            count = params[0] if params else 1
            self.actions.append(ScrollAction('scroll', dir, 'line', count))

Response: Sets attributes based on CSI Control Sequence Introducer code.


Instruction:
Write a Python 3 script to
set attributes based on OSC command parameters.

Response:
def set_osc_code(self, params):
        """ Set attributes based on OSC (Operating System Command) parameters.

        Parameters
        ----------
        params : sequence of str
            The parameters for the command.
        """
        try:
            command = int(params.pop(0))
        except (IndexError, ValueError):
            return

        if command == 4:
            # xterm-specific: set color number to color spec.
            try:
                color = int(params.pop(0))
                spec = params.pop(0)
                self.color_map[color] = self._parse_xterm_color_spec(spec)
            except (IndexError, ValueError):
                pass