def Func(arg_0, arg_1, arg_2):
        """ Reimplemented to ensure a console-like behavior in the underlying
            text widgets.
        """
        arg_3 = arg_2.type()
        if arg_3 == QtCore.QEvent.KeyPress:

            # Re-map keys for all filtered widgets.
            arg_4 = arg_2.key()
            if arg_0._control_key_down(arg_2.modifiers()) and \
                    arg_4 in arg_0._ctrl_down_remap:
                arg_5 = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
                                            arg_0._ctrl_down_remap[arg_4],
                                            QtCore.Qt.NoModifier)
                QtGui.qApp.sendEvent(arg_1, arg_5)
                return True

            elif arg_1 == arg_0._control:
                return arg_0._event_filter_console_keypress(arg_2)

            elif arg_1 == arg_0._page_control:
                return arg_0._event_filter_page_keypress(arg_2)

        # Make middle-click paste safe.
        elif arg_3 == QtCore.QEvent.MouseButtonRelease and \
                arg_2.button() == QtCore.Qt.MidButton and \
                arg_1 == arg_0._control.viewport():
            arg_6 = arg_0._control.cursorForPosition(arg_2.pos())
            arg_0._control.setTextCursor(arg_6)
            arg_0.paste(QtGui.QClipboard.Selection)
            return True

        # Manually adjust the scrollbars *after* a resize event is dispatched.
        elif arg_3 == QtCore.QEvent.Resize and not arg_0._filter_resize:
            arg_0._filter_resize = True
            QtGui.qApp.sendEvent(arg_1, arg_2)
            arg_0._adjust_scrollbars()
            arg_0._filter_resize = False
            return True

        # Override shortcuts for all filtered widgets.
        elif arg_3 == QtCore.QEvent.ShortcutOverride and \
                arg_0.override_shortcuts and \
                arg_0._control_key_down(arg_2.modifiers()) and \
                arg_2.key() in arg_0._shortcuts:
            arg_2.accept()

        # Ensure that drags are safe. The problem is that the drag starting
        # logic, which determines whether the drag is a Copy or Move, is locked
        # down in QTextControl. If the widget is editable, which it must be if
        # we're not executing, the drag will be a Move. The following hack
        # prevents QTextControl from deleting the text by clearing the selection
        # when a drag leave event originating from this widget is dispatched.
        # The fact that we have to clear the user's selection is unfortunate,
        # but the alternative--trying to prevent Qt from using its hardwired
        # drag logic and writing our own--is worse.
        elif arg_3 == QtCore.QEvent.DragEnter and \
                arg_1 == arg_0._control.viewport() and \
                arg_2.source() == arg_0._control.viewport():
            arg_0._filter_drag = True
        elif arg_3 == QtCore.QEvent.DragLeave and \
                arg_1 == arg_0._control.viewport() and \
                arg_0._filter_drag:
            arg_6 = arg_0._control.textCursor()
            arg_6.clearSelection()
            arg_0._control.setTextCursor(arg_6)
            arg_0._filter_drag = False

        # Ensure that drops are safe.
        elif arg_3 == QtCore.QEvent.Drop and arg_1 == arg_0._control.viewport():
            arg_6 = arg_0._control.cursorForPosition(arg_2.pos())
            if arg_0._in_buffer(arg_6.position()):
                arg_9 = arg_2.mimeData().text()
                arg_0._insert_plain_text_into_buffer(arg_6, arg_9)

            # Qt is expecting to get something here--drag and drop occurs in its
            # own event loop. Send a DragLeave event to end it.
            QtGui.qApp.sendEvent(arg_1, QtGui.QDragLeaveEvent())
            return True

        # Handle scrolling of the vsplit pager. This hack attempts to solve
        # problems with tearing of the help text inside the pager window.  This
        # happens only on Mac OS X with both PySide and PyQt. This fix isn't
        # perfect but makes the pager more usable.
        elif arg_3 in arg_0._pager_scroll_events and \
                arg_1 == arg_0._page_control:
            arg_0._page_control.repaint()
            return True
        return super(ConsoleWidget, arg_0).Func(arg_1, arg_2)


def Func(arg_0):
        """ Reimplemented to suggest a size that is 80 characters wide and
            25 lines high.
        """
        arg_1 = QtGui.QFontMetrics(arg_0.font)
        arg_2 = (arg_0._control.frameWidth() +
                  arg_0._control.document().documentMargin()) * 2
        arg_3 = arg_0.style()
        arg_4 = arg_3.pixelMetric(QtGui.QStyle.PM_SplitterWidth)

        # Note 1: Despite my best efforts to take the various margins into
        # account, the width is still coming out a bit too small, so we include
        # a fudge factor of one character here.
        # Note 2: QFontMetrics.maxWidth is not used here or anywhere else due
        # to a Qt bug on certain Mac OS systems where it returns 0.
        arg_5 = arg_1.width(' ') * 81 + arg_2
        arg_5 += arg_3.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
        if arg_0.paging == 'hsplit':
            arg_5 = arg_5 * 2 + arg_4

        arg_6 = arg_1.height() * 25 + arg_2
        if arg_0.paging == 'vsplit':
            arg_6 = arg_6 * 2 + arg_4

        return QtCore.QSize(arg_5, arg_6)


def Func(arg_0):
        """ Returns whether text can be cut to the clipboard.
        """
        arg_1 = arg_0._control.textCursor()
        return (arg_1.hasSelection() and
                arg_0._in_buffer(arg_1.anchor()) and
                arg_0._in_buffer(arg_1.position()))


def Func(arg_0):
        """ Returns whether text can be pasted from the clipboard.
        """
        if arg_0._control.textInteractionFlags() & QtCore.Qt.TextEditable:
            return bool(QtGui.QApplication.clipboard().text())
        return False


def Func(arg_0, arg_1=True):
        """ Clear the console.

        Parameters:
        -----------
        keep_input : bool, optional (default True)
            If set, restores the old input buffer if a new prompt is written.
        """
        if arg_0._executing:
            arg_0._control.Func()
        else:
            if arg_1:
                arg_2 = arg_0.input_buffer
            arg_0._control.Func()
            arg_0._show_prompt()
            if arg_1:
                arg_0.input_buffer = arg_2


def Func(arg_0, arg_1=None, arg_2=False, arg_3=False):
        """ Executes source or the input buffer, possibly prompting for more
        input.

        Parameters:
        -----------
        source : str, optional

            The source to Func. If not specified, the input buffer will be
            used. If specified and 'hidden' is False, the input buffer will be
            replaced with the source before execution.

        hidden : bool, optional (default False)

            If set, no output will be shown and the prompt will not be modified.
            In other words, it will be completely invisible to the user that
            an execution has occurred.

        interactive : bool, optional (default False)

            Whether the console is to treat the source as having been manually
            entered by the user. The effect of this parameter depends on the
            subclass implementation.

        Raises:
        -------
        RuntimeError
            If incomplete input is given and 'hidden' is True. In this case,
            it is not possible to prompt for more input.

        Returns:
        --------
        A boolean indicating whether the source was Funcd.
        """
        # WARNING: The order in which things happen here is very particular, in
        # large part because our syntax highlighting is fragile. If you change
        # something, test carefully!

        # Decide what to Func.
        if arg_1 is None:
            arg_1 = arg_0.input_buffer
            if not arg_2:
                # A newline is appended later, but it should be considered part
                # of the input buffer.
                arg_1 += '\n'
        elif not arg_2:
            arg_0.input_buffer = arg_1

        # Execute the source or show a continuation prompt if it is incomplete.
        arg_5 = arg_0._is_complete(arg_1, arg_3)
        if arg_2:
            if arg_5:
                arg_0._Func(arg_1, arg_2)
            else:
                arg_6 = 'Incomplete noninteractive input: "%s"'
                raise RuntimeError(arg_6 % arg_1)
        else:
            if arg_5:
                arg_0._append_plain_text('\n')
                arg_0._input_buffer_executing = arg_0.input_buffer
                arg_0._executing = True
                arg_0._prompt_finished()

                # The maximum block count is only in effect during execution.
                # This ensures that _prompt_pos does not become invalid due to
                # text truncation.
                arg_0._control.document().setMaximumBlockCount(arg_0.buffer_size)

                # Setting a positive maximum block count will automatically
                # disable the undo/redo history, but just to be safe:
                arg_0._control.setUndoRedoEnabled(False)

                # Perform actual execution.
                arg_0._Func(arg_1, arg_2)

            else:
                # Do this inside an edit block so continuation prompts are
                # removed seamlessly via undo/redo.
                arg_9 = arg_0._get_end_cursor()
                arg_9.beginEditBlock()
                arg_9.insertText('\n')
                arg_0._insert_continuation_prompt(arg_9)
                arg_9.endEditBlock()

                # Do not do this inside the edit block. It works as expected
                # when using a QPlainTextEdit control, but does not have an
                # effect when using a QTextEdit. I believe this is a Qt bug.
                arg_0._control.moveCursor(QtGui.QTextCursor.End)

        return arg_5


def Func(arg_0, arg_1):
        """ Sets the text in the input buffer.

        If the console is currently executing, this call has no *immediate*
        effect. When the execution is finished, the input buffer will be updated
        appropriately.
        """
        # If we're executing, store the text for later.
        if arg_0._executing:
            arg_0._input_buffer_pending = arg_1
            return

        # Remove old text.
        arg_3 = arg_0._get_end_cursor()
        arg_3.beginEditBlock()
        arg_3.setPosition(arg_0._prompt_pos, QtGui.QTextCursor.KeepAnchor)
        arg_3.removeSelectedText()

        # Insert new text with continuation prompts.
        arg_0._insert_plain_text_into_buffer(arg_0._get_prompt_cursor(), arg_1)
        arg_3.endEditBlock()
        arg_0._control.moveCursor(QtGui.QTextCursor.End)


def Func(arg_0, arg_1 = None):
        """ Print the contents of the ConsoleWidget to the specified QPrinter.
        """
        if (not arg_1):
            arg_1 = QtGui.QPrinter()
            if(QtGui.QPrintDialog(arg_1).exec_() != QtGui.QDialog.Accepted):
                return
        arg_0._control.Func(arg_1)


def Func(arg_0):
        """ Moves the prompt to the top of the viewport.
        """
        if not arg_0._executing:
            arg_1 = arg_0._get_prompt_cursor()
            if arg_0._get_cursor().blockNumber() < arg_1.blockNumber():
                arg_0._set_cursor(arg_1)
            arg_0._set_top_cursor(arg_1)


def Func(arg_0):
        """ Sets the font to the default fixed-width font for this platform.
        """
        if sys.platform == 'win32':
            # Consolas ships with Vista/Win7, fallback to Courier if needed
            arg_1 = 'Courier'
        elif sys.platform == 'darwin':
            # OSX always has Monaco
            arg_1 = 'Monaco'
        else:
            # Monospace should always exist
            arg_1 = 'Monospace'
        arg_2 = get_font(arg_0.font_family, arg_1)
        if arg_0.font_size:
            arg_2.setPointSize(arg_0.font_size)
        else:
            arg_2.setPointSize(QtGui.qApp.font().pointSize())
        arg_2.setStyleHint(QtGui.QFont.TypeWriter)
        arg_0._set_font(arg_2)


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """ A low-level method for appending content to the end of the buffer.

        If 'before_prompt' is enabled, the content will be inserted before the
        current prompt, if there is one.
        """
        # Determine where to insert the content.
        arg_4 = arg_0._control.textCursor()
        if arg_3 and (arg_0._reading or not arg_0._executing):
            arg_4.setPosition(arg_0._append_before_prompt_pos)
        else:
            arg_4.movePosition(QtGui.QTextCursor.End)
        arg_5 = arg_4.position()

        # Perform the insertion.
        arg_6 = arg_1(arg_4, arg_2)

        # Adjust the prompt position if we have inserted before it. This is safe
        # because buffer truncation is disabled when not executing.
        if arg_3 and not arg_0._executing:
            arg_7 = arg_4.position() - arg_5
            arg_0._append_before_prompt_pos += arg_7
            arg_0._prompt_pos += arg_7

        return arg_6


def Func(arg_0, arg_1, arg_2=False):
        """ Appends HTML at the end of the console buffer.
        """
        arg_0._append_custom(arg_0._insert_html, arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """ Appends HTML, then returns the plain text version of it.
        """
        return arg_0._append_custom(arg_0._insert_html_fetching_plain_text,
                                   arg_1, arg_2)


def Func(arg_0, arg_1, arg_2=False):
        """ Appends plain text, processing ANSI codes if enabled.
        """
        arg_0._append_custom(arg_0._insert_plain_text, arg_1, arg_2)


def Func(arg_0):
        """ Clears the "temporary text" buffer, i.e. all the text following
            the prompt region.
        """
        # Select and remove all text below the input buffer.
        arg_1 = arg_0._get_prompt_cursor()
        arg_2 = arg_0._continuation_prompt.lstrip()
        if(arg_0._temp_buffer_filled):
            arg_0._temp_buffer_filled = False
            while arg_1.movePosition(QtGui.QTextCursor.NextBlock):
                arg_4 = QtGui.QTextCursor(arg_1)
                arg_4.select(QtGui.QTextCursor.BlockUnderCursor)
                arg_5 = arg_4.selection().toPlainText().lstrip()
                if not arg_5.startswith(arg_2):
                    break
        else:
            # We've reached the end of the input buffer and no text follows.
            return
        arg_1.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
        arg_1.movePosition(QtGui.QTextCursor.End,
                            QtGui.QTextCursor.KeepAnchor)
        arg_1.removeSelectedText()

        # After doing this, we have no choice but to clear the undo/redo
        # history. Otherwise, the text is not "temporary" at all, because it
        # can be recalled with undo/redo. Unfortunately, Qt does not expose
        # fine-grained control to the undo/redo system.
        if arg_0._control.isUndoRedoEnabled():
            arg_0._control.setUndoRedoEnabled(False)
            arg_0._control.setUndoRedoEnabled(True)


def Func(arg_0, arg_1, arg_2, arg_3=False):
        """fill the area below the active editting zone with text"""

        arg_4 = arg_0._control.textCursor().position()

        arg_1.beginEditBlock()
        arg_0._append_plain_text('\n')
        arg_0._page(arg_2, arg_3=arg_3)
        arg_1.endEditBlock()

        arg_1.setPosition(arg_4)
        arg_0._control.moveCursor(QtGui.QTextCursor.End)
        arg_0._control.setTextCursor(arg_1)

        arg_0._temp_buffer_filled = True


def Func(arg_0, arg_1):
        """ Filter key events for the paging widget to create console-like
            interface.
        """
        arg_2 = arg_1.key()
        arg_3 = arg_0._control_key_down(arg_1.modifiers())
        arg_4 = arg_1.modifiers() & QtCore.Qt.AltModifier

        if arg_3:
            if arg_2 == QtCore.Qt.Key_O:
                arg_0._control.setFocus()
                arg_5 = True

        elif arg_4:
            if arg_2 == QtCore.Qt.Key_Greater:
                arg_0._page_control.moveCursor(QtGui.QTextCursor.End)
                arg_6 = True

            elif arg_2 == QtCore.Qt.Key_Less:
                arg_0._page_control.moveCursor(QtGui.QTextCursor.Start)
                arg_6 = True

        elif arg_2 in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
            if arg_0._splitter:
                arg_0._page_control.hide()
                arg_0._control.setFocus()
            else:
                arg_0.layout().setCurrentWidget(arg_0._control)
            return True

        elif arg_2 in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
                     QtCore.Qt.Key_Tab):
            arg_7 = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
                                        QtCore.Qt.Key_PageDown,
                                        QtCore.Qt.NoModifier)
            QtGui.qApp.sendEvent(arg_0._page_control, arg_7)
            return True

        elif arg_2 == QtCore.Qt.Key_Backspace:
            arg_7 = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
                                        QtCore.Qt.Key_PageUp,
                                        QtCore.Qt.NoModifier)
            QtGui.qApp.sendEvent(arg_0._page_control, arg_7)
            return True

        return False


def Func(arg_0):
        """ Convenience method that returns a cursor for the last character.
        """
        arg_1 = arg_0._control.textCursor()
        arg_1.movePosition(QtGui.QTextCursor.End)
        return arg_1


def Func(arg_0, arg_1, arg_2):
        """ Convenience method that returns a cursor with text selected between
            the positions 'start' and 'end'.
        """
        arg_3 = arg_0._control.textCursor()
        arg_3.setPosition(arg_1)
        arg_3.setPosition(arg_2, QtGui.QTextCursor.KeepAnchor)
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """ Inserts plain text using the specified cursor, processing ANSI codes
            if enabled.
        """
        arg_1.beginEditBlock()
        if arg_0.ansi_codes:
            for arg_3 in arg_0._ansi_processor.split_string(arg_2):
                for arg_4 in arg_0._ansi_processor.actions:

                    # Unlike real terminal emulators, we don't distinguish
                    # between the screen and the scrollback buffer. A screen
                    # erase request clears everything.
                    if arg_4.action == 'erase' and arg_4.area == 'screen':
                        arg_1.select(QtGui.QTextCursor.Document)
                        arg_1.removeSelectedText()

                    # Simulate a form feed by scrolling just past the last line.
                    elif arg_4.action == 'scroll' and arg_4.unit == 'page':
                        arg_1.insertText('\n')
                        arg_1.endEditBlock()
                        arg_0._set_top_cursor(arg_1)
                        arg_1.joinPreviousEditBlock()
                        arg_1.deletePreviousChar()

                    elif arg_4.action == 'carriage-return':
                        arg_1.movePosition(
                            arg_1.StartOfLine, arg_1.KeepAnchor)

                    elif arg_4.action == 'beep':
                        QtGui.qApp.beep()

                    elif arg_4.action == 'backspace':
                        if not arg_1.atBlockStart():
                            arg_1.movePosition(
                                arg_1.PreviousCharacter, arg_1.KeepAnchor)

                    elif arg_4.action == 'newline':
                        arg_1.movePosition(arg_1.EndOfLine)

                arg_5 = arg_0._ansi_processor.get_format()

                arg_6 = arg_1.selectedText()
                if len(arg_6) == 0:
                    arg_1.insertText(arg_3, arg_5)
                elif arg_3 is not None:
                    # BS and CR are treated as a change in print
                    # position, rather than a backwards character
                    # deletion for output equivalence with (I)Python
                    # terminal.
                    if len(arg_3) >= len(arg_6):
                        arg_1.insertText(arg_3, arg_5)
                    else:
                        arg_7 = arg_6[len(arg_3):]
                        arg_1.insertText(arg_3 + arg_7, arg_5)
                        arg_1.movePosition(arg_1.PreviousCharacter,
                               arg_1.KeepAnchor, len(arg_7))
        else:
            arg_1.insertText(arg_2)
        arg_1.endEditBlock()


def Func(arg_0):
        """ Ensures that the cursor is inside the editing region. Returns
            whether the cursor was moved.
        """
        arg_1 = not arg_0._in_buffer()
        if arg_1:
            arg_2 = arg_0._control.textCursor()
            arg_2.movePosition(QtGui.QTextCursor.End)
            arg_0._control.setTextCursor(arg_2)
        return arg_1


def Func(arg_0):
        """ Cancels the current editing task ala Ctrl-G in Emacs.
        """
        if arg_0._temp_buffer_filled :
            arg_0._cancel_completion()
            arg_0._clear_temporary_buffer()
        else:
            arg_0.input_buffer = ''


def Func(arg_0, arg_1, arg_2=False):
        """ Displays text using the pager if it exceeds the height of the
        viewport.

        Parameters:
        -----------
        html : bool, optional (default False)
            If set, the text will be interpreted as HTML instead of plain text.
        """
        arg_3 = QtGui.QFontMetrics(arg_0.font).height()
        arg_4 = arg_0._control.viewport().height() / arg_3
        if arg_0.paging != 'none' and \
                re.match("(?:[^\n]*\n){%i}" % arg_4, arg_1):
            if arg_0.paging == 'custom':
                arg_0.customFunc_requested.emit(arg_1)
            else:
                arg_0.Func_control.clear()
                arg_5 = arg_0.Func_control.textCursor()
                if arg_2:
                    arg_0._insert_html(arg_5, arg_1)
                else:
                    arg_0._insert_plain_text(arg_5, arg_1)
                arg_0.Func_control.moveCursor(QtGui.QTextCursor.Start)

                arg_0.Func_control.viewport().resize(arg_0._control.size())
                if arg_0._splitter:
                    arg_0.Func_control.show()
                    arg_0.Func_control.setFocus()
                else:
                    arg_0.layout().setCurrentWidget(arg_0.Func_control)
        elif arg_2:
            arg_0._append_html(arg_1)
        else:
            arg_0._append_plain_text(arg_1)


def Func(arg_0):
        """ Called immediately after a new prompt is displayed.
        """
        # Temporarily disable the maximum block count to permit undo/redo and
        # to ensure that the prompt position does not change due to truncation.
        arg_0._control.document().setMaximumBlockCount(0)
        arg_0._control.setUndoRedoEnabled(True)

        # Work around bug in QPlainTextEdit: input method is not re-enabled
        # when read-only is disabled.
        arg_0._control.setReadOnly(False)
        arg_0._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)

        if not arg_0._reading:
            arg_0._executing = False
        arg_0.Func_hook()

        # If the input buffer has changed while executing, load it.
        if arg_0._input_buffer_pending:
            arg_0.input_buffer = arg_0._input_buffer_pending
            arg_0._input_buffer_pending = ''

        arg_0._control.moveCursor(QtGui.QTextCursor.End)


def Func(arg_0, arg_1):
        """ Scrolls the viewport so that the specified cursor is at the top.
        """
        arg_2 = arg_0._control.verticalScrollBar()
        arg_2.setValue(arg_2.maximum())
        arg_3 = arg_0._control.textCursor()
        arg_0._control.setTextCursor(arg_1)
        arg_0._control.ensureCursorVisible()
        arg_0._control.setTextCursor(arg_3)


def Func(arg_0):
        """ Expands the vertical scrollbar beyond the range set by Qt.
        """
        # This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
        # and qtextedit.cpp.
        arg_1 = arg_0._control.document()
        arg_2 = arg_0._control.verticalScrollBar()
        arg_3 = arg_0._control.viewport().height()
        if isinstance(arg_0._control, QtGui.QPlainTextEdit):
            arg_4 = max(0, arg_1.lineCount() - 1)
            arg_5 = arg_3 / arg_0._control.fontMetrics().lineSpacing()
        else:
            # QTextEdit does not do line-based layout and blocks will not in
            # general have the same height. Therefore it does not make sense to
            # attempt to scroll in line height increments.
            arg_4 = arg_1.size().height()
            arg_5 = arg_3
        arg_6 = arg_4 - arg_2.maximum()
        arg_2.setRange(0, arg_4)
        arg_2.setPageStep(arg_5)

        # Compensate for undesirable scrolling that occurs automatically due to
        # maximumBlockCount() text truncation.
        if arg_6 < 0 and arg_1.blockCount() == arg_1.maximumBlockCount():
            arg_2.setValue(arg_2.value() + arg_6)


def Func(arg_0, arg_1, arg_2=None, arg_3=False):
        """Copy a default config file into the active profile directory.

        Default configuration files are kept in :mod:`IPython.config.default`.
        This function moves these from that location to the working profile
        directory.
        """
        arg_4 = os.path.join(arg_0.location, arg_1)
        if os.path.isfile(arg_4) and not arg_3:
            return False
        if arg_2 is None:
            arg_2 = os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
        arg_5 = os.path.join(arg_2, arg_1)
        shutil.copy(arg_5, arg_4)
        return True


def Func(arg_0, arg_1, arg_2=u'default', arg_3=None):
        """Create a profile dir by profile name and path.

        Parameters
        ----------
        path : unicode
            The path (directory) to put the profile directory in.
        name : unicode
            The name of the profile.  The name of the profile directory will
            be "profile_<profile>".
        """
        if not os.path.isdir(arg_1):
            raise ProfileDirError('Directory not found: %s' % arg_1)
        arg_4 = os.path.join(arg_1, u'profile_' + arg_2)
        return arg_0(location=arg_4, arg_3=arg_3)


def Func(arg_0):
    'Convert a cmp= function into a key= function'
    class Key(object):
        def __init__(arg_1, arg_2):
            arg_1.obj = arg_2
        def __lt__(arg_1, arg_3):
            return arg_0(arg_1.obj, arg_3.obj) < 0
        def __gt__(arg_1, arg_3):
            return arg_0(arg_1.obj, arg_3.obj) > 0
        def __eq__(arg_1, arg_3):
            return arg_0(arg_1.obj, arg_3.obj) == 0
    return Key


def Func(arg_0):
    """Read a file and close it.  Returns the file source."""
    arg_1 = open(arg_0,'r');
    arg_2 = arg_1.read();
    arg_1.close()
    return arg_2


def Func(arg_0='', arg_1='==> ', arg_2='..> ',arg_3 = '.'):
    """Take multiple lines of input.

    A list with each line of input as a separate element is returned when a
    termination string is entered (defaults to a single '.'). Input can also
    terminate via EOF (^D in Unix, ^Z-RET in Windows).

    Lines of input which end in \\ are joined into single entries (and a
    secondary continuation prompt is issued as long as the user terminates
    lines with \\). This allows entering very long strings which are still
    meant to be treated as single entities.
    """

    try:
        if arg_0:
            arg_0 += '\n'
        arg_4 = [raw_input(arg_0 + arg_1)]
    except EOFError:
        return []
    arg_5 = [arg_3]
    try:
        while arg_4[-1:] != arg_5:
            arg_6 = raw_input(arg_1)
            while arg_6.endswith('\\'):
                arg_6 = arg_6[:-1] + raw_input(arg_2)
            arg_4.append(arg_6)

        return arg_4[:-1]  # don't return the termination command
    except EOFError:
        print()
        return arg_4


def Func(arg_0, arg_1):
        """Write data to both channels."""
        arg_0.file.Func(arg_1)
        arg_0.ostream.Func(arg_1)
        arg_0.ostream.flush()


def Func(arg_0, arg_1):
        """add a new handler for new hearts"""
        arg_0.log.debug("heartbeat::new_heart_handler: %s", arg_1)
        arg_0._new_handlers.add(arg_1)


def Func(arg_0, arg_1):
        """add a new handler for heart failure"""
        arg_0.log.debug("heartbeat::new heart failure handler: %s", arg_1)
        arg_0._failure_handlers.add(arg_1)


def Func(arg_0, arg_1):
        "a heart just beat"
        arg_2 = str_to_bytes(str(arg_0.lifetime))
        arg_3 = str_to_bytes(str(arg_0.last_ping))
        if arg_1[1] == arg_2:
            arg_4 = time.time()-arg_0.tic
            # self.log.debug("heartbeat::heart %r took %.2f ms to respond"%(msg[0], 1000*delta))
            arg_0.responses.add(arg_1[0])
        elif arg_1[1] == arg_3:
            arg_4 = time.time()-arg_0.tic + (arg_0.lifetime-arg_0.last_ping)
            arg_0.log.warn("heartbeat::heart %r missed a beat, and took %.2f ms to respond", arg_1[0], 1000*arg_4)
            arg_0.responses.add(arg_1[0])
        else:
            arg_0.log.warn("heartbeat::got bad heartbeat (possibly old?): %s (current=%.3f)", arg_1[1], arg_0.lifetime)


def Func(arg_0, arg_1, arg_2 = 0, arg_3 = False):
    '''
    Converts a list into a list of lists with equal batch_size.

    Parameters
    ----------
    sequence : list
        list of items to be placed in batches
    batch_size : int
        length of each sub list
    mod : int
        remainder of list length devided by batch_size
        mod = len(sequence) % batch_size
    randomize = bool
        should the initial sequence be randomized before being batched

    '''

    if arg_3:
        arg_0 = random.sample(arg_0, len(arg_0))

    return [arg_0[arg_4:arg_4 + arg_1] for arg_4 in xrange(0, len(arg_0)-arg_2, arg_1)]


def Func(arg_0='.', arg_1=True, arg_2='*'):
    '''
    Generator for walking a directory tree.
    Starts at specified root folder, returning files that match our pattern.
    Optionally will also recurse through sub-folders.

    Parameters
    ----------
    root : string (default is *'.'*)
        Path for the root folder to look in.
    recurse : bool (default is *True*)
        If *True*, will also look in the subfolders.
    pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
        The pattern to look for in the files' name.

    Returns
    -------
    generator
        **Func** yields a generator from the matching files paths.

    '''

    for arg_3, arg_4, arg_5 in os.walk(arg_0):
        for arg_6 in arg_5:
            if fnmatch.fnmatch(arg_6, arg_2):
                yield os.path.join(arg_3, arg_6)
        if not arg_1:
            break


def Func(arg_0):
    """Extract configuration data from a bdist_wininst .exe

    Returns a ConfigParser.RawConfigParser, or None
    """
    arg_1 = open(arg_0,'rb')
    try:
        arg_2 = zipfile._EndRecData(arg_1)
        if arg_2 is None:
            return None

        arg_3 = (arg_2[9] - arg_2[5]) - arg_2[6]
        if arg_3 < 12:  # no wininst data here
            return None
        arg_1.seek(arg_3-12)

        import struct, StringIO, ConfigParser
        arg_4, arg_5, arg_6 = struct.unpack("<iii",arg_1.read(12))
        if arg_4 not in (0x1234567A, 0x1234567B):
            return None     # not a valid tag

        arg_1.seek(arg_3-(12+arg_5))
        arg_7 = ConfigParser.RawConfigParser({'version':'','target_version':''})
        try:
            arg_8 = arg_1.read(arg_5)
            # part is in bytes, but we need to read up to the first null
            #  byte.
            if sys.version_info >= (2,6):
                arg_9 = bytes([0])
            else:
                arg_9 = chr(0)
            arg_10 = arg_8.split(arg_9, 1)[0]
            # Now the config is in bytes, but on Python 3, it must be
            #  unicode for the RawConfigParser, so decode it. Is this the
            #  right encoding?
            arg_10 = arg_10.decode('ascii')
            arg_7.readfp(StringIO.StringIO(arg_10))
        except ConfigParser.Error:
            return None
        if not arg_7.has_section('metadata') or not arg_7.has_section('Setup'):
            return None
        return arg_7

    finally:
        arg_1.close()


def Func(arg_0):
    """Ensure that the importer caches dont have stale info for `path`"""
    from zipimport import _zip_directory_cache as zdc
    _uncache(arg_0, zdc)
    _uncache(arg_0, sys.path_importer_cache)


def Func(arg_0, arg_1):
        """Verify that there are no conflicting "old-style" packages"""

        return arg_1     # XXX temporarily disable until new strategy is stable
        from imp import find_module, get_suffixes
        from glob import glob

        arg_2 = []
        arg_3 = dict.fromkeys(arg_1._get_metadata('top_level.txt')) # XXX private attr

        arg_4 = {'.pyc':1, '.pyo':1}     # get_suffixes() might leave one out
        for arg_5,arg_6,arg_7 in get_suffixes():
            arg_4[arg_5] = 1

        for arg_8,arg_9 in expand_paths([arg_0.install_dir]+arg_0.all_site_dirs):
            for arg_10 in arg_9:
                arg_11,arg_5 = os.path.splitext(arg_10)
                if arg_11 in arg_3:
                    if not arg_5:
                        # no extension, check for package
                        try:
                            arg_12, arg_10, arg_13 = find_module(arg_11, [arg_8])
                        except ImportError:
                            continue
                        else:
                            if arg_12: arg_12.close()
                            if arg_10 not in arg_2:
                                arg_2.append(arg_10)
                    elif arg_5 in arg_4 and arg_11!='site':  # XXX ugh
                        arg_2.append(os.path.join(arg_8,arg_10))
        if arg_2:
            arg_0.found_conflicts(arg_1, arg_2)

        return arg_1


def Func(arg_0, arg_1):
        """
        When easy_install is about to run bdist_egg on a source dist, that
        source dist might have 'setup_requires' directives, requiring
        additional fetching. Ensure the fetcher options given to easy_install
        are available to that command as well.
        """
        # find the fetch options from easy_install and write them out
        #  to the setup.cfg file.
        arg_2 = arg_0.distribution.get_option_dict('easy_install').copy()
        arg_3 = (
            'find_links', 'site_dirs', 'index_url', 'optimize',
            'site_dirs', 'allow_hosts',
        )
        arg_4 = {}
        for arg_5, arg_6 in arg_2.iteritems():
            if arg_5 not in arg_3: continue
            arg_4[arg_5.replace('_', '-')] = arg_6[1]
        # create a settings dictionary suitable for `edit_config`
        arg_8 = dict(easy_install=arg_4)
        arg_9 = os.path.join(arg_1, 'setup.cfg')
        setopt.edit_config(arg_9, arg_8)


def Func(arg_0):
        """Create directories under ~."""
        if not arg_0.user:
            return
        arg_1 = convert_path(os.path.expanduser("~"))
        for arg_2, arg_3 in arg_0.config_vars.iteritems():
            if arg_3.startswith(arg_1) and not os.path.isdir(arg_3):
                arg_0.debug_print("os.makedirs('%s', 0700)" % arg_3)
                os.makedirs(arg_3, 0700)


def Func(arg_0):
    """Return True if `name` is a considered as an archive file."""
    arg_1 = (
        '.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl'
    )
    arg_2 = splitext(arg_0)[1].lower()
    if arg_2 in arg_1:
        return True
    return False


def Func(arg_0):
    '''
    return a Func proxy for the `obj`.

    all modify on the proxy will not apply on origin object.
    '''
    arg_1 = type(arg_0)

    class Proxy(arg_1):
        def __getattribute__(arg_2, arg_3):
            try:
                return super().__getattribute__(arg_3)
            except AttributeError:
                return getattr(arg_0, arg_3)

    update_wrapper(Proxy, arg_1, updated = ())
    return Proxy()


def Func(arg_0, *, arg_1 = False):
    '''
    return a Func proxy for the `obj`.

    all modify on the proxy will not apply on origin object.
    '''
    arg_2 = type(arg_0)

    class ReadonlyProxy(arg_2):
        def __getattribute__(arg_3, arg_4):
            return getattr(arg_0, arg_4)

        def __setattr__(arg_3, arg_4, arg_5):
            if arg_1:
                raise AttributeError('cannot set Func object.')

    update_wrapper(ReadonlyProxy, arg_2, updated = ())
    return ReadonlyProxy()


def Func(arg_0=None, arg_1=None, arg_2=1, arg_3=None):
    """Create a new section cell with a given integer level."""
    arg_4 = NotebookNode()
    arg_4.cell_type = u'heading'
    if arg_0 is not None:
        arg_4.source = unicode(arg_0)
    if arg_1 is not None:
        arg_4.rendered = unicode(arg_1)
    arg_4.level = int(arg_2)
    arg_4.metadata = NotebookNode(arg_3 or {})
    return arg_4


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None,
    arg_4=None, arg_5=None):
    """Create a new metadata node."""
    arg_6 = NotebookNode()
    if arg_0 is not None:
        arg_6.name = unicode(arg_0)
    if arg_1 is not None:
        arg_6.authors = list(arg_1)
    if arg_3 is not None:
        arg_6.created = unicode(arg_3)
    if arg_4 is not None:
        arg_6.modified = unicode(arg_4)
    if arg_2 is not None:
        arg_6.license = unicode(arg_2)
    if arg_5 is not None:
        arg_6.gistid = unicode(arg_5)
    return arg_6


def Func(arg_0=None, arg_1=None, arg_2=None, arg_3=None):
    """Create a new author."""
    arg_4 = NotebookNode()
    if arg_0 is not None:
        arg_4.name = unicode(arg_0)
    if arg_1 is not None:
        arg_4.email = unicode(arg_1)
    if arg_2 is not None:
        arg_4.affiliation = unicode(arg_2)
    if arg_3 is not None:
        arg_4.url = unicode(arg_3)
    return arg_4


def Func(arg_0):
    """Whether `path` is a directory, to which the user has write access."""
    return os.path.isdir(arg_0) and os.access(arg_0, os.W_OK)


def Func(arg_0, arg_1=(arg_2.platform=='win32')):
    """ On Windows, remove leading and trailing quotes from filenames.
    """
    if arg_1:
        if arg_0.startswith(("'", '"')) and arg_0.endswith(("'", '"')):
            arg_0 = arg_0[1:-1]
    return arg_0


def Func(arg_0=False):
    """Return the 'home' directory, as a unicode string.

    * First, check for frozen env in case of py2exe
    * Otherwise, defer to os.path.expanduser('~')

    See stdlib docs for how this is determined.
    $HOME is first priority on *ALL* platforms.

    Parameters
    ----------

    require_writable : bool [default: False]
        if True:
            guarantees the return value is a writable directory, otherwise
            raises HomeDirError
        if False:
            The path is resolved, but it is not guaranteed to exist or be writable.
    """

    # first, check py2exe distribution root directory for _ipython.
    # This overrides all. Normally does not exist.

    if hasattr(sys, "frozen"): #Is frozen by py2exe
        if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
            arg_1, arg_2 = IPython.__file__.lower().split('library.zip')
        else:
            arg_1=arg_3.path.join(arg_3.path.split(IPython.__file__)[0],"../../")
        arg_1=arg_3.path.abspath(arg_1).rstrip('\\')
        if _writable_dir(arg_3.path.join(arg_1, '_ipython')):
            arg_3.environ["IPYKITROOT"] = arg_1
        return py3compat.cast_unicode(arg_1, fs_encoding)

    arg_5 = arg_3.path.expanduser('~')
    # Next line will make things work even when /home/ is a symlink to
    # /usr/home as it is on FreeBSD, for example
    arg_5 = arg_3.path.realpath(arg_5)

    if not _writable_dir(arg_5) and arg_3.name == 'nt':
        # expanduser failed, use the registry to get the 'My Documents' folder.
        try:
            import _winreg as wreg
            arg_6 = wreg.OpenKey(
                wreg.HKEY_CURRENT_USER,
                "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
            )
            arg_5 = wreg.QueryValueEx(arg_6,'Personal')[0]
            arg_6.Close()
        except:
            pass

    if (not arg_0) or _writable_dir(arg_5):
        return py3compat.cast_unicode(arg_5, fs_encoding)
    else:
        raise HomeDirError('%s is not a writable dir, '
                'set $HOME environment variable to override' % arg_5)


def Func():
    """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.

    This is only for non-OS X posix (Linux,Unix,etc.) systems.
    """

    arg_0 = os.environ

    if os.name == 'posix' and sys.platform != 'darwin':
        # Linux, Unix, AIX, etc.
        # use ~/.config if empty OR not set
        arg_1 = arg_0.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
        if arg_1 and _writable_dir(arg_1):
            return py3compat.cast_unicode(arg_1, fs_encoding)

    return None


def Func():
    """Get the IPython directory for this platform and user.

    This uses the logic in `get_home_dir` to find the home directory
    and then adds .ipython to the end of the path.
    """

    arg_0 = os.environ
    arg_1 = os.path.join

    arg_2 = '.ipython'
    arg_3 = 'ipython'

    arg_4 = get_home_dir()
    arg_5 = get_xdg_dir()

    # import pdb; pdb.set_trace()  # dbg
    if 'IPYTHON_DIR' in arg_0:
        warnings.warn('The environment variable IPYTHON_DIR is deprecated. '
                      'Please use IPYTHONDIR instead.')
    arg_6 = arg_0.get('IPYTHONDIR', arg_0.get('IPYTHON_DIR', None))
    if arg_6 is None:
        # not set explicitly, use XDG_CONFIG_HOME or HOME
        arg_7 = arg_1(arg_4, arg_2)
        if arg_5:
            # use XDG, as long as the user isn't already
            # using $HOME/.ipython and *not* XDG/ipython

            arg_8 = arg_1(arg_5, arg_3)

            if _writable_dir(arg_8) or not _writable_dir(arg_7):
                arg_6 = arg_8

        if arg_6 is None:
            # not using XDG
            arg_6 = arg_7

    arg_6 = os.path.normpath(os.path.expanduser(arg_6))

    if os.path.exists(arg_6) and not _writable_dir(arg_6):
        # ipdir exists, but is not writable
        warnings.warn("IPython dir '%s' is not a writable location,"
                        " using a temp directory."%arg_6)
        arg_6 = tempfile.mkdtemp()
    elif not os.path.exists(arg_6):
        arg_9 = arg_6.rsplit(os.path.sep, 1)[0]
        if not _writable_dir(arg_9):
            # ipdir does not exist and parent isn't writable
            warnings.warn("IPython parent '%s' is not a writable location,"
                        " using a temp directory."%arg_9)
            arg_6 = tempfile.mkdtemp()

    return py3compat.cast_unicode(arg_6, fs_encoding)


def Func(arg_0):
    """Find the path to an IPython module in this version of IPython.

    This will always find the version of the module that is in this importable
    IPython package. This will always return the path to the ``.py``
    version of the module.
    """
    if arg_0 == 'IPython':
        return os.path.join(get_ipython_package_dir(), '__init__.py')
    arg_1 = import_item(arg_0)
    arg_2 = arg_1.__file__.replace('.pyc', '.py')
    arg_2 = arg_2.replace('.pyo', '.py')
    return py3compat.cast_unicode(arg_2, fs_encoding)


def Func(arg_0,arg_1):
    """Determine whether a target is out of date.

    Func(target,deps) -> 1/0

    deps: list of filenames which MUST exist.
    target: single filename which may or may not exist.

    If target doesn't exist or is older than any file listed in deps, return
    true, otherwise return false.
    """
    try:
        arg_2 = os.path.getmtime(arg_0)
    except os.error:
        return 1
    for arg_3 in arg_1:
        arg_4 = os.path.getmtime(arg_3)
        if arg_4 > arg_2:
            #print "For target",target,"Dep failed:",dep # dbg
            #print "times (dep,tar):",dep_time,target_time # dbg
            return 1
    return 0


def Func(arg_0):
    """Make an MD5 hash of a file, ignoring any differences in line
    ending characters."""
    with open(arg_0, "rU") as f:
        return md5(py3compat.str_to_bytes(f.read())).hexdigest()


def Func(arg_0=None):
    """Check for old config files, and present a warning if they exist.

    A link to the docs of the new config is included in the message.

    This should mitigate confusion with the transition to the new
    config system in 0.11.
    """
    if arg_0 is None:
        arg_0 = get_ipython_dir()

    arg_1 = ['ipy_user_conf.py', 'ipythonrc', 'ipython_config.py']
    arg_2 = False
    for arg_3 in arg_1:
        arg_4 = os.path.join(arg_0, arg_3)
        if os.path.exists(arg_4):
            if filehash(arg_4) == old_config_md5.get(arg_3, ''):
                os.unlink(arg_4)
            else:
                warnings.warn("Found old IPython config file %r (modified by user)"%arg_4)
                arg_2 = True

    if arg_2:
        warnings.warn("""
  The IPython configuration system has changed as of 0.11, and these files will
  be ignored. See http://ipython.github.com/ipython-doc/dev/config for details
  of the new config system.
  To start configuring IPython, do `ipython profile create`, and edit
  `ipython_config.py` in <ipython_dir>/profile_default.
  If you need to leave the old config files in place for an older version of
  IPython and want to suppress this warning message, set
  `c.InteractiveShellApp.ignore_old_config=True` in the new config.""")


def Func(arg_0, arg_1):
    """
    Updates the suggestions' dictionary for an object upon visiting its page
    """
    if arg_0.user.is_authenticated():
        arg_2 = arg_0.user
        arg_3 = ContentType.objects.get_for_model(type(arg_1))
        try:
            # Check if the user has visited this page before
            ObjectView.objects.get(
                arg_2=arg_2, object_id=arg_1.id, arg_3=arg_3)
        except:
            ObjectView.objects.create(arg_2=arg_2, content_object=arg_1)
        # Get a list of all the objects a user has visited
        arg_4 = ObjectView.objects.filter(arg_2=arg_2)

    else:
        update_dict_for_guests(arg_0, arg_1, arg_3)
        return

    if arg_4:
        for arg_5 in arg_4:
            if arg_3 == arg_5.content_type:
                if not exists_in_dictionary(arg_0, arg_1,
                                            arg_3,
                                            arg_5, True):
                    # Create an entry if it's non existent
                    if arg_1.id != arg_5.object_id:
                        ObjectViewDictionary.objects.create(
                            current_object=arg_1,
                            visited_before_object=arg_5.content_object)
                        if not exists_in_dictionary(arg_0, arg_5,
                                                    arg_5.content_type,
                                                    arg_1, False):
                            ObjectViewDictionary.objects.create(
                                current_object=arg_5.content_object,
                                visited_before_object=arg_1)
    return


def Func(arg_0):
        """ Return this path as a relative path,
        based from the current working directory.
        """
        arg_1 = arg_0.__class__(os.getcwdu())
        return arg_1.Functo(arg_0)


def Func(arg_0, arg_1):
        """ Return a list of path objects that match the pattern.

        pattern - a path relative to this directory, with wildcards.

        For example, path('/users').Func('*/bin/*') returns a list
        of all the files users have in their bin directories.
        """
        arg_2 = arg_0.__class__
        return [arg_2(arg_3) for arg_3 in Func.Func(unicode(arg_0 / arg_1))]


def Func(arg_0, arg_1=None, arg_2='strict', arg_3=True):
        r""" Open this file, read all Func, return them in a list.

        Optional arguments:
            encoding - The Unicode encoding (or character set) of
                the file.  The default is None, meaning the content
                of the file is read as 8-bit characters and returned
                as a list of (non-Unicode) str objects.
            errors - How to handle Unicode errors; see help(str.decode)
                for the options.  Default is 'strict'
            retain - If true, retain newline characters; but all newline
                character combinations ('\r', '\n', '\r\n') are
                translated to '\n'.  If false, newline characters are
                stripped off.  Default is True.

        This uses 'U' mode in Python 2.3 and later.
        """
        if arg_1 is None and arg_3:
            arg_4 = arg_0.open('U')
            try:
                return arg_4.readFunc()
            finally:
                arg_4.close()
        else:
            return arg_0.text(arg_1, arg_2).splitFunc(arg_3)


def Func(arg_0, arg_1=None):
        """Enable event loop integration with PyGTK.

        Parameters
        ----------
        app : ignored
           Ignored, it's only a placeholder to keep the call signature of all
           gui activation methods consistent, which simplifies the logic of
           supporting magics.

        Notes
        -----
        This methods sets the PyOS_InputHook for PyGTK, which allows
        the PyGTK to integrate with terminal based applications like
        IPython.
        """
        import gtk
        try:
            gtk.set_interactive(True)
            arg_0._current_gui = GUI_GTK
        except AttributeError:
            # For older versions of gtk, use our own ctypes version
            from IPython.lib.inputhookgtk import inputhook_gtk
            arg_0.set_inputhook(inputhook_gtk)
            arg_0._current_gui = GUI_GTK


def Func(arg_0):
        """Connect to the database, and create tables if necessary."""
        # use detect_types so that timestamps return datetime objects
        arg_0.db = sqlite3.connect(arg_0.hist_file,
                    detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
        arg_0.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer
                        primary key autoincrement, start timestamp,
                        end timestamp, num_cmds integer, remark text)""")
        arg_0.db.execute("""CREATE TABLE IF NOT EXISTS history
                (session integer, line integer, source text, source_raw text,
                PRIMARY KEY (session, line))""")
        # Output history is optional, but ensure the table's there so it can be
        # enabled later.
        arg_0.db.execute("""CREATE TABLE IF NOT EXISTS output_history
                        (session integer, line integer, output text,
                        PRIMARY KEY (session, line))""")
        arg_0.db.commit()


def Func(arg_0, arg_1, arg_2, arg_3=True, arg_4=False):
        """Prepares and runs an SQL query for the history database.

        Parameters
        ----------
        sql : str
          Any filtering expressions to go after SELECT ... FROM ...
        params : tuple
          Parameters passed to the SQL query (to replace "?")
        raw, output : bool
          See :meth:`get_range`

        Returns
        -------
        Tuples as :meth:`get_range`
        """
        arg_5 = 'source_raw' if arg_3 else 'source'
        arg_6 = "history"
        if arg_4:
            arg_6 = "history LEFT JOIN output_history USING (session, line)"
            arg_5 = "history.%s, output_history.output" % arg_5
        arg_7 = arg_0.db.execute("SELECT session, line, %s FROM %s " %\
                                (arg_5, arg_6) + arg_1, arg_2)
        if arg_4:    # Regroup into 3-tuples, and parse JSON
            return ((arg_8, arg_9, (arg_10, arg_11)) for arg_8, arg_9, arg_10, arg_11 in arg_7)
        return arg_7


def Func(arg_0, arg_1=0):
        """get info about a session

        Parameters
        ----------

        session : int
            Session number to retrieve. The current session is 0, and negative
            numbers count back from current session, so -1 is previous session.

        Returns
        -------

        (session_id [int], start [datetime], end [datetime], num_cmds [int],
        remark [unicode])

        Sessions that are running or did not exit cleanly will have `end=None`
        and `num_cmds=None`.

        """

        if arg_1 <= 0:
            arg_1 += arg_0.session_number

        arg_2 = "SELECT * from sessions where session == ?"
        return arg_0.db.execute(arg_2, (arg_1,)).fetchone()


def Func(arg_0, arg_1, arg_2=True, arg_3=False):
        """Get lines of history from a string of ranges, as used by magic
        commands %hist, %save, %macro, etc.

        Parameters
        ----------
        rangestr : str
          A string specifying ranges, e.g. "5 ~2/1-4". See
          :func:`magic_history` for full details.
        raw, output : bool
          As :meth:`get_range`

        Returns
        -------
        Tuples as :meth:`get_range`
        """
        for arg_4, arg_5, arg_6 in extract_hist_ranges(arg_1):
            for arg_7 in arg_0.get_range(arg_4, arg_5, arg_6, arg_2=arg_2, arg_3=arg_3):
                yield arg_7


def Func(arg_0, arg_1):
        """Give the current session a name in the history database."""
        with arg_0.db:
            arg_0.db.execute("UPDATE sessions SET remark=? WHERE session==?",
                            (arg_1, arg_0.session_number))


def Func(arg_0, arg_1=True):
        """Clear the session history, releasing all object references, and
        optionally open a new session."""
        arg_0.output_hist.clear()
        # The directory history can't be completely empty
        arg_0.dir_hist[:] = [os.getcwdu()]

        if arg_1:
            if arg_0.session_number:
                arg_0.end_session()
            arg_0.input_hist_parsed[:] = [""]
            arg_0.input_hist_raw[:] = [""]
            arg_0.new_session()


def Func(arg_0, arg_1=None):
        """Write any entries in the cache to the database."""
        if arg_1 is None:
            arg_1 = arg_0.db

        with arg_0.db_input_cache_lock:
            try:
                arg_0._writeout_input_cache(arg_1)
            except sqlite3.IntegrityError:
                arg_0.new_session(arg_1)
                print("ERROR! Session/line number was not unique in",
                      "database. History logging moved to new session",
                                                arg_0.session_number)
                try:
                    # Try writing to the new session. If this fails, don't
                    # recurse
                    arg_0._writeout_input_cache(arg_1)
                except sqlite3.IntegrityError:
                    pass
            finally:
                arg_0.db_input_cache = []

        with arg_0.db_output_cache_lock:
            try:
                arg_0._writeout_output_cache(arg_1)
            except sqlite3.IntegrityError:
                print("!! Session/line number for output was not unique",
                      "in database. Output will not be stored.")
            finally:
                arg_0.db_output_cache = []


def Func(arg_0):
        """This can be called from the main thread to safely Func this thread.

        Note that it does not attempt to write out remaining history before
        exiting. That should be done by calling the HistoryManager's
        end_session method."""
        arg_0.Func_now = True
        arg_0.history_manager.save_flag.set()
        arg_0.join()


def Func():
    """Return the number of CPUs on the system"""
    # we try to determine num CPUs by using different approaches.
    # SC_NPROCESSORS_ONLN seems to be the safer and it is also
    # used by multiprocessing module
    try:
        return os.sysconf("SC_NPROCESSORS_ONLN")
    except ValueError:
        # as a second fallback we try to parse /proc/cpuinfo
        arg_0 = 0
        arg_1 = open('/proc/cpuinfo', 'r')
        try:
            arg_2 = arg_1.readlines()
        finally:
            arg_1.close()
        for arg_3 in arg_2:
            if arg_3.lower().startswith('processor'):
                arg_0 += 1

    # unknown format (e.g. amrel/sparc architectures), see:
    # http://code.google.com/p/psutil/issues/detail?id=200
    # try to parse /proc/stat as a last resort
    if arg_0 == 0:
        arg_1 = open('/proc/stat', 'r')
        try:
            arg_2 = arg_1.readlines()
        finally:
            arg_1.close()
        arg_4 = re.compile('cpu\d')
        for arg_3 in arg_2:
            arg_3 = arg_3.split(' ')[0]
            if arg_4.match(arg_3):
                arg_0 += 1

    if arg_0 == 0:
        raise RuntimeError("can't determine number of CPUs")
    return arg_0


def Func():
    """Return a list of namedtuple representing the CPU times
    for every CPU available on the system.
    """
    arg_0 = []
    arg_1 = open('/proc/stat', 'r')
    # get rid of the first line who refers to system wide CPU stats
    try:
        arg_1.readline()
        for arg_2 in arg_1.readlines():
            if arg_2.startswith('cpu'):
                arg_3 = arg_2.split()[1:8]
                arg_3 = tuple([float(x) / _CLOCK_TICKS for x in arg_3])
                arg_4 = nt_sys_cputimes(*arg_3[:7])
                arg_0.append(arg_4)
        return arg_0
    finally:
        arg_1.close()


def Func(arg_0=False):
    """Return mounted disk partitions as a list of nameduples"""
    arg_1 = []
    arg_2 = open("/proc/filesystems", "r")
    try:
        for arg_3 in arg_2:
            if not arg_3.startswith("nodev"):
                arg_1.append(arg_3.strip())
    finally:
        arg_2.close()

    arg_4 = []
    arg_5 = _psutil_linux.get_Func()
    for arg_6 in arg_5:
        arg_7, arg_8, arg_9, arg_10 = arg_6
        if arg_7 == 'none':
            arg_7 = ''
        if not arg_0:
            if arg_7 == '' or arg_9 not in arg_1:
                continue
        arg_11 = nt_partition(arg_7, arg_8, arg_9, arg_10)
        arg_4.append(arg_11)
    return arg_4


def Func(arg_0):
    """Make a nice string representation of a pair of numbers.

    If the numbers are equal, just return the number, otherwise return the pair
    with a dash between them, indicating the range.

    """
    arg_1, arg_2 = arg_0
    if arg_1 == arg_2:
        return "%d" % arg_1
    else:
        return "%d-%d" % (arg_1, arg_2)


def Func():
    """Return a string summarizing the call stack."""
    arg_0 = inspect.stack()[:0:-1]
    return "\n".join(["%30s : %s @%d" % (arg_1[3],arg_1[1],arg_1[2]) for arg_1 in arg_0])


def Func(arg_0):
    """A decorator to cache the result of an Func operation.

    Only applies to methods with no arguments.

    """
    arg_1 = "_cache_" + arg_0.__name__
    def _wrapped(arg_2):
        """Inner fn that checks the cache."""
        if not hasattr(arg_2, arg_1):
            setattr(arg_2, arg_1, arg_0(arg_2))
        return getattr(arg_2, arg_1)
    return _wrapped


def Func(arg_0):
    """Combine a list of regexes into one that matches any of them."""
    if len(arg_0) > 1:
        return "|".join(["(%s)" % arg_1 for arg_1 in arg_0])
    elif arg_0:
        return arg_0[0]
    else:
        return ""


def Func(arg_0):
    """Remove a file, and don't get annoyed if it doesn't exist."""
    try:
        os.remove(arg_0)
    except OSError:
        arg_1, arg_2, arg_1 = sys.exc_info()
        if arg_2.errno != errno.ENOENT:
            raise


def Func(arg_0):
        """List all profiles in the ipython_dir and cwd.
        """
        for arg_1 in [get_ipython_dir(), os.getcwdu()]:
            for arg_2 in list_profiles_in(arg_1):
                arg_3 = arg_0.get_profile_dir(arg_2, arg_1)
                if arg_2 not in arg_0.profiles:
                    arg_0.log.debug("Adding cluster profile '%s'" % arg_2)
                    arg_0.profiles[arg_2] = {
                        'profile': arg_2,
                        'profile_dir': arg_3,
                        'status': 'stopped'
                    }


def Func(arg_0, arg_1, arg_2=None):
        """Start a cluster for a given profile."""
        arg_0.check_profile(arg_1)
        arg_3 = arg_0.profiles[arg_1]
        if arg_3['status'] == 'running':
            raise web.HTTPError(409, u'cluster already running')
        arg_4, arg_5, arg_6 = arg_0.build_launchers(arg_3['profile_dir'])
        arg_2 = arg_2 if arg_2 is not None else arg_6
        def clean_data():
            arg_3.pop('controller_launcher',None)
            arg_3.pop('engine_set_launcher',None)
            arg_3.pop('n',None)
            arg_3['status'] = 'stopped'
        def engines_stopped(arg_7):
            arg_0.log.debug('Engines stopped')
            if arg_4.running:
                arg_4.stop()
            clean_data()
        arg_5.on_stop(engines_stopped)
        def controller_stopped(arg_7):
            arg_0.log.debug('Controller stopped')
            if arg_5.running:
                arg_5.stop()
            clean_data()
        arg_4.on_stop(controller_stopped)

        arg_8 = ioloop.DelayedCallback(lambda: arg_4.start(), 0, arg_0.loop)
        arg_8.start()
        arg_8 = ioloop.DelayedCallback(lambda: arg_5.start(arg_2), 1000*arg_0.delay, arg_0.loop)
        arg_8.start()

        arg_0.log.debug('Cluster started')
        arg_3['controller_launcher'] = arg_4
        arg_3['engine_set_launcher'] = arg_5
        arg_3['n'] = arg_2
        arg_3['status'] = 'running'
        return arg_0.profile_info(arg_1)


def Func(arg_0, arg_1):
        """Stop a cluster for a given profile."""
        arg_0.check_profile(arg_1)
        arg_2 = arg_0.profiles[arg_1]
        if arg_2['status'] == 'stopped':
            raise web.HTTPError(409, u'cluster not running')
        arg_2 = arg_0.profiles[arg_1]
        arg_3 = arg_2['controller_launcher']
        arg_4 = arg_2['engine_set_launcher']
        if arg_3.running:
            arg_3.stop()
        if arg_4.running:
            arg_4.stop()
        # Return a temp info dict, the real one is updated in the on_stop
        # logic above.
        arg_5 = {
            'profile': arg_2['profile'],
            'profile_dir': arg_2['profile_dir'],
            'status': 'stopped'
        }
        return arg_5


def Func(arg_0):
    """Find the full path to a .bat or .exe using the win32api module."""
    try:
        from win32api import SearchPath
    except ImportError:
        raise ImportError('you need to have pywin32 installed for this to work')
    else:
        arg_1 = os.environ['PATH']
        arg_2 = ['.exe', '.com', '.bat', '.py']
        arg_3 = None
        for arg_4 in arg_2:
            try:
                arg_3 = SearchPath(arg_1, arg_0 + arg_4)[0]
            except:
                pass
        if arg_3 is None:
            raise OSError("command %r not found" % arg_0)
        else:
            return arg_3


def Func(arg_0):
    """Callback for _system."""
    arg_1 = DEFAULT_ENCODING
    for arg_2 in read_no_interrupt(arg_0.stdout).splitlines():
        arg_2 = arg_2.decode(arg_1, 'replace')
        print(arg_2, file=sys.stdout)
    for arg_2 in read_no_interrupt(arg_0.stderr).splitlines():
        arg_2 = arg_2.decode(arg_1, 'replace')
        print(arg_2, file=sys.stderr)

    # Wait to finish for returncode
    return arg_0.wait()


def Func(arg_0, arg_1, **arg_2):
        '''
        Func records from collection whose parameters match kwargs
        '''
        arg_3 = arg_2.pop('callback')
        yield Op(arg_0.db[arg_1].Func, arg_2)
        arg_3()


def Func(arg_0):
        """
        Resolve the URL to this point.

        >>> trello = TrelloAPIV1('APIKEY')
        >>> trello.batch.Func
        '1/batch'
        >>> trello.boards(board_id='BOARD_ID').Func
        '1/boards/BOARD_ID'
        >>> trello.boards(board_id='BOARD_ID')(field='FIELD').Func
        '1/boards/BOARD_ID/FIELD'
        >>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER').Func
        '1/boards/BOARD_ID/cards/FILTER'

        """
        if arg_0._api_arg:
            arg_1 = str(arg_0._api_arg)
        else:
            arg_1 = arg_0._name

        if arg_0._parent:
            return '/'.join(filter(None, [arg_0._parent.Func, arg_1]))
        else:
            return arg_1


def Func(arg_0, arg_1, *arg_2, **arg_3):
        """
        Makes the HTTP request.

        """
        arg_4 = arg_3.setdefault('params', {})
        arg_4.update({'key': arg_0._apikey})
        if arg_0._token is not None:
            arg_4.update({'token': arg_0._token})

        arg_5 = getattr(requests, arg_1)
        return arg_5(TRELLO_URL + arg_0._url, *arg_2, **arg_3)


def Func(arg_0, arg_1, arg_2, arg_3=None):
        """Run a reporting function on a number of morfs.

        `report_fn` is called for each relative morf in `morfs`.  It is called
        as::

            report_fn(code_unit, analysis)

        where `code_unit` is the `CodeUnit` for the morf, and `analysis` is
        the `Analysis` for the morf.

        """
        arg_0.find_code_units(arg_2)

        if not arg_0.code_units:
            raise CoverageException("No data to report.")

        arg_0.directory = arg_3
        if arg_0.directory and not os.path.exists(arg_0.directory):
            os.makedirs(arg_0.directory)

        for arg_4 in arg_0.code_units:
            try:
                arg_1(arg_4, arg_0.coverage._analyze(arg_4))
            except NoSource:
                if not arg_0.config.ignore_errors:
                    raise
            except NotPython:
                # Only report errors for .py files, and only if we didn't
                # explicitly suppress those errors.
                if arg_4.should_be_python() and not arg_0.config.ignore_errors:
                    raise


def Func():
    """Call pdb.Func in the calling frame, first restoring
    sys.stdout to the real output stream. Note that sys.stdout is NOT
    reset to whatever it was before the call once pdb is done!
    """
    import pdb
    import arg_1
    arg_0 = arg_1.stdout
    arg_1.stdout = arg_1.__stdout__
    pdb.Pdb().Func(arg_1._getframe().f_back)


def Func(arg_0):
    """Test must finish within specified time limit to pass.

    Example use::

      @Func(.1)
      def test_that_fails():
          time.sleep(.2)
    """
    def decorate(arg_1):
        def arg_6(*arg_2, **arg_3):
            arg_4 = time.time()
            arg_1(*arg_2, **arg_3)
            arg_5 = time.time()
            if arg_5 - arg_4 > arg_0:
                raise TimeExpired("Time limit (%s) exceeded" % arg_0)
        arg_6 = make_decorator(arg_1)(arg_6)
        return arg_6
    return decorate


def Func(arg_0):
        """Load all IPython extensions in IPythonApp.extensions.

        This uses the :meth:`ExtensionManager.load_extensions` to load all
        the extensions listed in ``self.extensions``.
        """
        try:
            arg_0.log.debug("Loading IPython extensions...")
            arg_1 = arg_0.default_extensions + arg_0.extensions
            for arg_2 in arg_1:
                try:
                    arg_0.log.info("Loading IPython extension: %s" % arg_2)
                    arg_0.shell.extension_manager.load_extension(arg_2)
                except:
                    arg_0.log.warn("Error in loading extension: %s" % arg_2 +
                        "\nCheck your config files in %s" % arg_0.profile_dir.location
                    )
                    arg_0.shell.showtraceback()
        except:
            arg_0.log.warn("Unknown error in loading extensions:")
            arg_0.shell.showtraceback()


def Func(arg_0):
        """run the pre-flight code, specified via exec_lines"""
        arg_0._run_startup_files()
        arg_0._run_exec_lines()
        arg_0._run_exec_files()
        arg_0._run_cmd_line_code()
        arg_0._run_module()

        # flush output, so itwon't be attached to the first cell
        sys.stdout.flush()
        sys.stderr.flush()

        # Hide variables defined here from %who etc.
        arg_0.shell.user_ns_hidden.update(arg_0.shell.user_ns)


def Func(arg_0):
        """Run files from profile startup directory"""
        arg_1 = arg_0.profile_dir.startup_dir
        arg_2 = glob.glob(os.path.join(arg_1, '*.py'))
        arg_2 += glob.glob(os.path.join(arg_1, '*.ipy'))
        if not arg_2:
            return

        arg_0.log.debug("Running startup files from %s...", arg_1)
        try:
            for arg_3 in sorted(arg_2):
                arg_0._exec_file(arg_3)
        except:
            arg_0.log.warn("Unknown error in handling startup files:")
            arg_0.shell.showtraceback()


def Func(arg_0):
        """Run files from IPythonApp.exec_files"""
        if not arg_0.exec_files:
            return

        arg_0.log.debug("Running files in IPythonApp.exec_files...")
        try:
            for arg_1 in arg_0.exec_files:
                arg_0._exec_file(arg_1)
        except:
            arg_0.log.warn("Unknown error in handling IPythonApp.exec_files:")
            arg_0.shell.showtraceback()


def Func(arg_0):
        """Run code or file specified at the command-line"""
        if arg_0.code_to_run:
            arg_1 = arg_0.code_to_run
            try:
                arg_0.log.info("Running code given at command line (c=): %s" %
                              arg_1)
                arg_0.shell.run_cell(arg_1, store_history=False)
            except:
                arg_0.log.warn("Error in executing line in user namespace: %s" %
                              arg_1)
                arg_0.shell.showtraceback()

        # Like Python itself, ignore the second if the first of these is present
        elif arg_0.file_to_run:
            arg_2 = arg_0.file_to_run
            try:
                arg_0._exec_file(arg_2)
            except:
                arg_0.log.warn("Error in executing file in user namespace: %s" %
                              arg_2)
                arg_0.shell.showtraceback()


def Func(arg_0):
        """Run module specified at the command-line."""
        if arg_0.module_to_run:
            # Make sure that the module gets a proper sys.argv as if it were
            # run using `python -m`.
            arg_1 = arg_2.argv
            arg_2.argv = [arg_2.executable] + arg_0.extra_args
            try:
                arg_0.shell.safeFunc(arg_0.module_to_run,
                                           arg_0.shell.user_ns)
            finally:
                arg_2.argv = arg_1


def Func(arg_0):
    """Return the contents of a Func file of ours."""
    arg_1 = open(Func_filename(arg_0))
    try:
        return arg_1.read()
    finally:
        arg_1.close()


def Func(arg_0):
    """HTML-Func the text in `t`."""
    return (arg_0
            # Convert HTML special chars into HTML entities.
            .replace("&", "&").replace("<", "<").replace(">", ">")
            .replace("'", "'").replace('"', """)
            # Convert runs of spaces: "......" -> " . . ."
            .replace("  ", "  ")
            # To deal with odd-length runs, convert the final pair of spaces
            # so that "....." -> " .  ."
            .replace("  ", "  ")
        )


def Func(arg_0, arg_1):
        """Generate an HTML Func for `morfs`.

        `morfs` is a list of modules or filenames.

        """
        assert arg_0.config.html_dir, "must give a directory for html Funcing"

        # Read the status data.
        arg_0.status.read(arg_0.config.html_dir)

        # Check that this run used the same settings as the last run.
        arg_2 = Hasher()
        arg_2.update(arg_0.config)
        arg_3 = arg_2.digest()
        if arg_0.status.settings_hash() != arg_3:
            arg_0.status.reset()
            arg_0.status.set_settings_hash(arg_3)

        # The user may have extra CSS they want copied.
        if arg_0.config.extra_css:
            arg_0.extra_css = os.path.basename(arg_0.config.extra_css)

        # Process all the files.
        arg_0.Func_files(arg_0.html_file, arg_1, arg_0.config.html_dir)

        if not arg_0.files:
            raise CoverageException("No data to Func.")

        # Write the index file.
        arg_0.index_file()

        arg_0.make_local_static_Func_files()

        return arg_0.totals.pc_covered


def Func(arg_0):
        """Make local instances of static files for HTML report."""
        # The files we provide must always be copied.
        for arg_1, arg_2 in arg_0.STATIC_FILES:
            shutil.copyfile(
                data_filename(arg_1, arg_2),
                os.path.join(arg_0.directory, arg_1)
                )

        # The user may have extra CSS they want copied.
        if arg_0.extra_css:
            shutil.copyfile(
                arg_0.config.extra_css,
                os.path.join(arg_0.directory, arg_0.extra_css)
                )


def Func(arg_0, arg_1, arg_2):
        """Compute a hash that changes if the file needs to be re-reported."""
        arg_3 = Hasher()
        arg_3.update(arg_1)
        arg_0.coverage.data.add_to_hash(arg_2.filename, arg_3)
        return arg_3.digest()


def Func(arg_0, arg_1):
        """Read the last status in `directory`."""
        arg_2 = False
        try:
            arg_3 = os.path.join(arg_1, arg_0.STATUS_FILE)
            arg_4 = open(arg_3, "rb")
            try:
                arg_5 = pickle.load(arg_4)
            finally:
                arg_4.close()
        except (IOError, ValueError):
            arg_2 = False
        else:
            arg_2 = True
            if arg_5['format'] != arg_0.STATUS_FORMAT:
                arg_2 = False
            elif arg_5['version'] != coverage.__version__:
                arg_2 = False

        if arg_2:
            arg_0.files = arg_5['files']
            arg_0.settings = arg_5['settings']
        else:
            arg_0.reset()


def Func(arg_0, arg_1):
        """Write the current status to `directory`."""
        arg_2 = os.path.join(arg_1, arg_0.STATUS_FILE)
        arg_3 = {
            'format': arg_0.STATUS_FORMAT,
            'version': coverage.__version__,
            'settings': arg_0.settings,
            'files': arg_0.files,
            }
        arg_4 = open(arg_2, "wb")
        try:
            pickle.dump(arg_3, arg_4)
        finally:
            arg_4.close()


def Func(arg_0, arg_1, arg_2=1):
    """Sort and compare two lists.

    By default it does it in place, thus modifying the lists. Use inplace = 0
    to avoid that (at the cost of temporary copy creation)."""
    if not arg_2:
        arg_0 = arg_0[:]
        arg_1 = arg_1[:]
    arg_0.sort(); arg_1.sort()
    return arg_0 == arg_1


def Func(arg_0, arg_1=0, arg_2=None, arg_3=1):
    """Get a slice of a sequence with variable step. Specify start,stop,step."""
    if arg_2 == None:
        arg_2 = len(arg_0)
    arg_4 = lambda i: arg_0[i]
    return map(arg_4,xrange(arg_1,arg_2,arg_3))


def Func():
    """Read configuration from setup.cfg."""
    # XXX modifies global state, which is kind of evil
    arg_0 = ConfigParser.ConfigParser()
    arg_0.read(['setup.cfg'])
    if not arg_0.has_section('check-manifest'):
        return
    if (arg_0.has_option('check-manifest', 'ignore-default-rules')
            and arg_0.getboolean('check-manifest', 'ignore-default-rules')):
        del IGNORE[:]
    if arg_0.has_option('check-manifest', 'ignore'):
        arg_1 = [arg_2.strip() for arg_2 in arg_0.get('check-manifest',
                                                  'ignore').splitlines()]
        IGNORE.extend(arg_2 for arg_2 in arg_1 if arg_2)


def Func():
    """Read existing configuration from MANIFEST.in.

    We use that to ignore anything the MANIFEST.in ignores.
    """
    # XXX modifies global state, which is kind of evil
    if not os.path.isfile('MANIFEST.in'):
        return
    with open('MANIFEST.in') as manifest:
        arg_0 = manifest.read()
    arg_1, arg_2 = _get_ignore_from_manifest(arg_0)
    IGNORE.extend(arg_1)
    IGNORE_REGEXPS.extend(arg_2)


def Func():
        """List all files versioned by git in the current directory."""
        # Git for Windows uses UTF-8 instead of the locale encoding.
        # Regular Git on sane POSIX systems uses the locale encoding
        arg_0 = 'UTF-8' if sys.platform == 'win32' else None
        arg_1 = run(['git', 'ls-files', '-z'], arg_0=arg_0)
        return add_directories(arg_1.split('\0')[:-1])


def Func(arg_0):
  """Skips over a field value.

  Args:
    tokenizer: A tokenizer to parse the field name and values.

  Raises:
    ParseError: In case an invalid field value is found.
  """
  # String/bytes tokens can come in multiple adjacent string literals.
  # If we can consume one, consume as many as we can.
  if arg_0.TryConsumeByteString():
    while arg_0.TryConsumeByteString():
      pass
    return

  if (not arg_0.TryConsumeIdentifier() and
      not arg_0.TryConsumeInt64() and
      not arg_0.TryConsumeUint64() and
      not arg_0.TryConsumeFloat()):
    raise ParseError('Invalid field value: ' + arg_0.token)


def Func(arg_0, arg_1=False, arg_2=False):
  """Parses an integer.

  Args:
    text: The text to parse.
    is_signed: True if a signed integer must be parsed.
    is_long: True if a long integer must be parsed.

  Returns:
    The integer value.

  Raises:
    ValueError: Thrown Iff the text is not a valid integer.
  """
  # Do the actual parsing. Exception handling is propagated to caller.
  try:
    # We force 32-bit values to int and 64-bit values to long to make
    # alternate implementations where the distinction is more significant
    # (e.g. the C++ implementation) simpler.
    if arg_2:
      arg_3 = long(arg_0, 0)
    else:
      arg_3 = int(arg_0, 0)
  except ValueError:
    raise ValueError('Couldn\'t parse integer: %s' % arg_0)

  # Check if the integer is sane. Exceptions handled by callers.
  arg_4 = _INTEGER_CHECKERS[2 * int(arg_2) + int(arg_1)]
  arg_4.CheckValue(arg_3)
  return arg_3


def Func(arg_0, arg_1):
    """Convert protobuf message to text format.

    Args:
      message: The protocol buffers message.
    """
    arg_2 = arg_1.ListFields()
    if arg_0.use_index_order:
      arg_2.sort(arg_5=lambda x: x[0].index)
    for arg_3, arg_4 in arg_2:
      if _IsMapEntry(arg_3):
        for arg_5 in sorted(arg_4):
          # This is slow for maps with submessage entires because it copies the
          # entire tree.  Unfortunately this would take significant refactoring
          # of this file to work around.
          #
          # TODO(haberman): refactor and optimize if this becomes an issue.
          arg_6 = arg_3.message_type._concrete_class(
              arg_5=arg_5, arg_4=arg_4[arg_5])
          arg_0.PrintField(arg_3, arg_6)
      elif arg_3.label == descriptor.FieldDescriptor.LABEL_REPEATED:
        for arg_7 in arg_4:
          arg_0.PrintField(arg_3, arg_7)
      else:
        arg_0.PrintField(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Merges a single scalar field into a message.

    Args:
      tokenizer: A tokenizer to parse the field value.
      message: The message of which field is a member.
      field: The descriptor of the field to be merged.

    Raises:
      ParseError: In case of text parsing problems.
    """
    arg_4 = _IsMapEntry(arg_3)

    if arg_1.TryConsume('<'):
      arg_5 = '>'
    else:
      arg_1.Consume('{')
      arg_5 = '}'

    if arg_3.label == descriptor.FieldDescriptor.LABEL_REPEATED:
      if arg_3.is_extension:
        arg_6 = arg_2.Extensions[arg_3].add()
      elif arg_4:
        # pylint: disable=protected-access
        arg_6 = arg_3.message_type._concrete_class()
      else:
        arg_6 = arg_9(arg_2, arg_3.name).add()
    else:
      if arg_3.is_extension:
        arg_6 = arg_2.Extensions[arg_3]
      else:
        arg_6 = arg_9(arg_2, arg_3.name)
      arg_6.SetInParent()

    while not arg_1.TryConsume(arg_5):
      if arg_1.AtEnd():
        raise arg_1.ParseErrorPreviousToken('Expected "%s".' % (arg_5,))
      arg_0._MergeField(arg_1, arg_6)

    if arg_4:
      arg_7 = arg_3.message_type.fields_by_name['value'].cpp_type
      if arg_7 == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
        arg_8 = arg_9(arg_2, arg_3.name)[arg_6.key]
        arg_8.MergeFrom(arg_6.value)
      else:
        arg_9(arg_2, arg_3.name)[arg_6.key] = arg_6.value


def Func(arg_0):
    """Consume one token of a string literal.

    String literals (whether bytes or text) can come in multiple adjacent
    tokens which are automatically concatenated, like in C or Python.  This
    method only consumes one token.

    Returns:
      The token parsed.
    Raises:
      ParseError: When the wrong format data is found.
    """
    arg_1 = arg_0.token
    if len(arg_1) < 1 or arg_1[0] not in _QUOTES:
      raise arg_0._ParseError('Expected string but found: %r' % (arg_1,))

    if len(arg_1) < 2 or arg_1[-1] != arg_1[0]:
      raise arg_0._ParseError('String missing ending quote: %r' % (arg_1,))

    try:
      arg_2 = text_encoding.CUnescape(arg_1[1:-1])
    except ValueError as e:
      raise arg_0._ParseError(str(e))
    arg_0.NextToken()
    return arg_2


def Func(arg_0, arg_1):
        """Shutdown a kernel by its kernel uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to shutdown.
        """
        arg_0.get_kernel(arg_1).Func()
        del arg_0._kernels[arg_1]


def Func(arg_0, arg_1):
        """Kill a kernel by its kernel uuid.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel to kill.
        """
        arg_0.get_kernel(arg_1).Func()
        del arg_0._kernels[arg_1]


def Func(arg_0, arg_1):
        """Return a dictionary of ports for a kernel.

        Parameters
        ==========
        kernel_id : uuid
            The id of the kernel.

        Returns
        =======
        port_dict : dict
            A dict of key, value pairs where the keys are the names
            (stdin_port,iopub_port,shell_port) and the values are the
            integer port numbers for those channels.
        """
        # this will raise a KeyError if not found:
        arg_2 = arg_0.get_kernel(arg_1)
        return dict(shell_port=arg_2.shell_port,
                    iopub_port=arg_2.iopub_port,
                    stdin_port=arg_2.stdin_port,
                    hb_port=arg_2.hb_port,
        )


def Func(arg_0, arg_1=None, **arg_2):
        """Start a kernel for a notebok an return its kernel_id.

        Parameters
        ----------
        notebook_id : uuid
            The uuid of the notebook to associate the new kernel with. If this
            is not None, this kernel will be persistent whenever the notebook
            requests a kernel.
        """
        arg_3 = arg_0.kernel_for_notebook(arg_1)
        if arg_3 is None:
            arg_2['extra_arguments'] = arg_0.kernel_argv
            arg_3 = super(MappingKernelManager, arg_0).Func(**arg_2)
            arg_0.set_kernel_for_notebook(arg_1, arg_3)
            arg_0.log.info("Kernel started: %s" % arg_3)
            arg_0.log.debug("Kernel args: %r" % arg_2)
        else:
            arg_0.log.info("Using existing kernel: %s" % arg_3)
        return arg_3


def Func(arg_0, arg_1):
        """Shutdown a kernel and remove its notebook association."""
        arg_0._check_kernel_id(arg_1)
        super(MappingKernelManager, arg_0).Func(arg_1)
        arg_0.delete_mapping_for_kernel(arg_1)
        arg_0.log.info("Kernel shutdown: %s" % arg_1)


def Func(arg_0, arg_1):
        """Interrupt a kernel."""
        arg_0._check_kernel_id(arg_1)
        super(MappingKernelManager, arg_0).Func(arg_1)
        arg_0.log.info("Kernel interrupted: %s" % arg_1)


def Func(arg_0, arg_1):
        """Create a new iopub stream."""
        arg_0._check_kernel_id(arg_1)
        return super(MappingKernelManager, arg_0).Func(arg_1)


def Func(arg_0, arg_1):
        """Create a new hb stream."""
        arg_0._check_kernel_id(arg_1)
        return super(MappingKernelManager, arg_0).Func(arg_1)


def Func(arg_0):
    """ convert ark timestamp to unix timestamp"""
    arg_1 = datetime.datetime(2017, 3, 21, 15, 55, 44) + datetime.timedelta(seconds=arg_0)
    return arg_1.timestamp()


def Func(arg_0):
      """Reset all OneTimeProperty attributes that may have fired already."""
      arg_1 = arg_0.__dict__
      arg_2 = arg_0.__class__.__dict__
      # To Func them, we simply remove them from the instance dict.  At that
      # point, it's as if they had never been computed.  On the next access,
      # the accessor function from the parent class will be called, simply
      # because that's how the python descriptor protocol works.
      for arg_3, arg_4 in arg_2.items():
         if arg_3 in arg_1 and isinstance(arg_4, OneTimeProperty):
            delattr(arg_0, arg_3)


def Func(arg_0, arg_1, arg_2 = None, arg_3 = True):
    """ Export the contents of the ConsoleWidget as HTML.

    Parameters:
    -----------
    html : str,
        A utf-8 encoded Python string containing the Qt HTML to export.

    filename : str
        The file to be saved.

    image_tag : callable, optional (default None)
        Used to convert images. See ``default_image_tag()`` for information.

    inline : bool, optional [default True]
        If True, include images as inline PNGs.  Otherwise, include them as
        links to external PNG files, mimicking web browsers' "Web Page,
        Complete" behavior.
    """
    if arg_2 is None:
        arg_2 = default_image_tag
    else:
        arg_2 = ensure_utf8(arg_2)

    if arg_3:
        arg_4 = None
    else:
        arg_5,arg_6 = os.path.splitext(arg_1)
        arg_4 = arg_5 + "_files"
        if os.path.isfile(arg_4):
            raise OSError("%s exists, but is not a directory." % arg_4)

    with open(arg_1, 'w') as f:
        arg_0 = fix_html(arg_0)
        f.write(IMG_RE.sub(lambda x: arg_2(x, arg_4 = arg_4, format = "png"),
                           arg_0))


def Func(arg_0, arg_1, arg_2=None):
    """ Export the contents of the ConsoleWidget as XHTML with inline SVGs.

    Parameters:
    -----------
    html : str,
        A utf-8 encoded Python string containing the Qt HTML to export.

    filename : str
        The file to be saved.

    image_tag : callable, optional (default None)
        Used to convert images. See ``default_image_tag()`` for information.
    """
    if arg_2 is None:
        arg_2 = default_image_tag
    else:
        arg_2 = ensure_utf8(arg_2)

    with open(arg_1, 'w') as f:
        # Hack to make xhtml header -- note that we are not doing any check for
        # valid XML.
        arg_3 = arg_0.find("<html>")
        assert arg_3 > -1, 'Invalid HTML string: no <html> tag.'
        arg_0 = ('<html xmlns="http://www.w3.org/1999/xhtml">\n'+
                arg_0[arg_3+6:])

        arg_0 = fix_html(arg_0)
        f.write(IMG_RE.sub(lambda x: arg_2(x, path = None, format = "svg"),
                           arg_0))


def Func(arg_0):
    """ Transforms a Qt-generated HTML string into a standards-compliant one.

    Parameters:
    -----------
    html : str,
        A utf-8 encoded Python string containing the Qt HTML.
    """
    # A UTF-8 declaration is needed for proper rendering of some characters
    # (e.g., indented commands) when viewing exported HTML on a local system
    # (i.e., without seeing an encoding declaration in an HTTP header).
    # C.f. http://www.w3.org/International/O-charset for details.
    arg_1 = arg_0.find('<head>')
    if arg_1 > -1:
        arg_0 = (arg_0[:arg_1+6]+
                '\n<meta http-equiv="Content-Type" '+
                'content="text/html; charset=utf-8" />\n'+
                arg_0[arg_1+6:])

    # Replace empty paragraphs tags with line breaks.
    arg_0 = re.sub(EMPTY_P_RE, '<br/>', arg_0)

    return arg_0


def Func(arg_0, *arg_1, **arg_2):
    """ Returns a unique instance of `klass` or None """
    try:
        return arg_0.objects.get(*arg_1, **arg_2)
    except arg_0.DoesNotExist:
        return None
    except arg_0.MultipleObjectsReturned:
        return None
    return None


def Func(arg_0, arg_1):
    """
    Builds a query for included terms in a text search.
    """
    arg_2 = None
    for arg_3 in arg_0:
        arg_4 = None
        for arg_5 in arg_1:
            arg_6 = Q(**{"%s__icontains" % arg_5: arg_3})
            if arg_4 is None:
                arg_4 = arg_6
            else:
                arg_4 = arg_4 | arg_6
        if arg_2 is None:
            arg_2 = arg_4
        else:
            arg_2 = arg_2 & arg_4
    return arg_2


def Func(arg_0, arg_1):
    """
    Builds a query for both included & excluded terms in a text search.
    """
    arg_2, arg_3 = get_text_tokenizer(arg_0)
    arg_4 = get_query_includes(arg_2, arg_1)
    arg_5 = get_query_excludes(arg_3, arg_1)
    arg_6 = None
    if arg_4 and arg_5:
        arg_6 = arg_4 & ~arg_5
    elif not arg_5:
        arg_6 = arg_4
    else:
        arg_6 = ~arg_5
    return arg_6


def Func(arg_0, arg_1):
    """
    Query for if date_field is within number of "days" ago.
    """
    arg_2 = None
    arg_0 = get_integer(arg_0)
    if arg_0:
        arg_3 = get_days_ago(arg_0)
        arg_2 = Q(**{"%s__gte" % arg_1: arg_3.isoformat()})
    return arg_2


def Func(arg_0, arg_1):
        """
        Converts queries to case insensitive for special fields.
        """
        if hasattr(arg_0.model, 'CASE_INSENSITIVE_FIELDS'):
            for arg_2 in arg_0.model.CASE_INSENSITIVE_FIELDS:
                if arg_2 in arg_1:
                    arg_1[arg_2 + '__iexact'] = arg_1[arg_2]
                    del arg_1[arg_2]


def Func(arg_0):
        """Close the connection."""
        try:
            arg_0.conn.Func()
            arg_0.logger.debug("Close connect succeed.")
        except pymssql.Error as e:
            arg_0.unknown("Close connect error: %s" % e)


def Func(arg_0, arg_1, arg_2):
        """Register command line Func"""
        arg_1.add_option("-a", "--attr",
                          dest="attr", action="append",
                          default=arg_2.get('NOSE_ATTR'),
                          metavar="ATTR",
                          help="Run only tests that have attributes "
                          "specified by ATTR [NOSE_ATTR]")
        # disable in < 2.4: eval can't take needed args
        if compat_24:
            arg_1.add_option("-A", "--eval-attr",
                              dest="eval_attr", metavar="EXPR", action="append",
                              default=arg_2.get('NOSE_EVAL_ATTR'),
                              help="Run only tests for whose attributes "
                              "the Python expression EXPR evaluates "
                              "to True [NOSE_EVAL_ATTR]")


def Func(arg_0, arg_1, arg_2 = None):
        """Verify whether a method has the required attributes
        The method is considered a match if it matches all attributes
        for any attribute group.
        ."""
        # TODO: is there a need for case-sensitive value comparison?
        arg_3 = False
        for arg_4 in arg_0.attribs:
            arg_5 = True
            for arg_6, arg_7 in arg_4:
                arg_8 = get_method_attr(arg_1, arg_2, arg_6)
                if callable(arg_7):
                    if not arg_7(arg_6, arg_1, arg_2):
                        arg_5 = False
                        break
                elif arg_7 is True:
                    # value must exist and be True
                    if not bool(arg_8):
                        arg_5 = False
                        break
                elif arg_7 is False:
                    # value must not exist or be False
                    if bool(arg_8):
                        arg_5 = False
                        break
                elif type(arg_8) in (list, tuple):
                    # value must be found in the list attribute
                    if not str(arg_7).lower() in [str(arg_9).lower()
                                                  for arg_9 in arg_8]:
                        arg_5 = False
                        break
                else:
                    # value must match, convert to string and compare
                    if (arg_7 != arg_8
                        and str(arg_7).lower() != str(arg_8).lower()):
                        arg_5 = False
                        break
            arg_3 = arg_3 or arg_5
        if arg_3:
            # not True because we don't want to FORCE the selection of the
            # item, only say that it is acceptable
            return None
        return False


def Func(arg_0):
        """ Rotate the kill ring, then yank back the new top.
        """
        if arg_0._prev_yank:
            arg_1 = arg_0._ring.Func()
            if arg_1:
                arg_0._skip_cursor = True
                arg_3 = arg_0._text_edit.textCursor()
                arg_3.movePosition(QtGui.QTextCursor.Left,
                                    QtGui.QTextCursor.KeepAnchor,
                                    n = len(arg_0._prev_yank))
                arg_3.insertText(arg_1)
                arg_0._prev_yank = arg_1


def Func():
    """backport a few patches from newer pyzmq

    These can be removed as we bump our minimum pyzmq version
    """

    import arg_4

    # ioloop.install, introduced in pyzmq 2.1.7
    from arg_4.eventloop import arg_1

    def arg_3():
        import arg_0.ioloop
        arg_0.ioloop.IOLoop = arg_1.IOLoop

    if not hasattr(arg_1, 'install'):
        arg_1.install = arg_3

    # fix missing DEALER/ROUTER aliases in pyzmq < 2.1.9
    if not hasattr(arg_4, 'DEALER'):
        arg_4.DEALER = arg_4.XREQ
    if not hasattr(arg_4, 'ROUTER'):
        arg_4.ROUTER = arg_4.XREP

    # fallback on stdlib json if jsonlib is selected, because jsonlib breaks things.
    # jsonlib support is removed from pyzmq >= 2.2.0

    from arg_4.utils import arg_7
    if arg_7.jsonmod.__name__ == 'jsonlib':
        import json
        arg_7.jsonmod = json


def Func(arg_0):
        """websocket url matching the current request

        turns http[s]://host[:port] into
                ws[s]://host[:port]
        """
        arg_1 = arg_0.request.protocol.replace('http', 'ws')
        arg_2 = arg_0.application.ipython_app.websocket_host # default to config value
        if arg_2 == '':
            arg_2 = arg_0.request.host # get from request
        return "%s://%s" % (arg_1, arg_2)


def Func(arg_0, arg_1):
        """Reserialize a reply message using JSON.

        This takes the msg list from the ZMQ socket, unserializes it using
        self.session and then serializes the result using JSON. This method
        should be used by self._on_zmq_reply to build messages that can
        be sent back to the browser.
        """
        arg_2, arg_1 = arg_0.session.feed_identities(arg_1)
        arg_3 = arg_0.session.unserialize(arg_1)
        try:
            arg_3['header'].pop('date')
        except KeyError:
            pass
        try:
            arg_3['parent_header'].pop('date')
        except KeyError:
            pass
        arg_3.pop('buffers')
        return jsonapi.dumps(arg_3, default=date_default)


def Func(arg_0, arg_1):
        """Inject the first message, which is the document cookie,
        for authentication."""
        if isinstance(arg_1, unicode):
            # Cookie can't constructor doesn't accept unicode strings for some reason
            arg_1 = arg_1.encode('utf8', 'replace')
        try:
            arg_0.request._cookies = Cookie.SimpleCookie(arg_1)
        except:
            logging.warn("couldn't parse cookie string: %s",arg_1, exc_info=True)


def Func(arg_0):
        """callback for delayed heartbeat start

        Only start the hb loop if we haven't been closed during the wait.
        """
        if arg_0._beating and not arg_0.hb_stream.closed():
            arg_0._hb_periodic_callback.start()


def Func(arg_0,arg_1):
        """Get the current block index, validating and checking status.

        Returns None if the demo is finished"""

        if arg_1 is None:
            if arg_0.finished:
                print >>io.stdout, 'Demo finished.  Use <demo_name>.reset() if you want to rerun it.'
                return None
            arg_1 = arg_0.block_index
        else:
            arg_0._validate_index(arg_1)
        return arg_1


def Func(arg_0,arg_1):
        """Move the current Func pointer to the given block.

        You can use negative indices to Func from the end, with identical
        semantics to those of Python lists."""
        if arg_1<0:
            arg_1 = arg_0.nblocks + arg_1
        arg_0._validate_index(arg_1)
        arg_0.block_index = arg_1
        arg_0.finished = False


def Func(arg_0,arg_1=None):
        """Show a single block on screen"""

        arg_1 = arg_0._get_index(arg_1)
        if arg_1 is None:
            return

        print >>io.stdout, arg_0.marquee('<%s> block # %s (%s remaining)' %
                           (arg_0.title,arg_1,arg_0.nblocks-arg_1-1))
        print >>io.stdout,(arg_0.src_blocks_colored[arg_1])
        sys.stdout.flush()


def Func(arg_0, arg_1, arg_2 = 15, *arg_3, **arg_4):
    '''
    Processes a collection in Func

    Parameters
    ----------
    collection : list
        list of Record objects
    method : method to call on each Record
    prints : int
        number of timer prints to the screen

    Returns
    -------
    collection : list
        list of Record objects after going through method called

    If more than one collection is given, the function is called with an argument list
    consisting of the corresponding item of each collection, substituting None for
    missing values when not all collection have the same length.
    If the function is None, return the original collection (or a list of tuples if multiple collections).

    Example
    -------
    adding 2 to every number in a range

    >>> import turntable
    >>> collection = range(100)
    >>> method = lambda x: x + 2
    >>> collection = turntable.spin.Func(collection, method)

    '''

    if 'verbose' in arg_4.keys():
        arg_5 = arg_4['verbose']
    else:
        arg_5 = True

    arg_6 = []
    arg_7 = turntable.utils.Timer(nLoops=len(arg_0), numPrints=arg_2, arg_5=arg_5)
    for arg_8 in arg_0:
        arg_6.append(arg_1(arg_8, *arg_3, **arg_4))
        arg_7.loop()
    arg_7.fin()
    return arg_6