def Func(arg_0):
        """Toggle between the currently active color scheme and NoColor."""

        if arg_0.color_scheme_table.active_scheme_name == 'NoColor':
            arg_0.color_scheme_table.set_active_scheme(arg_0.old_scheme)
            arg_0.Colors = arg_0.color_scheme_table.active_colors
        else:
            arg_0.old_scheme = arg_0.color_scheme_table.active_scheme_name
            arg_0.color_scheme_table.set_active_scheme('NoColor')
            arg_0.Colors = arg_0.color_scheme_table.active_colors


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None,
                             arg_5=5):
        """Return a color formatted string with the traceback info.

        Parameters
        ----------
        etype : exception type
          Type of the exception raised.

        value : object
          Data stored in the exception

        elist : list
          List of frames, see class docstring for details.

        tb_offset : int, optional
          Number of frames in the traceback to skip.  If not given, the
          instance value is used (set in constructor).

        context : int, optional
          Number of lines of context information to print.

        Returns
        -------
        String with formatted exception.
        """
        arg_4 = arg_0.tb_offset if arg_4 is None else arg_4
        arg_6 = arg_0.Colors
        arg_7 = []
        if arg_3:

            if arg_4 and len(arg_3) > arg_4:
                arg_3 = arg_3[arg_4:]

            arg_7.append('Traceback %s(most recent call last)%s:' %
                                (arg_6.normalEm, arg_6.Normal) + '\n')
            arg_7.extend(arg_0._format_list(arg_3))
        # The exception info should be a single entry in the list.
        arg_8 = ''.join(arg_0._format_exception_only(arg_1, arg_2))
        arg_7.append(arg_8)

        # Note: this code originally read:

        ## for line in lines[:-1]:
        ##     out_list.append(" "+line)
        ## out_list.append(lines[-1])

        # This means it was indenting everything but the last line by a little
        # bit.  I've disabled this for now, but if we see ugliness somewhre we
        # can restore it.

        return arg_7


def Func(arg_0, arg_1):
        """Format a list of traceback entry tuples for printing.

        Given a list of tuples as returned by extract_tb() or
        extract_stack(), return a list of strings ready for printing.
        Each string in the resulting list corresponds to the item with the
        same index in the argument list.  Each string ends in a newline;
        the strings may contain internal newlines as well, for those items
        whose source text line is not None.

        Lifted almost verbatim from traceback.py
        """

        arg_2 = arg_0.Colors
        arg_3 = []
        for arg_4, arg_5, arg_6, arg_7 in arg_1[:-1]:
            arg_8 = '  File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \
                    (arg_2.filename, arg_4, arg_2.Normal,
                     arg_2.lineno, arg_5, arg_2.Normal,
                     arg_2.name, arg_6, arg_2.Normal)
            if arg_7:
                arg_8 += '    %s\n' % arg_7.strip()
            arg_3.append(arg_8)
        # Emphasize the last entry
        arg_4, arg_5, arg_6, arg_7 = arg_1[-1]
        arg_8 = '%s  File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \
                (arg_2.normalEm,
                 arg_2.filenameEm, arg_4, arg_2.normalEm,
                 arg_2.linenoEm, arg_5, arg_2.normalEm,
                 arg_2.nameEm, arg_6, arg_2.normalEm,
                 arg_2.Normal)
        if arg_7:
            arg_8 += '%s    %s%s\n' % (arg_2.line, arg_7.strip(),
                                            arg_2.Normal)
        arg_3.append(arg_8)
        #from pprint import pformat; print 'LISTTB', pformat(list) # dbg
        return arg_3


def Func(arg_0, arg_1, arg_2):
        """Format the exception part of a traceback.

        The arguments are the exception type and value such as given by
        sys.exc_info()[:2]. The return value is a list of strings, each ending
        in a newline.  Normally, the list contains a single string; however,
        for SyntaxError exceptions, it contains several lines that (when
        printed) display detailed information about where the syntax error
        occurred.  The message indicating which exception occurred is the
        always last string in the list.

        Also lifted nearly verbatim from traceback.py
        """

        arg_3 = False
        arg_4 = arg_0.Colors
        arg_5 = []
        arg_6 = arg_4.excName + arg_1.__name__ + arg_4.Normal
        if arg_2 is None:
            # Not sure if this can still happen in Python 2.6 and above
            arg_5.append( str(arg_6) + '\n')
        else:
            if arg_1 is SyntaxError:
                arg_3 = True
                #print 'filename is',filename  # dbg
                if not arg_2.filename: arg_2.filename = "<string>"
                arg_5.append('%s  File %s"%s"%s, line %s%d%s\n' % \
                        (arg_4.normalEm,
                         arg_4.filenameEm, arg_2.filename, arg_4.normalEm,
                         arg_4.linenoEm, arg_2.lineno, arg_4.Normal  ))
                if arg_2.text is not None:
                    arg_8 = 0
                    while arg_8 < len(arg_2.text) and arg_2.text[arg_8].isspace():
                        arg_8 += 1
                    arg_5.append('%s    %s%s\n' % (arg_4.line,
                                                  arg_2.text.strip(),
                                                  arg_4.Normal))
                    if arg_2.offset is not None:
                        arg_9 = '    '
                        for arg_10 in arg_2.text[arg_8:arg_2.offset-1]:
                            if arg_10.isspace():
                                arg_9 += arg_10
                            else:
                                arg_9 += ' '
                        arg_5.append('%s%s^%s\n' % (arg_4.caret, arg_9,
                                                   arg_4.Normal) )

            try:
                arg_9 = arg_2.msg
            except Exception:
                arg_9 = arg_0._some_str(arg_2)
            if arg_9:
                arg_5.append('%s%s:%s %s\n' % (str(arg_6), arg_4.excName,
                                              arg_4.Normal, arg_9))
            else:
                arg_5.append('%s\n' % str(arg_6))

        # sync with user hooks
        if arg_3:
            arg_11 = ipapi.get()
            if arg_11 is not None:
                arg_11.hooks.synchronize_with_editor(arg_2.filename, arg_2.lineno, 0)

        return arg_5


def Func(arg_0, arg_1, arg_2):
        """Only print the exception type and message, without a traceback.

        Parameters
        ----------
        etype : exception type
        value : exception value
        """
        # This method needs to use __call__ from *this* class, not the one from
        # a subclass whose signature or behavior may be different
        arg_3 = arg_0.ostream
        arg_3.flush()
        arg_3.write('\n'.join(arg_0.get_exception_only(arg_1, arg_2)))
        arg_3.flush()


def Func(arg_0,arg_1=None):
        """Switch to the desired mode.

        If mode is not specified, cycles through the available modes."""

        if not arg_1:
            arg_2 = ( arg_0.valid_modes.index(arg_0.mode) + 1 ) % \
                      len(arg_0.valid_modes)
            arg_0.mode = arg_0.valid_modes[arg_2]
        elif arg_1 not in arg_0.valid_modes:
            raise ValueError, 'Unrecognized mode in FormattedTB: <'+arg_1+'>\n'\
                  'Valid modes: '+str(arg_0.valid_modes)
        else:
            arg_0.mode = arg_1
        # include variable details only in 'Verbose' mode
        arg_0.include_vars = (arg_0.mode == arg_0.valid_modes[2])
        # Set the join character for generating text tracebacks
        arg_0.tb_join_char = arg_0._join_chars[arg_0.mode]


def Func(arg_0,
                   arg_1=None,
                   arg_2=arg_3,
                   arg_4=True):
    """
    View decorator for requiring a user group.
    """
    def decorator(arg_5):
        @login_required(arg_2=arg_2,
                        arg_1=arg_1)
        def _wrapped_view(arg_6, *arg_7, **arg_8):

            if not (arg_6.user.is_superuser and arg_4):
                if arg_6.user.groups.filter(name=arg_0).count() == 0:
                    raise PermissionDenied

            return arg_5(arg_6, *arg_7, **arg_8)
        return _wrapped_view

    return decorator


def Func(arg_0):
    """
    Initialize the model for a Pyramid app.

    Activate this setup using ``config.include('baka_model')``.

    """
    arg_1 = arg_0.get_settings()
    arg_2 = asbool(arg_1.get('baka_model.should_create_all', False))
    arg_3 = asbool(arg_1.get('baka_model.should_drop_all', False))

    # Configure the transaction manager to support retrying retryable
    # exceptions. We also register the session factory with the thread-local
    # transaction manager, so that all sessions it creates are registered.
    #    "tm.attempts": 3,
    arg_0.add_settings({
        "retry.attempts": 3,
        "tm.activate_hook": tm_activate_hook,
        "tm.annotate_user": False,
    })

    # use pyramid_retry couse pyramid_tm disabled it
    arg_0.include('pyramid_retry')
    # use pyramid_tm to hook the transaction lifecycle to the request
    arg_0.include('pyramid_tm')

    arg_4 = get_engine(arg_1)
    arg_5 = get_session_factory(arg_4)

    arg_0.registry['db_session_factory'] = arg_5

    # make request.db available for use in Pyramid
    arg_0.add_request_method(
        # r.tm is the transaction manager used by pyramid_tm
        lambda r: get_tm_session(arg_5, r.tm),
        'db',
        reify=True
    )

    # service model factory
    arg_0.include('.service')

    # Register a deferred action to bind the engine when the configuration is
    # committed. Deferring the action means that this module can be included
    # before model modules without ill effect.
    arg_0.action(None, bind_engine, (arg_4,), {
        'should_create': arg_2,
        'should_drop': arg_3
    }, order=10)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Handle 'from module import a, b, c' imports."""
    if not hasattr(arg_0, '__path__'):
        return
    for arg_4 in arg_1:
        if not hasattr(arg_4, 'rindex'):
            raise TypeError("Item in ``from list'' not a string")
        if arg_4 == '*':
            if arg_3:
                continue # avoid endless recursion
            try:
                arg_5 = arg_0.__all__
            except AttributeError:
                pass
            else:
                arg_6 = Func(arg_0, arg_5, arg_2, 1)
                if not arg_6:
                    return 0
        elif not hasattr(arg_0, arg_4):
            import_submodule(arg_0, arg_4, arg_2 + '.' + arg_4)


def Func(arg_0, arg_1):
        """Add a line of source to the code.

        Don't include indentations or newlines.

        """
        arg_0.code.append(" " * arg_0.indent_amount)
        arg_0.code.append(arg_1)
        arg_0.code.append("\n")


def Func(arg_0, arg_1):
        """Generate a Python expression for `expr`."""
        if "|" in arg_1:
            arg_2 = arg_1.split("|")
            arg_3 = arg_0.Func(arg_2[0])
            for arg_4 in arg_2[1:]:
                arg_0.all_vars.add(arg_4)
                arg_3 = "c_%s(%s)" % (arg_4, arg_3)
        elif "." in arg_1:
            arg_5 = arg_1.split(".")
            arg_3 = arg_0.Func(arg_5[0])
            arg_6 = [repr(d) for d in arg_5[1:]]
            arg_3 = "dot(%s, %s)" % (arg_3, ", ".join(arg_6))
        else:
            arg_0.all_vars.add(arg_1)
            arg_3 = "c_%s" % arg_1
        return arg_3


def Func(arg_0, arg_1=None):
        """Render this template by applying it to `context`.

        `context` is a dictionary of values to use in this Funcing.

        """
        # Make the complete context we'll use.
        arg_2 = dict(arg_0.context)
        if arg_1:
            arg_2.update(arg_1)
        return arg_0.Func_function(arg_2, arg_0.do_dots)


def Func(arg_0, arg_1, *arg_2):
        """Evaluate dotted expressions at runtime."""
        for arg_3 in arg_2:
            try:
                arg_1 = getattr(arg_1, arg_3)
            except AttributeError:
                arg_1 = arg_1[arg_3]
            if hasattr(arg_1, '__call__'):
                arg_1 = arg_1()
        return arg_1


def Func(arg_0, arg_1):
    '''
    A shortcut function to render a partial template with context and return
    the output.
    '''

    arg_2 = [arg_0] if type(arg_0) != list else arg_0
    arg_3 = None

    for arg_0 in arg_2:
        try:
            arg_3 = template.loader.get_template(arg_0)
            break
        except template.TemplateDoesNotExist:
            pass

    if not arg_3:
        raise Exception('Template does not exist: ' + arg_2[-1])

    return arg_3.render(template.Context(arg_1))


def Func(arg_0):
        """Activate the default formatters."""
        arg_1 = [
            PlainTextFormatter,
            HTMLFormatter,
            SVGFormatter,
            PNGFormatter,
            JPEGFormatter,
            LatexFormatter,
            JSONFormatter,
            JavascriptFormatter
        ]
        arg_2 = {}
        for arg_3 in arg_1:
            arg_4 = arg_3(config=arg_0.config)
            arg_2[arg_4.format_type] = arg_4
        return arg_2


def Func(arg_0, arg_1, arg_2, arg_3):
        """Add a format function for a type specified by the full dotted
        module and name of the type, rather than the type of the object.

        Parameters
        ----------
        type_module : str
            The full dotted name of the module the type is defined in, like
            ``numpy``.
        type_name : str
            The name of the type (the class name), like ``dtype``
        func : callable
            The callable that will be called to compute the format data. The
            call signature of this function is simple, it must take the
            object to be formatted and return the raw data for the given
            format. Subclasses may use a different call signature for the
            `func` argument.
        """
        arg_4 = (arg_1, arg_2)
        arg_5 = arg_0.deferred_printers.get(arg_4, None)
        if arg_3 is not None:
            # To support easy restoration of old printers, we need to ignore
            # Nones.
            arg_0.deferred_printers[arg_4] = arg_3
        return arg_5


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Return absolute and relative path for file

        :type root_path: str|unicode
        :type file_name: str|unicode
        :type input_dir: str|unicode
        :rtype: tuple

        """
        # todo: change relative path resolving [bug on duplicate dir names in path]
        arg_4 = arg_1.replace(arg_3, '')
        return os.path.join(arg_1, arg_2), arg_4 + '/' + arg_2


def Func(arg_0):
        """Configure logging for nose, or optionally other packages. Any logger
        name may be set with the debug option, and that logger will be set to
        debug level and be assigned the same handler as the nose loggers, unless
        it already has a handler.
        """
        if arg_0.loggingConfig:
            from logging.config import fileConfig
            fileConfig(arg_0.loggingConfig)
            return

        arg_1 = logging.Formatter('%(name)s: %(levelname)s: %(message)s')
        if arg_0.debugLog:
            arg_2 = logging.FileHandler(arg_0.debugLog)
        else:
            arg_2 = logging.StreamHandler(arg_0.logStream)
        arg_2.setFormatter(arg_1)

        arg_3 = logging.getLogger('nose')
        arg_3.propagate = 0

        # only add our default handler if there isn't already one there
        # this avoids annoying duplicate log messages.
        if arg_2 not in arg_3.handlers:
            arg_3.addHandler(arg_2)

        # default level
        arg_5 = logging.WARNING
        if arg_0.verbosity >= 5:
            arg_5 = 0
        elif arg_0.verbosity >= 4:
            arg_5 = logging.DEBUG
        elif arg_0.verbosity >= 3:
            arg_5 = logging.INFO
        arg_3.setLevel(arg_5)

        # individual overrides
        if arg_0.debug:
            # no blanks
            arg_6 = [ name for name in arg_0.debug.split(',')
                              if name ]
            for arg_7 in arg_6:
                arg_8 = logging.getLogger(arg_7)
                arg_8.setLevel(logging.DEBUG)
                if not arg_8.handlers and not arg_7.startswith('nose'):
                    arg_8.addHandler(arg_2)


def Func(arg_0, arg_1):
        """Configure the working directory or directories for the test run.
        """
        from nose.importer import add_path
        arg_0.workingDir = None
        arg_1 = tolist(arg_1)
        arg_3 = False
        for arg_4 in arg_1:
            if not arg_0.workingDir:
                arg_5 = absdir(arg_4)
                if arg_5 is None:
                    raise ValueError("Working directory %s not found, or "
                                     "not a directory" % arg_4)
                log.info("Set working dir to %s", arg_5)
                arg_0.workingDir = arg_5
                if arg_0.addPaths and \
                       os.path.exists(os.path.join(arg_5, '__init__.py')):
                    log.info("Working directory %s is a package; "
                             "adding to sys.path" % arg_5)
                    add_path(arg_5)
                continue
            if not arg_3:
                warn("Use of multiple -w arguments is deprecated and "
                     "support may be removed in a future release. You can "
                     "get the same behavior by passing directories without "
                     "the -w argument on the command line, or by using the "
                     "--tests argument in a configuration file.",
                     DeprecationWarning)
            arg_0.testNames.append(arg_4)


def Func(arg_0, arg_1=0, arg_2=25):
    """Very dumb 'pager' in Python, for when nothing else works.

    Only moves forward, same interface as page(), except for pager_cmd and
    mode."""

    arg_3  = arg_0.splitlines()[arg_1:]
    arg_4 = chop(arg_3,arg_2-1)
    if len(arg_4) == 1:
        print >>io.stdout, os.linesep.join(arg_4[0])
    else:
        arg_5 = ""
        for arg_6 in arg_4[0:-1]:
            arg_7 = os.linesep.join(arg_6)
            print >>io.stdout, arg_5 + arg_7
            if not page_more():
                return
            arg_8 = esc_re.findall(arg_7)
            if len(arg_8) > 0:
                arg_5 = arg_8[-1]
        print >>io.stdout, arg_5 + os.linesep.join(arg_4[-1])


def Func(arg_0, arg_1=0, arg_2=None):
    """Page a file, using an optional pager command and starting line.
    """

    arg_2 = get_pager_cmd(arg_2)
    arg_2 += ' ' + get_pager_start(arg_2,arg_1)

    try:
        if os.environ['TERM'] in ['emacs','dumb']:
            raise EnvironmentError
        system(arg_2 + ' ' + arg_0)
    except:
        try:
            if arg_1 > 0:
                arg_1 -= 1
            page(open(arg_0).read(),arg_1)
        except:
            print 'Unable to show file',`fname`


def Func(arg_0=None):
    """Return a pager command.

    Makes some attempts at finding an OS-correct one.
    """
    if os.name == 'posix':
        arg_1 = 'less -r'  # -r for color control sequences
    elif os.name in ['nt','dos']:
        arg_1 = 'type'

    if arg_0 is None:
        try:
            arg_0 = os.environ['PAGER']
        except:
            arg_0 = arg_1
    return arg_0


def Func(arg_0, arg_1):
    """Return the string for paging files with an offset.

    This is the '+N' argument which less and more (under Unix) accept.
    """

    if arg_0 in ['less','more']:
        if arg_1:
            arg_2 = '+' + str(arg_1)
        else:
            arg_2 = ''
    else:
        arg_2 = ''
    return arg_2


def Func(arg_0, arg_1, arg_2):
    """A function to pretty print sympy Basic objects."""
    if arg_2:
        return arg_1.text('Basic(...)')
    arg_3 = pretty(arg_0, use_unicode=True)
    if '\n' in arg_3:
        arg_1.text(u'\n')
    arg_1.text(arg_3)


def Func(arg_0):
    """
    A function to display sympy expression using display style LaTeX in PNG.
    """
    arg_1 = latex(arg_0, mode='plain')
    arg_1 = arg_1.strip('$')
    # As matplotlib does not support display style, dvipng backend is
    # used here.
    arg_2 = latex_to_png('$$%s$$' % arg_1, backend='dvipng')
    return arg_2


def Func(arg_0):
    """
    Return True if type o can be printed with LaTeX.

    If o is a container type, this is True if and only if every element of o
    can be printed with LaTeX.
    """
    import sympy
    if isinstance(arg_0, (list, tuple, set, frozenset)):
        return all(Func(arg_1) for arg_1 in arg_0)
    elif isinstance(arg_0, dict):
        return all((isinstance(arg_1, basestring) or Func(arg_1)) and Func(arg_0[arg_1]) for arg_1 in arg_0)
    elif isinstance(arg_0,(sympy.Basic, sympy.matrices.Matrix, int, long, float)):
        return True
    return False


def Func(arg_0):
    """A function to generate the latex representation of sympy
    expressions."""
    if can_Func(arg_0):
        arg_1 = latex(arg_0, mode='plain')
        arg_1 = arg_1.replace('\\dag','\\dagger')
        arg_1 = arg_1.strip('$')
        return '$$%s$$' % arg_1
    # Fallback to the string printer
    return None


def Func(arg_0, arg_1, arg_2=None):
        """Non-camel-case version of func name for backwards compatibility.

        .. warning ::

           DEPRECATED: Do not use this method,
           use :meth:`options <nose.plugins.base.IPluginInterface.options>`
           instead.

        """
        # FIXME raise deprecation warning if wasn't called by wrapper
        if arg_2 is None:
            arg_2 = os.environ
        try:
            arg_0.options(arg_1, arg_2)
            arg_0.can_configure = True
        except OptionConflictError, e:
            warn("Plugin %s has conflicting option string: %s and will "
                 "be disabled" % (arg_0, e), RuntimeWarning)
            arg_0.enabled = False
            arg_0.can_configure = False


def Func(arg_0):
    """Validate that the input is a list of strings.

    Raises ValueError if not."""
    if not isinstance(arg_0, list):
        raise ValueError('input %r must be a list' % arg_0)
    for arg_1 in arg_0:
        if not isinstance(arg_1, basestring):
            raise ValueError('element %r in list must be a string' % arg_1)


def Func(arg_0):
    """Validate that the input is a dict with string keys and values.

    Raises ValueError if not."""
    for arg_1,arg_2 in arg_0.iteritems():
        if not isinstance(arg_1, basestring):
            raise ValueError('key %r in dict must be a string' % arg_1)
        if not isinstance(arg_2, basestring):
            raise ValueError('value %r in dict must be a string' % arg_2)


def Func(arg_0):
        """Run my loop, ignoring EINTR events in the poller"""
        while True:
            try:
                arg_0.ioloop.start()
            except ZMQError as e:
                if e.errno == errno.EINTR:
                    continue
                else:
                    raise
            except Exception:
                if arg_0._exiting:
                    break
                else:
                    raise
            else:
                break


def Func(arg_0, arg_1):
        """callback for stream.on_recv

        unpacks message, and calls handlers with it.
        """
        arg_2,arg_3 = arg_0.session.feed_identities(arg_1)
        arg_0.call_handlers(arg_0.session.unserialize(arg_3))


def Func(arg_0, arg_1, arg_2=False,
                arg_3=None, arg_4=None, arg_5=None):
        """Execute code in the kernel.

        Parameters
        ----------
        code : str
            A string of Python code.

        silent : bool, optional (default False)
            If set, the kernel will Func the code as quietly possible.

        user_variables : list, optional
            A list of variable names to pull from the user's namespace.  They
            will come back as a dict with these names as keys and their
            :func:`repr` as values.

        user_expressions : dict, optional
            A dict with string keys and  to pull from the user's
            namespace.  They will come back as a dict with these names as keys
            and their :func:`repr` as values.

        allow_stdin : bool, optional
            Flag for
            A dict with string keys and  to pull from the user's
            namespace.  They will come back as a dict with these names as keys
            and their :func:`repr` as values.

        Returns
        -------
        The msg_id of the message sent.
        """
        if arg_3 is None:
            arg_3 = []
        if arg_4 is None:
            arg_4 = {}
        if arg_5 is None:
            arg_5 = arg_0.allow_stdin

        # Don't waste network traffic if inputs are invalid
        if not isinstance(arg_1, basestring):
            raise ValueError('code %r must be a string' % arg_1)
        validate_string_list(arg_3)
        validate_string_dict(arg_4)

        # Create class for content/msg creation. Related to, but possibly
        # not in Session.
        arg_6 = dict(arg_1=arg_1, arg_2=arg_2,
                       arg_3=arg_3,
                       arg_4=arg_4,
                       arg_5=arg_5,
                       )
        arg_7 = arg_0.session.msg('Func_request', arg_6)
        arg_0._queue_send(arg_7)
        return arg_7['header']['msg_id']


def Func(arg_0, arg_1, arg_2, arg_3, arg_4=None):
        """Tab Func text in the kernel's namespace.

        Parameters
        ----------
        text : str
            The text to Func.
        line : str
            The full line of text that is the surrounding context for the
            text to Func.
        cursor_pos : int
            The position of the cursor in the line where the completion was
            requested.
        block : str, optional
            The full block of code in which the completion is being requested.

        Returns
        -------
        The msg_id of the message sent.
        """
        arg_5 = dict(arg_1=arg_1, arg_2=arg_2, arg_4=arg_4, arg_3=arg_3)
        arg_6 = arg_0.session.msg('Func_request', arg_5)
        arg_0._queue_send(arg_6)
        return arg_6['header']['msg_id']


def Func(arg_0, arg_1, arg_2=0):
        """Get metadata information about an object.

        Parameters
        ----------
        oname : str
            A string specifying the object name.
        detail_level : int, optional
            The level of detail for the introspection (0-2)

        Returns
        -------
        The msg_id of the message sent.
        """
        arg_3 = dict(arg_1=arg_1, arg_2=arg_2)
        arg_4 = arg_0.session.msg('Func_request', arg_3)
        arg_0._queue_send(arg_4)
        return arg_4['header']['msg_id']


def Func(arg_0, arg_1=False):
        """Request an immediate kernel Func.

        Upon receipt of the (empty) reply, client code can safely assume that
        the kernel has shut down and it's safe to forcefully terminate it if
        it's still alive.

        The kernel will send the reply via a function registered with Python's
        atexit module, ensuring it's truly done as the kernel is done with all
        normal operation.
        """
        # Send quit message to kernel. Once we implement kernel-side setattr,
        # this should probably be done that way, but for now this will do.
        arg_2 = arg_0.session.msg('Func_request', {'restart':arg_1})
        arg_0._queue_send(arg_2)
        return arg_2['header']['msg_id']


def Func(arg_0, arg_1=1.0):
        """Immediately processes all pending messages on the SUB channel.

        Callers should use this method to ensure that :method:`call_handlers`
        has been called for all messages that have been received on the
        0MQ SUB socket of this channel.

        This method is thread safe.

        Parameters
        ----------
        timeout : float, optional
            The maximum amount of time to spend Funcing, in seconds. The
            default is one second.
        """
        # We do the IOLoop callback process twice to ensure that the IOLoop
        # gets to perform at least one full poll.
        arg_2 = time.time() + arg_1
        for arg_3 in xrange(2):
            arg_0._Funced = False
            arg_0.ioloop.add_callback(arg_0._Func)
            while not arg_0._Funced and time.time() < arg_2:
                time.sleep(0.01)


def Func(arg_0, arg_1):
        """Send a string of raw Func to the kernel."""
        arg_2 = dict(value=arg_1)
        arg_3 = arg_0.session.msg('Func_reply', arg_2)
        arg_0._queue_send(arg_3)


def Func(arg_0, arg_1=True, arg_2=True, arg_3=True, arg_4=True):
        """Starts the channels for this kernel.

        This will create the channels if they do not exist and then start
        them. If port numbers of 0 are being used (random ports) then you
        must first call :method:`start_kernel`. If the channels have been
        stopped and you call this, :class:`RuntimeError` will be raised.
        """
        if arg_1:
            arg_0.shell_channel.start()
        if arg_2:
            arg_0.sub_channel.start()
        if arg_3:
            arg_0.stdin_channel.start()
            arg_0.shell_channel.allow_stdin = True
        else:
            arg_0.shell_channel.allow_stdin = False
        if arg_4:
            arg_0.hb_channel.start()


def Func(arg_0):
        """Are any of the channels created and running?"""
        return (arg_0.shell_channel.is_alive() or arg_0.sub_channel.is_alive() or
                arg_0.stdin_channel.is_alive() or arg_0.hb_channel.is_alive())


def Func(arg_0):
        """load connection info from JSON dict in self.connection_file"""
        with open(arg_0.connection_file) as f:
            arg_1 = json.loads(f.read())

        arg_0.ip = arg_1['ip']
        arg_0.shell_port = arg_1['shell_port']
        arg_0.stdin_port = arg_1['stdin_port']
        arg_0.iopub_port = arg_1['iopub_port']
        arg_0.hb_port = arg_1['hb_port']
        arg_0.session.key = str_to_bytes(arg_1['key'])


def Func(arg_0, arg_1=False):
        """ Attempts to the stop the kernel process cleanly. If the kernel
        cannot be stopped, it is killed, if possible.
        """
        # FIXME: Shutdown does not work on Windows due to ZMQ errors!
        if sys.platform == 'win32':
            arg_0.kill_kernel()
            return

        # Pause the heart beat channel if it exists.
        if arg_0._hb_channel is not None:
            arg_0._hb_channel.pause()

        # Don't send any additional kernel kill messages immediately, to give
        # the kernel a chance to properly execute shutdown actions. Wait for at
        # most 1s, checking every 0.1s.
        arg_0.shell_channel.shutdown(arg_1=arg_1)
        for arg_2 in range(10):
            if arg_0.is_alive:
                time.sleep(0.1)
            else:
                break
        else:
            # OK, we've waited long enough.
            if arg_0.has_kernel:
                arg_0.kill_kernel()

        if not arg_1 and arg_0._connection_file_written:
            # cleanup connection files on full shutdown of kernel we started
            arg_0._connection_file_written = False
            try:
                os.remove(arg_0.connection_file)
            except IOError:
                pass


def Func(arg_0, arg_1=False, **arg_2):
        """Restarts a kernel with the arguments that were used to launch it.

        If the old kernel was launched with random ports, the same ports will be
        used for the new kernel.

        Parameters
        ----------
        now : bool, optional
            If True, the kernel is forcefully restarted *immediately*, without
            having a chance to do any cleanup action.  Otherwise the kernel is
            given 1s to clean up before a forceful restart is issued.

            In all cases the kernel is restarted, the only difference is whether
            it is given a chance to perform a clean shutdown or not.

        **kw : optional
            Any options specified here will replace those used to launch the
            kernel.
        """
        if arg_0._launch_args is None:
            raise RuntimeError("Cannot restart the kernel. "
                               "No previous call to 'start_kernel'.")
        else:
            # Stop currently running kernel.
            if arg_0.has_kernel:
                if arg_1:
                    arg_0.kill_kernel()
                else:
                    arg_0.shutdown_kernel(restart=True)

            # Start new kernel.
            arg_0._launch_args.update(arg_2)
            arg_0.start_kernel(**arg_0._launch_args)

            # FIXME: Messages get dropped in Windows due to probable ZMQ bug
            # unless there is some delay here.
            if sys.platform == 'win32':
                time.sleep(0.2)


def Func(arg_0):
        """ Kill the running kernel. """
        if arg_0.has_kernel:
            # Pause the heart beat channel if it exists.
            if arg_0._hb_channel is not None:
                arg_0._hb_channel.pause()

            # Attempt to kill the kernel.
            try:
                arg_0.kernel.kill()
            except OSError, e:
                # In Windows, we will get an Access Denied error if the process
                # has already terminated. Ignore it.
                if sys.platform == 'win32':
                    if e.winerror != 5:
                        raise
                # On Unix, we may get an ESRCH error if the process has already
                # terminated. Ignore it.
                else:
                    from errno import ESRCH
                    if e.errno != ESRCH:
                        raise
            arg_0.kernel = None
        else:
            raise RuntimeError("Cannot kill kernel. No kernel is running!")


def Func(arg_0):
        """ Interrupts the kernel. Unlike ``signal_kernel``, this operation is
        well supported on all platforms.
        """
        if arg_0.has_kernel:
            if sys.platform == 'win32':
                from parentpoller import ParentPollerWindows as Poller
                Poller.send_interrupt(arg_0.kernel.win32_interrupt_event)
            else:
                arg_0.kernel.send_signal(signal.SIGINT)
        else:
            raise RuntimeError("Cannot interrupt kernel. No kernel is running!")


def Func(arg_0, arg_1):
        """ Sends a signal to the kernel. Note that since only SIGTERM is
        supported on Windows, this function is only useful on Unix systems.
        """
        if arg_0.has_kernel:
            arg_0.kernel.send_signal(arg_1)
        else:
            raise RuntimeError("Cannot signal kernel. No kernel is running!")


def Func(arg_0):
        """Get the REQ socket channel object to make requests of the kernel."""
        if arg_0._Func is None:
            arg_0._Func = arg_0.Func_class(arg_0.context,
                                                         arg_0.session,
                                                         (arg_0.ip, arg_0.shell_port))
        return arg_0._Func


def Func(arg_0):
        """Get the SUB socket channel object."""
        if arg_0._Func is None:
            arg_0._Func = arg_0.Func_class(arg_0.context,
                                                       arg_0.session,
                                                       (arg_0.ip, arg_0.iopub_port))
        return arg_0._Func


def Func(arg_0):
        """Get the heartbeat socket channel object to check that the
        kernel is alive."""
        if arg_0._Func is None:
            arg_0._Func = arg_0.Func_class(arg_0.context,
                                                       arg_0.session,
                                                       (arg_0.ip, arg_0.hb_port))
        return arg_0._Func


def Func(**arg_0):
    """Bind an Engine's Kernel to be used as a full IPython kernel.

    This allows a running Engine to be used simultaneously as a full IPython kernel
    with the QtConsole or other frontends.

    This function returns immediately.
    """
    from IPython.zmq.ipkernel import IPKernelApp
    from IPython.parallel.apps.ipengineapp import IPEngineApp

    # first check for IPKernelApp, in which case this should be a no-op
    # because there is already a bound kernel
    if IPKernelApp.initialized() and isinstance(IPKernelApp._instance, IPKernelApp):
        return

    if IPEngineApp.initialized():
        try:
            arg_1 = IPEngineApp.instance()
        except MultipleInstanceError:
            pass
        else:
            return arg_1.Func(**arg_0)

    raise RuntimeError("Func be called from an IPEngineApp instance")


def Func(arg_0, arg_1, arg_2):
        """
        Emit a Funcging message depending on the Funcging level.

        :param level: The Funcging level.
        :param message: The message to emit.
        """

        if arg_0._Func >= arg_1:
            print(arg_2, file=sys.stderr)


def Func(arg_0):
        """
        Retrieve the extension classes in priority order.

        :returns: A list of extension classes, in proper priority
                  order.
        """

        if arg_0._extension_classes is None:
            arg_1 = {}

            # Iterate over the entrypoints
            for arg_2 in entry.points[NAMESPACE_EXTENSIONS]:
                arg_1.setdefault(arg_2.priority, [])
                arg_1[arg_2.priority].append(arg_2)

            # Save the list of extension classes
            arg_0._extension_classes = list(utils.iter_prio_dict(arg_1))

        return arg_0._extension_classes


def Func(arg_0, arg_1, arg_2, arg_3):
        """
        Called prior to executing a step.

        :param ctxt: An instance of ``timid.context.Context``.
        :param step: An instance of ``timid.steps.Step`` describing
                     the step to be executed.
        :param idx: The index of the step in the list of steps.

        :returns: A ``True`` value if the step is to be skipped,
                  ``False`` otherwise.
        """

        arg_4 = ExtensionDebugger('Func')

        for arg_5 in arg_0.exts:
            with arg_4(arg_5):
                if arg_5.Func(arg_1, arg_2, arg_3):
                    # Step must be skipped
                    arg_4.debug(3, 'Skipping step %d' % arg_3)
                    return True

        return False


def Func(arg_0, arg_1, arg_2):
        """
        Called at the end of processing.  This call allows extensions to
        emit any additional data, such as timing information, prior to
        ``timid``'s exit.  Extensions may also alter the return value.

        :param ctxt: An instance of ``timid.context.Context``.
        :param result: The return value of the basic ``timid`` call,
                       or an ``Exception`` instance if an exception
                       was raised.  Without the extension, this would
                       be passed directly to ``sys.exit()``.

        :returns: The final result.
        """

        arg_3 = ExtensionDebugger('Func')

        for arg_4 in arg_0.exts:
            with arg_3(arg_4):
                arg_2 = arg_4.Func(arg_1, arg_2)

        return arg_2


def Func(arg_0, arg_1):
    """Adds an EnumDescriptor to the pool.

    This method also registers the FileDescriptor associated with the message.

    Args:
      enum_desc: An EnumDescriptor.
    """

    if not isinstance(arg_1, descriptor.EnumDescriptor):
      raise TypeError('Expected instance of descriptor.EnumDescriptor.')

    arg_0._enum_descriptors[arg_1.full_name] = arg_1
    arg_0.AddFileDescriptor(arg_1.file)


def Func(arg_0, arg_1):
    """Loads the named enum descriptor from the pool.

    Args:
      full_name: The full name of the enum descriptor to load.

    Returns:
      The enum descriptor for the named type.
    """

    arg_1 = _NormalizeFullyQualifiedName(arg_1)
    if arg_1 not in arg_0._enum_descriptors:
      arg_0.FindFileContainingSymbol(arg_1)
    return arg_0._enum_descriptors[arg_1]


def Func(arg_0, arg_1, arg_2=None, arg_3=None,
                             arg_4=None, arg_5=None):
    """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.

    Args:
      enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
      package: Optional package name for the new message EnumDescriptor.
      file_desc: The file containing the enum descriptor.
      containing_type: The type containing this enum.
      scope: Scope containing available types.

    Returns:
      The added descriptor
    """

    if arg_2:
      arg_6 = '.'.join((arg_2, arg_1.name))
    else:
      arg_6 = arg_1.name

    if arg_3 is None:
      arg_7 = None
    else:
      arg_7 = arg_3.name

    arg_8 = [arg_0._MakeEnumValueDescriptor(value, index)
              for index, value in enumerate(arg_1.value)]
    arg_9 = descriptor.EnumDescriptor(name=arg_1.name,
                                     full_name=arg_6,
                                     filename=arg_7,
                                     file=arg_3,
                                     arg_8=arg_8,
                                     arg_4=arg_4,
                                     options=arg_1.options)
    arg_5['.%s' % arg_6] = arg_9
    arg_0._enum_descriptors[arg_6] = arg_9
    return arg_9


def Func(arg_0, arg_1, arg_2, arg_3,
                           arg_4=False):
    """Creates a field descriptor from a FieldDescriptorProto.

    For message and enum type fields, this method will do a look up
    in the pool for the appropriate descriptor for that type. If it
    is unavailable, it will fall back to the _source function to
    create it. If this type is still unavailable, construction will
    fail.

    Args:
      field_proto: The proto describing the field.
      message_name: The name of the containing message.
      index: Index of the field
      is_extension: Indication that this field is for an extension.

    Returns:
      An initialized FieldDescriptor object
    """

    if arg_2:
      arg_5 = '.'.join((arg_2, arg_1.name))
    else:
      arg_5 = arg_1.name

    return descriptor.FieldDescriptor(
        name=arg_1.name,
        arg_5=arg_5,
        arg_3=arg_3,
        number=arg_1.number,
        type=arg_1.type,
        cpp_type=None,
        message_type=None,
        enum_type=None,
        containing_type=None,
        label=arg_1.label,
        has_default_value=False,
        default_value=None,
        arg_4=arg_4,
        extension_scope=None,
        options=arg_1.options)


def Func(arg_0, arg_1, arg_2, arg_3):
    """Check whether module possibly uses unsafe-for-zipfile stuff"""

    arg_4 = os.path.join(arg_1,arg_2)
    if arg_4[:-1] in arg_3:
        return True     # Extension module
    arg_5 = arg_1[len(arg_0)+1:].replace(os.sep,'.')
    arg_6 = arg_5+(arg_5 and '.' or '')+os.path.splitext(arg_2)[0]
    if sys.version_info < (3, 3):
        arg_7 = 8   # skip magic & date
    else:
        arg_7 = 12  # skip magic & date & file size
    arg_8 = open(arg_4,'rb'); arg_8.read(arg_7)
    arg_9 = marshal.load(arg_8); arg_8.close()
    arg_10 = True
    arg_11 = dict.fromkeys(iter_symbols(arg_9))
    for arg_12 in ['__file__', '__path__']:
        if arg_12 in arg_11:
            log.warn("%s: module references %s", arg_6, arg_12)
            arg_10 = False
    if 'inspect' in arg_11:
        for arg_12 in [
            'getsource', 'getabsfile', 'getsourcefile', 'getfile'
            'getsourcelines', 'findsource', 'getcomments', 'getframeinfo',
            'getinnerframes', 'getouterframes', 'stack', 'trace'
        ]:
            if arg_12 in arg_11:
                log.warn("%s: module MAY be using inspect.%s", arg_6, arg_12)
                arg_10 = False
    if '__name__' in arg_11 and '__main__' in arg_11 and '.' not in arg_6:
        if sys.version[:3]=="2.4":  # -m works w/zipfiles in 2.5
            log.warn("%s: top-level module may be 'python -m' script", arg_6)
            arg_10 = False
    return arg_10


def Func():
    """Create and run the IPython controller"""
    if sys.platform == 'win32':
        # make sure we don't get called from a multiprocessing subprocess
        # this can result in infinite Controllers being started on Windows
        # which doesn't have a proper fork, so multiprocessing is wonky

        # this only comes up when IPython has been installed using vanilla
        # setuptools, and *not* distribute.
        import multiprocessing
        arg_0 = multiprocessing.current_process()
        # the main process has name 'MainProcess'
        # subprocesses will have names like 'Process-1'
        if arg_0.name != 'MainProcess':
            # we are a subprocess, don't start another Controller!
            return
    arg_1 = IPControllerApp.instance()
    arg_1.initialize()
    arg_1.start()


def Func(arg_0, arg_1, arg_2):
        """save a connection dict to json file."""
        arg_3 = arg_0.config
        arg_4 = arg_2['url']
        arg_5 = arg_2['location']
        if not arg_5:
            try:
                arg_6,arg_7,arg_8 = split_url(arg_4)
            except AssertionError:
                pass
            else:
                try:
                    arg_5 = socket.gethostbyname_ex(socket.gethostname())[2][-1]
                except (socket.gaierror, IndexError):
                    arg_0.log.warn("Could not identify this machine's IP, assuming 127.0.0.1."
                    " You may need to specify '--location=<external_ip_address>' to help"
                    " IPython decide when to connect via loopback.")
                    arg_5 = '127.0.0.1'
            arg_2['location'] = arg_5
        arg_1 = os.path.join(arg_0.profile_dir.security_dir, arg_1)
        arg_0.log.info("writing connection info to %s", arg_1)
        with open(arg_1, 'w') as f:
            f.write(json.dumps(arg_2, indent=2))
        os.chmod(arg_1, stat.S_IRUSR|stat.S_IWUSR)


def Func(arg_0):
        """load config from existing json connector files."""
        arg_1 = arg_0.config
        arg_0.log.debug("loading config from JSON")
        # load from engine config
        arg_2 = os.path.join(arg_0.profile_dir.security_dir, arg_0.engine_json_file)
        arg_0.log.info("loading connection info from %s", arg_2)
        with open(arg_2) as f:
            arg_3 = json.loads(f.read())
        arg_4 = arg_3['exec_key']
        # json gives unicode, Session.key wants bytes
        arg_1.Session.key = arg_4.encode('ascii')
        arg_6,arg_7 = arg_3['url'].split('://')
        arg_1.HubFactory.engine_transport = arg_6
        arg_10,arg_11 = arg_7.split(':')
        arg_1.HubFactory.engine_ip = arg_10
        arg_1.HubFactory.regport = int(arg_11)
        arg_0.location = arg_3['location']
        if not arg_0.engine_ssh_server:
            arg_0.engine_ssh_server = arg_3['ssh']
        # load client config
        arg_2 = os.path.join(arg_0.profile_dir.security_dir, arg_0.client_json_file)
        arg_0.log.info("loading connection info from %s", arg_2)
        with open(arg_2) as f:
            arg_3 = json.loads(f.read())
        assert arg_4 == arg_3['exec_key'], "exec_key mismatch between engine and client keys"
        arg_6,arg_7 = arg_3['url'].split('://')
        arg_1.HubFactory.client_transport = arg_6
        arg_10,arg_11 = arg_7.split(':')
        arg_1.HubFactory.client_ip = arg_10
        if not arg_0.ssh_server:
            arg_0.ssh_server = arg_3['ssh']
        assert int(arg_11) == arg_1.HubFactory.regport, "regport mismatch"


def Func(arg_0):
        """secondary config, loading from JSON and setting defaults"""
        if arg_0.reuse_files:
            try:
                arg_0.load_config_from_json()
            except (AssertionError,IOError) as e:
                arg_0.log.error("Could not load config from JSON: %s" % e)
            else:
                # successfully loaded config from JSON, and reuse=True
                # no need to wite back the same file
                arg_0.write_connection_files = False

        # switch Session.key default to secure
        default_secure(arg_0.config)
        arg_0.log.debug("Config changed")
        arg_0.log.debug(repr(arg_0.config))


def Func(arg_0, arg_1):
    """
    Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.

    This function will hook the session to the transaction manager which
    will take care of committing any changes.

    - When using pyramid_tm it will automatically be committed or aborted
      depending on whether an exception is raised.

    - When using scripts you should wrap the session in a manager yourself.
      For example::

          import transaction

          engine = get_engine(settings)
          session_factory = get_session_factory(engine)
          with transaction.manager:
              dbsession = Func(session_factory, transaction.manager)

    """
    arg_2 = arg_0()
    zope.sqlalchemy.register(
        arg_2, arg_1=arg_1)
    return arg_2


def Func(arg_0):
        """Enable %autopx mode by saving the original run_cell and installing
        pxrun_cell.
        """
        # override run_cell
        arg_0._original_run_cell = arg_0.shell.run_cell
        arg_0.shell.run_cell = arg_0.pxrun_cell

        arg_0._autopx = True
        print "%autopx enabled"


def Func(arg_0):
        """Disable %autopx by restoring the original InteractiveShell.run_cell.
        """
        if arg_0._autopx:
            arg_0.shell.run_cell = arg_0._original_run_cell
            arg_0._autopx = False
            print "%autopx disabled"


def Func(arg_0, arg_1, arg_2=False, arg_3=False):
        """drop-in replacement for InteractiveShell.run_cell.

        This executes code remotely, instead of in the local namespace.

        See InteractiveShell.run_cell for details.
        """

        if (not arg_1) or arg_1.isspace():
            return

        arg_4 = arg_0.shell

        with arg_4.builtin_trap:
            arg_5 = arg_4.prefilter_manager.prefilter_lines(arg_1)

            # Store raw and processed history
            if arg_2:
                arg_4.history_manager.store_inputs(arg_4.execution_count,
                                                  arg_5, arg_1)

            # ipself.logger.log(cell, raw_cell)

            arg_6 = arg_4.compile.cache(arg_5, arg_4.execution_count)

            try:
                ast.parse(arg_5, filename=arg_6)
            except (OverflowError, SyntaxError, ValueError, TypeError,
                    MemoryError):
                # Case 1
                arg_4.showsyntaxerror()
                arg_4.execution_count += 1
                return None
            except NameError:
                # ignore name errors, because we don't know the remote keys
                pass

        if arg_2:
            # Write output to the database. Does nothing unless
            # history output logging is enabled.
            arg_4.history_manager.store_output(arg_4.execution_count)
            # Each cell is a *single* input, regardless of how many lines it has
            arg_4.execution_count += 1
        if re.search(r'get_ipython\(\)\.magic\(u?["\']%?autopx', arg_5):
            arg_0._disable_autopx()
            return False
        else:
            try:
                arg_7 = arg_0.view.execute(arg_5, arg_3=False, block=False)
            except:
                arg_4.showtraceback()
                return True
            else:
                if arg_0.view.block:
                    try:
                        arg_7.get()
                    except:
                        arg_0.shell.showtraceback()
                        return True
                    else:
                        with arg_4.builtin_trap:
                            arg_7.display_outputs()
                return False


def Func(arg_0):
    """
    Patch the protocol's makeConnection and connectionLost methods to make the
    protocol and its transport behave more like what `Agent` expects.

    While `Agent` is the driving force behind this, other clients and servers
    will no doubt have similar requirements.
    """
    arg_1 = arg_0.makeConnection
    arg_2 = arg_0.connectionLost

    def new_makeConnection(arg_3):
        patch_transport_fake_push_producer(arg_3)
        patch_transport_abortConnection(arg_3, arg_0)
        return arg_1(arg_3)

    def new_connectionLost(arg_4):
        # Replace ConnectionDone with ConnectionAborted if we aborted.
        if arg_0._fake_connection_aborted and arg_4.check(ConnectionDone):
            arg_4 = Failure(ConnectionAborted())
        return arg_2(arg_4)

    arg_0.makeConnection = new_makeConnection
    arg_0.connectionLost = new_connectionLost
    arg_0._fake_connection_aborted = False


def Func(arg_0, arg_1, arg_2):
    """
    Patch a method onto an object if it isn't already there.
    """
    setattr(arg_0, arg_1, getattr(arg_0, arg_1, arg_2))


def Func(arg_0):
        """
        Accept a pending connection.
        """
        assert arg_0.pending, "Connection is not pending."
        arg_0.server_protocol = arg_0.server.server_factory.buildProtocol(None)
        arg_0._accept_d.callback(
            FakeServerProtocolWrapper(arg_0, arg_0.server_protocol))
        return arg_0.await_connected()


def Func(arg_0, arg_1=None):
        """
        Reject a pending connection.
        """
        assert arg_0.pending, "Connection is not pending."
        if arg_1 is None:
            arg_1 = ConnectionRefusedError()
        arg_0._accept_d.errback(arg_1)


def Func(arg_0, arg_1):
        """
        Calls pre and post save hooks.
        """
        arg_0.object = arg_1.save(commit=False)

        # Invoke pre_save hook, and allow it to abort the saving
        # process and do a redirect.
        arg_3 = arg_0.pre_save(arg_0.object)
        if arg_3:
            return arg_3

        arg_0.object.save()
        arg_1.save_m2m()
        arg_0.post_save(arg_0.object)

        return HttpResponseRedirect(arg_0.get_success_url())


def Func(arg_0, arg_1):
        super(UserViewMixin, arg_0).Func(arg_1)

        """
        Use SaveHookMixin Func to set the user.
        """
        if  arg_0.request.user.is_authenticated():
            for arg_2 in arg_0.user_field:
                setattr(arg_1, arg_2, arg_0.request.user)


def Func(arg_0, arg_1=False):
        """Check whether some modules need to be reloaded."""

        if not arg_0.enabled and not arg_1:
            return

        if arg_1 or arg_0.Func_all:
            arg_2 = sys.modules.keys()
        else:
            arg_2 = arg_0.modules.keys()

        for arg_3 in arg_2:
            arg_4 = sys.modules.get(arg_3, None)

            if arg_3 in arg_0.skip_modules:
                continue

            if not hasattr(arg_4, '__file__'):
                continue

            if arg_4.__name__ == '__main__':
                # we cannot reload(__main__)
                continue

            arg_5 = arg_4.__file__
            arg_6, arg_7 = os.path.splitext(arg_5)

            if arg_7.lower() == '.py':
                arg_7 = PY_COMPILED_EXT
                arg_8 = pyfile.cache_from_source(arg_5)
                arg_9 = arg_5
            else:
                arg_8 = arg_5
                try:
                    arg_9 = pyfile.source_from_cache(arg_5)
                except ValueError:
                    continue

            try:
                arg_10 = os.stat(arg_9).st_mtime
                if arg_10 <= os.stat(arg_8).st_mtime:
                    continue
                if arg_0.failed.get(arg_9, None) == arg_10:
                    continue
            except OSError:
                continue

            try:
                superreload(arg_4, reload, arg_0.old_objects)
                if arg_9 in arg_0.failed:
                    del arg_0.failed[arg_9]
            except:
                print >> sys.stderr, "[autoreload of %s failed: %s]" % (
                        arg_3, traceback.format_exc(1))
                arg_0.failed[arg_9] = arg_10


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
    """Open the default editor at the given filename and linenumber.

    This is IPython's default editor hook, you can use it as an example to
    write your own modified one.  To set your own editor function as the
    new editor hook, call ip.set_hook('editor',yourfunc)."""

    # IPython configures a default editor at startup by reading $EDITOR from
    # the environment, and falling back on vi (unix) or notepad (win32).
    Func = arg_0.editor

    # marker for at which line to open the file (for existing objects)
    if arg_2 is None or Func=='notepad':
        arg_5 = ''
    else:
        arg_5 = '+%d' % int(arg_2)

    # Enclose in quotes if necessary and legal
    if ' ' in Func and os.path.isfile(Func) and Func[0] != '"':
        Func = '"%s"' % Func

    # Call the actual editor
    arg_6 = subprocess.Popen('%s %s %s' % (Func, arg_5, arg_1),
                            shell=True)
    if arg_3 and arg_6.wait() != 0:
        raise TryNext()


def Func(arg_0):
    """ Get text from the clipboard.
    """
    from IPython.lib.clipboard import (
        osx_Func, tkinter_Func,
        win32_Func
    )
    if sys.platform == 'win32':
        arg_1 = [win32_Func, tkinter_Func]
    elif sys.platform == 'darwin':
        arg_1 = [osx_Func, tkinter_Func]
    else:
        arg_1 = [tkinter_Func]
    arg_2 = CommandChainDispatcher()
    for arg_3 in arg_1:
        arg_2.add(arg_3)
    arg_4 = arg_2()
    return arg_4


def Func(arg_0, arg_1, arg_2=0):
        """ Add a func to the cmd chain with given priority """
        arg_0.chain.append((arg_2, arg_1))
        arg_0.chain.sort(key=lambda x: x[0])


def Func(arg_0, arg_1, arg_2):
        """Configure which kinds of exceptions trigger plugin.
        """
        arg_0.conf = arg_2
        arg_0.enabled = arg_1.debugErrors or arg_1.debugFailures
        arg_0.enabled_for_errors = arg_1.debugErrors
        arg_0.enabled_for_failures = arg_1.debugFailures


def Func(arg_0):
    """Import and return bar given the string foo.bar."""
    arg_1 = '.'.join(arg_0.split('.')[0:-1])
    arg_2 = arg_0.split('.')[-1]

    # Note: the original code for this was the following.  We've left it
    # visible for now in case the new implementation shows any problems down
    # the road, to make it easier on anyone looking for a problem.  This code
    # should be removed once we're comfortable we didn't break anything.

    ## execString = 'from %s import %s' % (package, obj)
    ## try:
    ##     exec execString
    ## except SyntaxError:
    ##     raise ImportError("Invalid class specification: %s" % name)
    ## exec 'temp = %s' % obj
    ## return temp

    if arg_1:
        arg_3 = __import__(arg_1,fromlist=[arg_2])
        try:
            arg_4 = arg_3.__dict__[arg_2]
        except KeyError:
            raise ImportError('No module named %s' % arg_2)
        return arg_4
    else:
        return __import__(arg_2)


def Func(arg_0):
        """Forces a Func from the internal queue to the server"""
        arg_1 = arg_0.queue
        arg_2 = arg_1.qsize()
        arg_1.join()
        arg_0.log.debug('successfully Funced %s items.', arg_2)


def Func(arg_0, arg_1):
    """Try passwordless login with shell ssh command."""
    if pexpect is None:
        raise ImportError("pexpect unavailable, use paramiko")
    arg_2 = 'ssh -f '+ arg_0
    if arg_1:
        arg_2 += ' -i ' + arg_1
    arg_2 += ' exit'
    arg_3 = pexpect.spawn(arg_2)
    while True:
        try:
            arg_3.expect('[Pp]assword:', timeout=.1)
        except pexpect.TIMEOUT:
            continue
        except pexpect.EOF:
            return True
        else:
            return False


def Func(arg_0, arg_1):
    """Try passwordless login with paramiko."""
    if paramiko is None:
        arg_2 = "Paramiko unavaliable, "
        if sys.platform == 'win32':
            arg_2 += "Paramiko is required for ssh tunneled connections on Windows."
        else:
            arg_2 += "use OpenSSH."
        raise ImportError(arg_2)
    arg_3, arg_0, arg_4 = _split_server(arg_0)
    arg_5 = paramiko.SSHClient()
    arg_5.load_system_host_keys()
    arg_5.set_missing_host_key_policy(paramiko.WarningPolicy())
    try:
        arg_5.connect(arg_0, arg_4, arg_3=arg_3, key_filename=arg_1,
               look_for_keys=True)
    except paramiko.AuthenticationException:
        return False
    else:
        arg_5.close()
        return True


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None, arg_6=60):
    """Connect a socket to an address via an ssh tunnel.

    This is a wrapper for socket.connect(addr), when addr is not accessible
    from the local machine.  It simply creates an ssh tunnel using the remaining args,
    and calls socket.connect('tcp://localhost:lport') where lport is the randomly
    selected local port of the tunnel.

    """
    arg_7, arg_8 = open_tunnel(arg_1, arg_2, arg_3=arg_3, arg_4=arg_4, arg_5=arg_5, arg_6=arg_6)
    arg_0.connect(arg_7)
    return arg_8


def Func(arg_0, arg_1):
        """unwrap exception, and remap engine_id to int."""
        arg_2 = error.unwrap_exception(arg_1)
        # print e.traceback
        if arg_2.engine_info:
            arg_3 = arg_2.engine_info['engine_uuid']
            arg_4 = arg_0._engines[arg_3]
            arg_2.engine_info['engine_id'] = arg_4
        return arg_2


def Func(arg_0, arg_1):
        """Register a new engine, and update our connection info."""
        arg_2 = arg_1['content']
        arg_3 = arg_2['id']
        arg_4 = {arg_3 : arg_2['queue']}
        arg_0._update_engines(arg_4)


def Func(arg_0, arg_1):
        """Flush task or queue results waiting in ZMQ queue."""
        arg_2,arg_3 = arg_0.session.recv(arg_1, mode=zmq.NOBLOCK)
        while arg_3 is not None:
            if arg_0.debug:
                pprint(arg_3)
            arg_4 = arg_3['header']['msg_type']
            arg_5 = arg_0._queue_handlers.get(arg_4, None)
            if arg_5 is None:
                raise Exception("Unhandled message type: %s"%arg_3.msg_type)
            else:
                arg_5(arg_3)
            arg_2,arg_3 = arg_0.session.recv(arg_1, mode=zmq.NOBLOCK)


def Func(arg_0, arg_1):
        """Flush replies from the iopub channel waiting
        in the ZMQ queue.
        """
        arg_2,arg_3 = arg_0.session.recv(arg_1, mode=zmq.NOBLOCK)
        while arg_3 is not None:
            if arg_0.debug:
                pprint(arg_3)
            arg_4 = arg_3['parent_header']
            # ignore IOPub messages with no parent.
            # Caused by print statements or warnings from before the first execution.
            if not arg_4:
                continue
            arg_5 = arg_4['msg_id']
            arg_6 = arg_3['content']
            arg_7 = arg_3['header']
            arg_8 = arg_3['header']['msg_type']

            # init metadata:
            arg_9 = arg_0.metadata[arg_5]

            if arg_8 == 'stream':
                arg_10 = arg_6['name']
                arg_11 = arg_9[arg_10] or ''
                arg_9[arg_10] = arg_11 + arg_6['data']
            elif arg_8 == 'pyerr':
                arg_9.update({'pyerr' : arg_0._unwrap_exception(arg_6)})
            elif arg_8 == 'pyin':
                arg_9.update({'pyin' : arg_6['code']})
            elif arg_8 == 'display_data':
                arg_9['outputs'].append(arg_6)
            elif arg_8 == 'pyout':
                arg_9['pyout'] = arg_6
            elif arg_8 == 'status':
                # idle message comes after all outputs
                if arg_6['execution_state'] == 'idle':
                    arg_9['outputs_ready'] = True
            else:
                # unhandled msg_type (status, etc.)
                pass

            # reduntant?
            arg_0.metadata[arg_5] = arg_9

            arg_2,arg_3 = arg_0.session.recv(arg_1, mode=zmq.NOBLOCK)


def Func(arg_0, arg_1=1):
        """target func for use in spin_thread"""
        while True:
            if arg_0._stop_spinning.is_set():
                return
            time.sleep(arg_1)
            arg_0.spin()


def Func(arg_0):
        """Flush any registration notifications and execution results
        waiting in the ZMQ queue.
        """
        if arg_0._notification_socket:
            arg_0._flush_notifications()
        if arg_0._iopub_socket:
            arg_0._flush_iopub(arg_0._iopub_socket)
        if arg_0._mux_socket:
            arg_0._flush_results(arg_0._mux_socket)
        if arg_0._task_socket:
            arg_0._flush_results(arg_0._task_socket)
        if arg_0._control_socket:
            arg_0._flush_control(arg_0._control_socket)
        if arg_0._query_socket:
            arg_0._flush_ignored_hub_replies()


def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None, arg_6=False,
                            arg_7=None):
        """construct and send an apply message via a socket.

        This is the principal method with which all engine execution is performed by views.
        """

        if arg_0._closed:
            raise RuntimeError("Client cannot be used after its sockets have been closed")

        # defaults:
        arg_3 = arg_3 if arg_3 is not None else []
        arg_4 = arg_4 if arg_4 is not None else {}
        arg_5 = arg_5 if arg_5 is not None else {}

        # validate arguments
        if not callable(arg_2) and not isinstance(arg_2, Reference):
            raise TypeError("f must be callable, not %s"%type(arg_2))
        if not isinstance(arg_3, (tuple, list)):
            raise TypeError("args must be tuple or list, not %s"%type(arg_3))
        if not isinstance(arg_4, dict):
            raise TypeError("kwargs must be dict, not %s"%type(arg_4))
        if not isinstance(arg_5, dict):
            raise TypeError("subheader must be dict, not %s"%type(arg_5))

        arg_8 = util.pack_apply_message(arg_2,arg_3,arg_4)

        arg_9 = arg_0.session.send(arg_1, "apply_request", buffers=arg_8, arg_7=arg_7,
                            arg_5=arg_5, arg_6=arg_6)

        arg_10 = arg_9['header']['msg_id']
        arg_0.outstanding.add(arg_10)
        if arg_7:
            # possibly routed to a specific engine
            if isinstance(arg_7, list):
                arg_7 = arg_7[-1]
            if arg_7 in arg_0._engines.values():
                # save for later, in case of engine death
                arg_0._outstanding_dict[arg_7].add(arg_10)
        arg_0.history.append(arg_10)
        arg_0.metadata[arg_10]['submitted'] = datetime.now()

        return arg_9


def Func(arg_0, arg_1, arg_2, arg_3=True, arg_4=None, arg_5=None):
        """construct and send an execute request via a socket.

        """

        if arg_0._closed:
            raise RuntimeError("Client cannot be used after its sockets have been closed")

        # defaults:
        arg_4 = arg_4 if arg_4 is not None else {}

        # validate arguments
        if not isinstance(arg_2, basestring):
            raise TypeError("code must be text, not %s" % type(arg_2))
        if not isinstance(arg_4, dict):
            raise TypeError("subheader must be dict, not %s" % type(arg_4))

        arg_6 = dict(arg_2=arg_2, arg_3=bool(arg_3), user_variables=[], user_expressions={})

        arg_7 = arg_0.session.send(arg_1, "execute_request", arg_6=arg_6, arg_5=arg_5,
                            arg_4=arg_4)

        arg_8 = arg_7['header']['msg_id']
        arg_0.outstanding.add(arg_8)
        if arg_5:
            # possibly routed to a specific engine
            if isinstance(arg_5, list):
                arg_5 = arg_5[-1]
            if arg_5 in arg_0._engines.values():
                # save for later, in case of engine death
                arg_0._outstanding_dict[arg_5].add(arg_8)
        arg_0.history.append(arg_8)
        arg_0.metadata[arg_8]['submitted'] = datetime.now()

        return arg_7


def Func(arg_0, arg_1=None, arg_2=None):
        """Retrieve a result by msg_id or history index, wrapped in an AsyncResult object.

        If the client already has the results, no request to the Hub will be made.

        This is a convenient way to construct AsyncResult objects, which are wrappers
        that include metadata about execution, and allow for awaiting results that
        were not submitted by this Client.

        It can also be a convenient way to retrieve the metadata associated with
        blocking execution, since it always retrieves

        Examples
        --------
        ::

            In [10]: r = client.apply()

        Parameters
        ----------

        indices_or_msg_ids : integer history index, str msg_id, or list of either
            The indices or msg_ids of indices to be retrieved

        block : bool
            Whether to wait for the result to be done

        Returns
        -------

        AsyncResult
            A single AsyncResult object will always be returned.

        AsyncHubResult
            A subclass of AsyncResult that retrieves results from the Hub

        """
        arg_2 = arg_0.block if arg_2 is None else arg_2
        if arg_1 is None:
            arg_1 = -1

        if not isinstance(arg_1, (list,tuple)):
            arg_1 = [arg_1]

        arg_3 = []
        for arg_4 in arg_1:
            if isinstance(arg_4, int):
                arg_4 = arg_0.history[arg_4]
            if not isinstance(arg_4, basestring):
                raise TypeError("indices must be str or int, not %r"%arg_4)
            arg_3.append(arg_4)

        arg_5 = filter(lambda msg_id: msg_id in arg_0.history or msg_id in arg_0.results, arg_3)
        arg_6 = filter(lambda msg_id: msg_id not in arg_5, arg_3)

        if arg_6:
            arg_7 = AsyncHubResult(arg_0, msg_ids=arg_3)
        else:
            arg_7 = AsyncResult(arg_0, msg_ids=arg_3)

        if arg_2:
            arg_7.wait()

        return arg_7


def Func(*arg_0):
    """Return a set of opcodes by the names in `names`."""
    arg_1 = set()
    for arg_2 in arg_0:
        try:
            arg_1.add(_opcode(arg_2))
        except KeyError:
            pass
    return arg_1


def Func(arg_0):
        """Parse the source to find the interesting facts about its lines.

        A handful of member fields are updated.

        """
        # Find lines which match an exclusion pattern.
        if arg_0.exclude:
            arg_0.excluded = arg_0.lines_matching(arg_0.exclude)

        # Tokenize, to find excluded suites, to find docstrings, and to find
        # multi-line statements.
        arg_2 = 0
        arg_3 = 0
        arg_4 = False
        arg_5 = token.INDENT
        arg_6 = None
        arg_7 = True

        arg_8 = generate_tokens(arg_0.text)
        for arg_9, arg_10, (arg_11, arg_12), (arg_13, arg_12), arg_14 in arg_8:
            if arg_0.show_tokens:                # pragma: not covered
                print("%10s %5s %-20r %r" % (
                    tokenize.tok_name.get(arg_9, arg_9),
                    nice_pair((arg_11, arg_13)), arg_10, arg_14
                    ))
            if arg_9 == token.INDENT:
                arg_2 += 1
            elif arg_9 == token.DEDENT:
                arg_2 -= 1
            elif arg_9 == token.NAME and arg_10 == 'class':
                # Class definitions look like branches in the byte code, so
                # we need to exclude them.  The simplest way is to note the
                # lines with the 'class' keyword.
                arg_0.classdefs.add(arg_11)
            elif arg_9 == token.OP and arg_10 == ':':
                if not arg_4 and arg_13 in arg_0.excluded:
                    # Start excluding a suite.  We trigger off of the colon
                    # token so that the #pragma comment will be recognized on
                    # the same line as the colon.
                    arg_3 = arg_2
                    arg_4 = True
            elif arg_9 == token.STRING and arg_5 == token.INDENT:
                # Strings that are first on an indented line are docstrings.
                # (a trick from trace.py in the stdlib.) This works for
                # 99.9999% of cases.  For the rest (!) see:
                # http://stackoverflow.com/questions/1769332/x/1769794#1769794
                arg_0.docstrings.update(range(arg_11, arg_13+1))
            elif arg_9 == token.NEWLINE:
                if arg_6 is not None and arg_13 != arg_6:
                    # We're at the end of a line, and we've ended on a
                    # different line than the first line of the statement,
                    # so record a multi-line range.
                    arg_15 = (arg_6, arg_13)
                    for arg_16 in range(arg_6, arg_13+1):
                        arg_0.multiline[arg_16] = arg_15
                arg_6 = None

            if arg_10.strip() and arg_9 != tokenize.COMMENT:
                # A non-whitespace token.
                arg_7 = False
                if arg_6 is None:
                    # The token is not whitespace, and is the first in a
                    # statement.
                    arg_6 = arg_11
                    # Check whether to end an excluded suite.
                    if arg_4 and arg_2 <= arg_3:
                        arg_4 = False
                    if arg_4:
                        arg_0.excluded.add(arg_13)

            arg_5 = arg_9

        # Find the starts of the executable statements.
        if not arg_7:
            arg_0.statement_starts.update(arg_0.byte_parser._find_statements())


def Func(arg_0, arg_1):
        """Return the first line number of the statement including `line`."""
        arg_2 = arg_0.multiline.get(arg_1)
        if arg_2:
            Func = arg_2[0]
        else:
            Func = arg_1
        return Func


def Func(arg_0, arg_1, *arg_2):
        """Map the line numbers in `lines` to the correct first line of the
        statement.

        Skip any line mentioned in any of the sequences in `ignores`.

        Returns a set of the first lines.

        """
        arg_3 = set()
        for arg_4 in arg_2:
            arg_3.update(arg_4)
        arg_5 = set()
        for arg_6 in arg_1:
            if arg_6 in arg_3:
                continue
            arg_7 = arg_0.first_line(arg_6)
            if arg_7 not in arg_3:
                arg_5.add(arg_7)
        return arg_5


def Func(arg_0):
        """Get information about the Func available in the code.

        Returns a sorted list of line number pairs.  Line numbers have been
        normalized to the first line of multiline statements.

        """
        arg_1 = []
        for arg_2, arg_3 in arg_0.byte_parser._all_Func():
            arg_4 = arg_0.first_line(arg_2)
            arg_5 = arg_0.first_line(arg_3)
            if arg_4 != arg_5:
                arg_1.append((arg_4, arg_5))
        return sorted(arg_1)


def Func(arg_0):
        """Get a mapping from line numbers to count of exits from that line.

        Excluded lines are excluded.

        """
        arg_1 = arg_0.first_lines(arg_0.excluded)
        Func = {}
        for arg_3, arg_4 in arg_0.arcs():
            if arg_3 < 0:
                # Don't ever report -1 as a line number
                continue
            if arg_3 in arg_1:
                # Don't report excluded lines as line numbers.
                continue
            if arg_4 in arg_1:
                # Arcs to excluded lines shouldn't count.
                continue
            if arg_3 not in Func:
                Func[arg_3] = 0
            Func[arg_3] += 1

        # Class definitions have one extra exit, so remove one for each:
        for arg_5 in arg_0.classdefs:
            # Ensure key is there: classdefs can include excluded lines.
            if arg_5 in Func:
                Func[arg_5] -= 1

        return Func


def Func(arg_0):
        """Iterate over all the code objects nested within this one.

        The iteration includes `self` as its first value.

        """
        arg_1 = CodeObjects(arg_0.code)
        return [ByteParser(code=arg_2, text=arg_0.text) for arg_2 in arg_1]


def Func(arg_0):
        """Map byte offsets to line numbers in `code`.

        Uses co_lnotab described in Python/compile.c to map byte offsets to
        line numbers.  Produces a sequence: (b0, l0), (b1, l1), ...

        Only byte offsets that correspond to line numbers are included in the
        results.

        """
        # Adapted from dis.py in the standard library.
        arg_1 = bytes_to_ints(arg_0.code.co_lnotab[0::2])
        arg_2 = bytes_to_ints(arg_0.code.co_lnotab[1::2])

        arg_3 = None
        arg_4 = arg_0.code.co_firstlineno
        arg_5 = 0
        for arg_6, arg_7 in zip(arg_1, arg_2):
            if arg_6:
                if arg_4 != arg_3:
                    yield (arg_5, arg_4)
                    arg_3 = arg_4
                arg_5 += arg_6
            arg_4 += arg_7
        if arg_4 != arg_3:
            yield (arg_5, arg_4)


def Func(arg_0, arg_1):
        """Validate the rule that chunks have a single entrance."""
        # starts is the entrances to the chunks
        arg_2 = set([arg_3.byte for arg_3 in arg_1])
        for arg_3 in arg_1:
            assert all([(arg_4 in arg_2 or arg_4 < 0) for arg_4 in arg_3.exits])


def Func(arg_0):
        """Returns a list of `Chunk` objects for this code and its children.

        See `_split_into_chunks` for details.

        """
        arg_1 = []
        for arg_2 in arg_0.child_parsers():
            arg_1.extend(arg_2._split_into_chunks())

        return arg_1


def Func(arg_0):
        """Get the set of all arcs in this code object and its children.

        See `_arcs` for details.

        """
        arg_1 = set()
        for arg_2 in arg_0.child_parsers():
            arg_1.update(arg_2._arcs())

        return arg_1


def Func(arg_0=None, arg_1=None, arg_2=True):
    """
    Use all decompressor possible to make the stream
    """
    return Guesser().Func(arg_0=arg_0, arg_1=arg_1, arg_2=arg_2)


def Func(arg_0, arg_1, arg_2):
        """
        Add Func to command line.
        """
        super(Coverage, arg_0).Func(arg_1, arg_2)
        arg_1.add_option("--cover-package", action="append",
                          default=arg_2.get('NOSE_COVER_PACKAGE'),
                          metavar="PACKAGE",
                          dest="cover_packages",
                          help="Restrict coverage output to selected packages "
                          "[NOSE_COVER_PACKAGE]")
        arg_1.add_option("--cover-erase", action="store_true",
                          default=arg_2.get('NOSE_COVER_ERASE'),
                          dest="cover_erase",
                          help="Erase previously collected coverage "
                          "statistics before run")
        arg_1.add_option("--cover-tests", action="store_true",
                          dest="cover_tests",
                          default=arg_2.get('NOSE_COVER_TESTS'),
                          help="Include test modules in coverage report "
                          "[NOSE_COVER_TESTS]")
        arg_1.add_option("--cover-min-percentage", action="store",
                          dest="cover_min_percentage",
                          default=arg_2.get('NOSE_COVER_MIN_PERCENTAGE'),
                          help="Minimum percentage of coverage for tests"
                          "to pass [NOSE_COVER_MIN_PERCENTAGE]")
        arg_1.add_option("--cover-inclusive", action="store_true",
                          dest="cover_inclusive",
                          default=arg_2.get('NOSE_COVER_INCLUSIVE'),
                          help="Include all python files under working "
                          "directory in coverage report.  Useful for "
                          "discovering holes in test coverage if not all "
                          "files are imported by the test suite. "
                          "[NOSE_COVER_INCLUSIVE]")
        arg_1.add_option("--cover-html", action="store_true",
                          default=arg_2.get('NOSE_COVER_HTML'),
                          dest='cover_html',
                          help="Produce HTML coverage information")
        arg_1.add_option('--cover-html-dir', action='store',
                          default=arg_2.get('NOSE_COVER_HTML_DIR', 'cover'),
                          dest='cover_html_dir',
                          metavar='DIR',
                          help='Produce HTML coverage information in dir')
        arg_1.add_option("--cover-branches", action="store_true",
                          default=arg_2.get('NOSE_COVER_BRANCHES'),
                          dest="cover_branches",
                          help="Include branch coverage in coverage report "
                          "[NOSE_COVER_BRANCHES]")
        arg_1.add_option("--cover-xml", action="store_true",
                          default=arg_2.get('NOSE_COVER_XML'),
                          dest="cover_xml",
                          help="Produce XML coverage information")
        arg_1.add_option("--cover-xml-file", action="store",
                          default=arg_2.get('NOSE_COVER_XML_FILE', 'coverage.xml'),
                          dest="cover_xml_file",
                          metavar="FILE",
                          help="Produce XML coverage information in file")


def Func(arg_0, arg_1, arg_2=None):
        """If inclusive coverage enabled, return true for all source files
        in wanted packages.
        """
        if arg_0.coverInclusive:
            if arg_1.endswith(".py"):
                if arg_2 and arg_0.coverPackages:
                    for arg_3 in arg_0.coverPackages:
                        if arg_2.startswith(arg_3):
                            return True
                else:
                    return True
        return None


def Func(arg_0, arg_1, arg_2,
    arg_3=None, arg_4=arg_5, arg_6=None
):
    """Generate alternative interpretations of a source distro name

    Note: if `location` is a filesystem filename, you should call
    ``pkg_resources.normalize_path()`` on it before passing it to this
    routine!
    """
    # Generate alternative interpretations of a source distro name
    # Because some packages are ambiguous as to name/versions split
    # e.g. "adns-python-1.1.0", "egenix-mx-commercial", etc.
    # So, we generate each possible interepretation (e.g. "adns, python-1.1.0"
    # "adns-python, 1.1.0", and "adns-python-1.1.0, no version").  In practice,
    # the spurious interpretations should be ignored, because in the event
    # there's also an "adns" package, the spurious "python-1.1.0" version will
    # compare lower than any numeric version number, and is therefore unlikely
    # to match a request for it.  It's still a potential problem, though, and
    # in the long run PyPI and the distutils should go for "safe" names and
    # versions in distribution archive names (sdist and bdist).

    arg_7 = arg_1.split('-')
    if not arg_3:
        for arg_8,arg_9 in enumerate(arg_7[2:]):
            if len(arg_9)==5 and arg_9.startswith('py2.'):
                return # It's a bdist_dumb, not an sdist -- bail out

    for arg_9 in range(1,len(arg_7)+1):
        yield Distribution(
            arg_0, arg_2, '-'.join(arg_7[:arg_9]), '-'.join(arg_7[arg_9:]),
            arg_3=arg_3, arg_4 = arg_4,
            arg_6 = arg_6
        )


def Func(arg_0):
    """Open a urllib2 request, handling HTTP authentication"""

    arg_1, arg_2, arg_3, arg_4, arg_5, arg_6 = urlparse.urlparse(arg_0)

    # Double scheme does not raise on Mac OS X as revealed by a
    # failing test. We would expect "nonnumeric port". Refs #20.
    if arg_2.endswith(':'):
        raise httplib.InvalidURL("nonnumeric port: ''")

    if arg_1 in ('http', 'https'):
        arg_7, arg_8 = urllib2.splituser(arg_2)
    else:
        arg_7 = None

    if arg_7:
        arg_7 = "Basic " + _encode_auth(arg_7)
        arg_9 = urlparse.urlunparse((arg_1,arg_8,arg_3,arg_4,arg_5,arg_6))
        arg_10 = urllib2.Request(arg_9)
        arg_10.add_header("Authorization", arg_7)
    else:
        arg_10 = urllib2.Request(arg_0)

    arg_10.add_header('User-Agent', user_agent)
    arg_11 = urllib2.urlopen(arg_10)

    if arg_7:
        # Put authentication info back into request URL if same host,
        # so that links found on the page will work
        arg_12, arg_13, arg_14, arg_15, arg_16, arg_17 = urlparse.urlparse(arg_11.url)
        if arg_12==arg_1 and arg_13==arg_8:
            arg_11.url = urlparse.urlunparse((arg_12,arg_2,arg_14,arg_15,arg_16,arg_17))

    return arg_11


def Func(arg_0,
        arg_1, arg_2, arg_3=False, arg_4=False, arg_5=False,
        arg_6=None
    ):
        """Obtain a distribution suitable for fulfilling `requirement`

        `requirement` must be a ``pkg_resources.Requirement`` instance.
        If necessary, or if the `force_scan` flag is set, the requirement is
        searched for in the (online) package index as well as the locally
        installed packages.  If a distribution matching `requirement` is found,
        the returned distribution's ``location`` is the value you would have
        gotten from calling the ``download()`` method with the matching
        distribution's URL or filename.  If no matching distribution is found,
        ``None`` is returned.

        If the `source` flag is set, only source distributions and source
        checkout links will be considered.  Unless the `develop_ok` flag is
        set, development and system eggs (i.e., those using the ``.egg-info``
        format) will be ignored.
        """

        # process a Requirement
        arg_0.info("Searching for %s", arg_1)
        arg_7 = {}
        arg_8 = None

        def find(arg_9, arg_10=None):
            if arg_10 is None:
                arg_10 = arg_0
            # Find a matching distribution; may be called more than once

            for arg_8 in arg_10[arg_9.key]:

                if arg_8.precedence==DEVELOP_DIST and not arg_5:
                    if arg_8 not in arg_7:
                        arg_0.warn("Skipping development or system egg: %s",arg_8)
                        arg_7[arg_8] = 1
                    continue

                if arg_8 in arg_9 and (arg_8.precedence<=SOURCE_DIST or not arg_4):
                    arg_0.info("Best match: %s", arg_8)
                    return arg_8.clone(
                        location=arg_0.download(arg_8.location, arg_2)
                    )

        if arg_3:
            arg_0.prescan()
            arg_0.find_packages(arg_1)
            arg_8 = find(arg_1)

        if arg_6 is not None:
            arg_8 = arg_8 or find(arg_1, arg_6)

        if arg_8 is None and arg_0.to_scan is not None:
            arg_0.prescan()
            arg_8 = find(arg_1)

        if arg_8 is None and not arg_3:
            arg_0.find_packages(arg_1)
            arg_8 = find(arg_1)

        if arg_8 is None:
            arg_0.warn(
                "No local packages or download links found for %s%s",
                (arg_4 and "a source distribution of " or ""),
                arg_1,
            )
        return arg_8


def Func(arg_0):
    '''
    get parent from obj.
    '''
    arg_1 = arg_0.__qualname__.split('.')[:-1]
    if '<locals>' in arg_1: # locals function
        raise ValueError('cannot get parent from locals object.')
    arg_2 = sys.modules[arg_0.__module__]
    arg_3 = arg_2
    while arg_1:
        arg_3 = getattr(arg_3, arg_1.pop(0))
    return arg_3


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
    """Manage a Marv site"""
    if arg_1 is None:
        arg_5 = os.path.abspath(os.path.curdir)
        while arg_5 != os.path.sep:
            arg_1 = os.path.join(arg_5, 'Func.conf')
            if os.path.exists(arg_1):
                break
            arg_5 = os.path.dirname(arg_5)
        else:
            arg_1 = '/etc/Func/Func.conf'
            if not os.path.exists(arg_1):
                arg_1 = None
    arg_0.obj = arg_1
    setup_logging(arg_2, arg_4, arg_3)


def Func(arg_0):
        """this is a property, in case the handler is created
        before the engine gets registered with an id"""
        if isinstance(getattr(arg_0.engine, 'id', None), int):
            return "engine.%i"%arg_0.engine.id
        else:
            return "engine"


def Func(arg_0, arg_1):
    """ renders context aware template """
    arg_2 = Template(arg_0).render(Context(arg_1))
    return arg_2


def Func(arg_0, arg_1):
        """Add a function to the function list, in order."""
        arg_1 = arg_1.strip()
        try:
            arg_2 = get_function(arg_1)
        except Exception, exc:
            arg_0.wfile.write(js_error(exc) + NEWLINE)
            return
        # This tests to see if the function has been decorated with the view
        # server synchronisation decorator (``decorate_view``).
        if not getattr(arg_2, 'view_decorated', None):
            arg_0.functions[arg_1] = (arg_0.function_counter, arg_2)
        # The decorator gets called with the logger function.
        else:
            arg_0.functions[arg_1] = (arg_0.function_counter,
                arg_2(arg_0.log))
        arg_0.function_counter += 1
        return True


def Func(arg_0, arg_1):
        """Return the mapping of a document according to the function list."""
        # This uses the stored set of functions, sorted by order of addition.
        for arg_2 in sorted(arg_0.functions.values(), key=lambda x: x[0]):
            try:
                # It has to be run through ``list``, because it may be a
                # generator function.
                yield [list(arg_2(arg_1))]
            except Exception, exc:
                # Otherwise, return an empty list and log the event.
                yield []
                arg_0.log(repr(exc))


def Func(arg_0, arg_1, arg_2):
        """Re-reduce a set of values, with a list of rereduction functions."""
        # This gets a large list of reduction functions, given their names.
        arg_3 = []
        for arg_4 in arg_1:
            try:
                arg_5 = get_function(arg_4)
                if getattr(arg_5, 'view_decorated', None):
                    arg_5 = arg_5(arg_0.log)
                arg_3.append(arg_5)
            except Exception, exc:
                arg_0.log(repr(exc))
                arg_3.append(lambda *args, **kwargs: None)
        # This gets the list of results from those functions.
        arg_6 = []
        for arg_5 in arg_3:
            try:
                arg_6.append(arg_5(None, arg_2, rereduce=True))
            except Exception, exc:
                arg_0.log(repr(exc))
                arg_6.append(None)
        return [True, arg_6]


def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Validate...this function is undocumented, but still in CouchDB."""
        try:
            arg_5 = get_function(arg_1)
        except Exception, exc:
            arg_0.log(repr(exc))
            return False
        try:
            return arg_5(arg_2, arg_3, arg_4)
        except Exception, exc:
            arg_0.log(repr(exc))
            return repr(exc)


def Func(arg_0):
        """The main function called to Func a request."""
        while True:
            try:
                arg_1 = arg_0.rfile.readline()
                try:
                    # All input data are lines of JSON like the following:
                    #   ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ...]
                    # So I Func this by dispatching to various methods.
                    arg_2 = json.loads(arg_1)
                except Exception, exc:
                    # Sometimes errors come up. Once again, I can't predict
                    # anything, but can at least tell CouchDB about the error.
                    arg_0.wfile.write(repr(exc) + NEWLINE)
                    continue
                else:
                    # Automagically get the command Funcr.
                    arg_3 = getattr(arg_0, 'Func_' + arg_2[0], None)
                    if not arg_3:
                        # We are ready to not find commands. It probably won't
                        # happen, but fortune favours the prepared.
                        arg_0.wfile.write(
                            repr(CommandNotFound(arg_2[0])) + NEWLINE)
                        continue
                    arg_4 = arg_3(*arg_2[1:])
                    if not arg_4:
                        continue
                    # We write the output back to CouchDB.
                    arg_0.wfile.write(
                        one_lineify(json.dumps(arg_4)) + NEWLINE)
            except Exception, exc:
                arg_0.wfile.write(repr(exc) + NEWLINE)
                continue


def Func(arg_0, arg_1):
        """Log an event on the CouchDB server."""
        arg_0.wfile.write(json.dumps({'Func': arg_1}) + NEWLINE)


def Func(arg_0, arg_1):
    """ Turn a list to list of list """
    return [arg_0[arg_2:arg_2 + arg_1] for arg_2 in range(0, len(arg_0), arg_1)]


def Func(*arg_0):
    """
    Generates a universally unique ID.
    Any arguments only create more randomness.
    """
    arg_1 = float(time.time() * 1000)
    arg_2 = float(random.random()*10000000000000)

    arg_3 = random.random() * 10000000000000
    arg_4 = str(arg_1) + ' ' + str(arg_2) + ' ' + str(arg_3) + ' ' + str(arg_0)
    arg_4 = hashlib.md5(arg_4.encode()).hexdigest()[:10]

    return arg_4


def Func(arg_0):
    """Convert a hex color to rgb integer tuple."""
    if arg_0.startswith('#'):
        arg_0 = arg_0[1:]
    if len(arg_0) == 3:
        arg_0 = ''.join([c*2 for c in arg_0])
    if len(arg_0) != 6:
        return False
    try:
        arg_1 = int(arg_0[:2],16)
        arg_2 = int(arg_0[2:4],16)
        arg_3 = int(arg_0[4:],16)
    except ValueError:
        return False
    else:
        return arg_1,arg_2,arg_3


def Func(arg_0):
    """Construct the keys to be used building the base stylesheet
    from a templatee."""
    arg_1 = get_style_by_name(arg_0)
    arg_2 = arg_1.style_for_token(Token.Text)['color'] or ''
    if len(arg_2) in (3,6):
        # could be 'abcdef' or 'ace' hex, which needs '#' prefix
        try:
            int(arg_2, 16)
        except TypeError:
            pass
        else:
            arg_2 = "#"+arg_2

    return dict(
        bgcolor = arg_1.background_color,
        select = arg_1.highlight_color,
        arg_2 = arg_2
    )


def Func(arg_0, arg_1, arg_2):
        '''
        Func removes the access token from the data_store
        '''
        yield Task(arg_0.data_store.remove, 'tokens', arg_1=arg_1)
        arg_2()


def Func(arg_0, arg_1, arg_2, arg_3):
        '''
        Func - internal method for verifying the the given nonce.
        also removes the nonce from the data_store, as they are intended for
        one-time use.
        '''
        arg_4 = yield Task(arg_0.data_store.fetch, 'nonce_codes', arg_1=arg_1)
        if not arg_4:
            raise Proauth2Error('access_denied', 'invalid request code: %s' % arg_1)
        if arg_2 != arg_4['client_id']:
            raise Proauth2Error('access_denied', 'invalid request code: %s' % arg_1)
        arg_5 = arg_4['user_id']
        arg_6 = arg_4['expires']
        yield Task(arg_0.data_store.remove, 'nonce_codes', arg_1=arg_1,
                   arg_2=arg_2, arg_5=arg_5)

        if time() > arg_6:
            raise Proauth2Error('access_denied', 'request code %s expired' % arg_1)

        arg_3(arg_5)


def Func(arg_0, arg_1=32):
        '''
        Func - internal function for generating randomized alphanumberic
        strings of a given length
        '''
        return ''.join(choice(ascii_letters + digits) for arg_2 in range(arg_1))


def Func(arg_0, arg_1=None):
    """Return a font of the requested family, using fallback as alternative.

    If a fallback is provided, it is used in case the requested family isn't
    found.  If no fallback is given, no alternative is chosen and Qt's internal
    algorithms may automatically choose a fallback font.

    Parameters
    ----------
    family : str
      A font name.
    fallback : str
      A font name.

    Returns
    -------
    font : QFont object
    """
    arg_2 = QtGui.QFont(arg_0)
    # Check whether we got what we wanted using QFontInfo, since exactMatch()
    # is overly strict and returns false in too many cases.
    arg_3 = QtGui.QFontInfo(arg_2)
    if arg_1 is not None and arg_3.family() != arg_0:
        arg_2 = QtGui.QFont(arg_1)
    return arg_2


def Func(arg_0, arg_1):
        """ Implemented to handle history tail replies, which are only supported
            by the IPython kernel.
        """
        arg_2 = arg_1['content']
        if 'history' not in arg_2:
            arg_0.log.error("History request failed: %r"%arg_2)
            if arg_2.get('status', '') == 'aborted' and \
                                            not arg_0._retrying_history_request:
                # a *different* action caused this request to be aborted, so
                # we should try again.
                arg_0.log.error("Retrying aborted history request")
                # prevent multiple retries of aborted requests:
                arg_0._retrying_history_request = True
                # wait out the kernel's queue flush, which is currently timed at 0.1s
                time.sleep(0.25)
                arg_0.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000)
            else:
                arg_0._retrying_history_request = False
            return
        # reset retry flag
        arg_0._retrying_history_request = False
        arg_4 = arg_2['history']
        arg_0.log.debug("Received history reply with %i entries", len(arg_4))
        arg_5 = []
        arg_6 = u""
        for arg_7, arg_7, arg_8 in arg_4:
            arg_8 = arg_8.rstrip()
            if arg_8 != arg_6:
                arg_5.append(arg_8)
                arg_6 = arg_8
        arg_0._set_history(arg_5)


def Func(arg_0, arg_1):
        """ Reimplemented for IPython-style "display hook".
        """
        arg_0.log.debug("pyout: %s", arg_1.get('content', ''))
        if not arg_0._hidden and arg_0._is_from_this_session(arg_1):
            arg_2 = arg_1['content']
            arg_3 = arg_2.get('execution_count', 0)
            arg_4 = arg_2['data']
            if arg_4.has_key('text/html'):
                arg_0._append_plain_text(arg_0.output_sep, True)
                arg_0._append_html(arg_0._make_out_prompt(arg_3), True)
                arg_5 = arg_4['text/html']
                arg_0._append_plain_text('\n', True)
                arg_0._append_html(arg_5 + arg_0.output_sep2, True)
            elif arg_4.has_key('text/plain'):
                arg_0._append_plain_text(arg_0.output_sep, True)
                arg_0._append_html(arg_0._make_out_prompt(arg_3), True)
                arg_6 = arg_4['text/plain']
                # If the repr is multiline, make sure we start on a new line,
                # so that its lines are aligned.
                if "\n" in arg_6 and not arg_0.output_sep.endswith("\n"):
                    arg_0._append_plain_text('\n', True)
                arg_0._append_plain_text(arg_6 + arg_0.output_sep2, True)