Add some bundle to build group

        :type bundle: static_bundle.bundles.AbstractBundle
        @rtype: BuildGroup


Return collected files links

        :rtype: list[static_bundle.files.StaticFileResult]


Render all includes in asset by names

        :type name: str|unicode
        :rtype: str|unicode


Return links without build files


Write the collected coverage data to a file.

        `suffix` is a suffix to append to the base file name. This can be used
        for multiple or parallel execution, so that many coverage data files
        can exist simultaneously.  A dot will be used to join the base name and
        the suffix.


Erase the data, both in this object, and from its file storage.


Return the map from filenames to lists of line numbers executed.


Return the map from filenames to lists of line number pairs.


Write the coverage data to `filename`.


Combine a number of data files together.

        Treat `self.filename` as a file prefix, and combine the data from all
        of the data files starting with that prefix plus a dot.

        If `aliases` is provided, it's a `PathAliases` object that is used to
        re-map paths to match the local machine's.


Add executed line data.

        `line_data` is { filename: { lineno: None, ... }, ...}


Return a dict summarizing the coverage data.

        Keys are based on the filenames, and values are the number of executed
        lines.  If `fullpath` is true, then the keys are the full pathnames of
        the files, otherwise they are the basenames of the files.


Coerce everything to strings.
    All objects representing time get output according to default_date_fmt.


Initialize the zlogger.

    Sets up a rotating file handler to the specified path and file with
    the given size and backup count limits, sets the default
    application_name, server_hostname, and default/whitelist fields.

    :param path: path to write the log file
    :param target: name of the log file
    :param logger_name: name of the logger (defaults to root)
    :param level: log level for this logger (defaults to logging.DEBUG)
    :param maxBytes: size of the file before rotation (default 1MB)
    :param application_name: app name to add to each log entry
    :param server_hostname: hostname to add to each log entry
    :param fields: default/whitelist fields.
    :type path: string
    :type target: string
    :type logger_name: string
    :type level: int
    :type maxBytes: int
    :type backupCount: int
    :type application_name: string
    :type server_hostname: string
    :type fields: dict


Yield pasted lines until the user enters the given sentinel value.


Start the mainloop.

        If an optional banner argument is given, it will override the
        internally created default banner.


Store multiple lines as a single entry in history


Write a prompt and read a line.

        The returned line does not include the trailing newline.
        When the user enters the EOF key sequence, EOFError is raised.

        Optional inputs:

          - prompt(''): a string to be printed to prompt the user.

          - continue_prompt(False): whether this line is the first one or a
          continuation in a sequence of inputs.


The bottom half of the syntax error handler called in the main loop.

        Loop until syntax error is fixed or user cancels.


Utility routine for edit_syntax_error


Handle interactive exit.

        This method calls the ask_exit callback.


Returns the correct repository URL and revision by parsing the given
        repository URL


Create and return new frontend attached to new kernel, launched on localhost.


return the connection info for this object's sockets.


Convert an object in R's namespace to one suitable
    for ipython's namespace.

    For a data.frame, it tries to return a structured array.
    It first checks for colnames, then names.
    If all are NULL, it returns np.asarray(Robj), else
    it tries to construct a recarray

    Parameters
    ----------

    Robj: an R object returned from rpy2


Toggle between the currently active color scheme and NoColor.


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.


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


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


Only print the exception type and message, without a traceback.

        Parameters
        ----------
        etype : exception type
        value : exception value


Switch to the desired mode.

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


View decorator for requiring a user group.


Initialize the model for a Pyramid app.

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


Handle 'from module import a, b, c' imports.


Add a line of source to the code.

        Don't include indentations or newlines.


Generate a Python expression for `expr`.


Render this template by applying it to `context`.

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


Evaluate dotted expressions at runtime.


A shortcut function to render a partial template with context and return
    the output.


Activate the default formatters.


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.


Return absolute and relative path for file

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


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.


Configure the working directory or directories for the test run.


Very dumb 'pager' in Python, for when nothing else works.

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


Page a file, using an optional pager command and starting line.


Return a pager command.

    Makes some attempts at finding an OS-correct one.


Return the string for paging files with an offset.

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


A function to pretty print sympy Basic objects.


A function to display sympy expression using display style LaTeX in PNG.


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.


A function to generate the latex representation of sympy
    expressions.


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.


Validate that the input is a list of strings.

    Raises ValueError if not.


Validate that the input is a dict with string keys and values.

    Raises ValueError if not.


Run my loop, ignoring EINTR events in the poller


callback for stream.on_recv

        unpacks message, and calls handlers with it.


Execute code in the kernel.

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

        silent : bool, optional (default False)
            If set, the kernel will execute 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.


Tab complete text in the kernel's namespace.

        Parameters
        ----------
        text : str
            The text to complete.
        line : str
            The full line of text that is the surrounding context for the
            text to complete.
        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.


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.


Request an immediate kernel shutdown.

        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.


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 flushing, in seconds. The
            default is one second.


Send a string of raw input to the kernel.


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.


Are any of the channels created and running?


load connection info from JSON dict in self.connection_file


Attempts to the stop the kernel process cleanly. If the kernel
        cannot be stopped, it is killed, if possible.


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.


Kill the running kernel.


Interrupts the kernel. Unlike ``signal_kernel``, this operation is
        well supported on all platforms.


Sends a signal to the kernel. Note that since only SIGTERM is
        supported on Windows, this function is only useful on Unix systems.


Get the REQ socket channel object to make requests of the kernel.


Get the SUB socket channel object.


Get the heartbeat socket channel object to check that the
        kernel is alive.


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.


Emit a debugging message depending on the debugging level.

        :param level: The debugging level.
        :param message: The message to emit.


Retrieve the extension classes in priority order.

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


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.


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.


Adds an EnumDescriptor to the pool.

    This method also registers the FileDescriptor associated with the message.

    Args:
      enum_desc: An EnumDescriptor.


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.


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


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


Check whether module possibly uses unsafe-for-zipfile stuff


Create and run the IPython controller


save a connection dict to json file.


load config from existing json connector files.


secondary config, loading from JSON and setting defaults


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 = get_tm_session(session_factory, transaction.manager)


Enable %autopx mode by saving the original run_cell and installing
        pxrun_cell.


Disable %autopx by restoring the original InteractiveShell.run_cell.


drop-in replacement for InteractiveShell.run_cell.

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

        See InteractiveShell.run_cell for details.


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.


Patch a method onto an object if it isn't already there.


Accept a pending connection.


Reject a pending connection.


Calls pre and post save hooks.


Use SaveHookMixin pre_save to set the user.


Check whether some modules need to be reloaded.


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).


Get text from the clipboard.


Add a func to the cmd chain with given priority


Configure which kinds of exceptions trigger plugin.


Import and return bar given the string foo.bar.


Forces a flush from the internal queue to the server


Try passwordless login with shell ssh command.


Try passwordless login with paramiko.


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.


unwrap exception, and remap engine_id to int.


Register a new engine, and update our connection info.


Flush task or queue results waiting in ZMQ queue.


Flush replies from the iopub channel waiting
        in the ZMQ queue.


target func for use in spin_thread


Flush any registration notifications and execution results
        waiting in the ZMQ queue.


construct and send an apply message via a socket.

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


construct and send an execute request via a socket.


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


Return a set of opcodes by the names in `names`.


Parse the source to find the interesting facts about its lines.

        A handful of member fields are updated.


Return the first line number of the statement including `line`.


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.


Get information about the arcs available in the code.

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


Get a mapping from line numbers to count of exits from that line.

        Excluded lines are excluded.


Iterate over all the code objects nested within this one.

        The iteration includes `self` as its first value.


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.


Validate the rule that chunks have a single entrance.


Returns a list of `Chunk` objects for this code and its children.

        See `_split_into_chunks` for details.


Get the set of all arcs in this code object and its children.

        See `_arcs` for details.


Use all decompressor possible to make the stream


Add options to command line.


If inclusive coverage enabled, return true for all source files
        in wanted packages.


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!


Open a urllib2 request, handling HTTP authentication


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.


get parent from obj.


Manage a Marv site


this is a property, in case the handler is created
        before the engine gets registered with an id


renders context aware template


Add a function to the function list, in order.


Return the mapping of a document according to the function list.


Re-reduce a set of values, with a list of rereduction functions.


Validate...this function is undocumented, but still in CouchDB.


The main function called to handle a request.


Log an event on the CouchDB server.


Turn a list to list of list


Generates a universally unique ID.
    Any arguments only create more randomness.


Convert a hex color to rgb integer tuple.


Construct the keys to be used building the base stylesheet
    from a templatee.


revoke_token removes the access token from the data_store


_validate_request_code - internal method for verifying the the given nonce.
        also removes the nonce from the data_store, as they are intended for
        one-time use.


_generate_token - internal function for generating randomized alphanumberic
        strings of a given length


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


Implemented to handle history tail replies, which are only supported
            by the IPython kernel.


Reimplemented for IPython-style "display hook".


Reimplemented to make a history request and load %guiref.


Reimplemented for IPython-style traceback formatting.


Reimplemented to dispatch payloads to handler methods.


Sets the widget style to the class defaults.

        Parameters:
        -----------
        colors : str, optional (default lightbg)
            Whether to use the default IPython light background or dark
            background or B&W style.


Opens a Python script for editing.

        Parameters:
        -----------
        filename : str
            A path to a local system file.

        line : int, optional
            A line of interest in the file.


Set the style sheets of the underlying widgets.


Set the style for the syntax highlighter.


Handles the response returned from the CloudStack API. Some CloudStack API are implemented asynchronous, which
        means that the API call returns just a job id. The actually expected API response is postponed and a specific
        asyncJobResults API has to be polled using the job id to get the final result once the API call has been
        processed.

        :param response: The response returned by the aiohttp call.
        :type response: aiohttp.client_reqrep.ClientResponse
        :param await_final_result: Specifier that indicates whether the function should poll the asyncJobResult API
                                   until the asynchronous API call has been processed
        :type await_final_result: bool
        :return: Dictionary containing the JSON response of the API call
        :rtype: dict


According to the CloudStack documentation, each request needs to be signed in order to authenticate the user
        account executing the API command. The signature is generated using a combination of the api secret and a SHA-1
        hash of the url parameters including the command string. In order to generate a unique identifier, the url
        parameters have to be transformed to lower case and ordered alphabetically.

        :param url_parameters: The url parameters of the API call including the command string
        :type url_parameters: dict
        :return: The url parameters including a new key, which contains the signature
        :rtype: dict


Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating
        the API that originated the response. This function removes that first level from the data returned to the
        caller.

        :param data: Response of the API call
        :type data: dict
        :return: Simplified response without the information about the API that originated the response.
        :rtype: dict


System virtual memory as a namedutple.


Return system per-CPU times as a named tuple


Return real, effective and saved group ids.


Return the number of threads belonging to the process.


Return files opened by process as a list of namedtuples.


Return dict describing the context of this package

    Parameters
    ----------
    pkg_path : str
       path containing __init__.py for package

    Returns
    -------
    context : dict
       with named parameters of interest


Return useful information about IPython and the system, as a string.

    Example
    -------
    In [2]: print sys_info()
    {'commit_hash': '144fdae',      # random
     'commit_source': 'repository',
     'ipython_path': '/home/fperez/usr/lib/python2.6/site-packages/IPython',
     'ipython_version': '0.11.dev',
     'os_name': 'posix',
     'platform': 'Linux-2.6.35-22-generic-i686-with-Ubuntu-10.10-maverick',
     'sys_executable': '/usr/bin/python',
     'sys_platform': 'linux2',
     'sys_version': '2.6.6 (r266:84292, Sep 15 2010, 15:52:39) \\n[GCC 4.4.5]'}


Return the number of active CPUs on a Darwin system.


Return the effective number of CPUs in the system as an integer.

   This cross-platform function makes an attempt at finding the total number of
   available CPUs in the system, as returned by various underlying system and
   python calls.

   If it can't find a sensible answer, it returns 1 (though an error *may* make
   it return a large positive number that's actually incorrect).


Fetches a single row from the cursor.


this function will be called on the engines


Read a .py notebook from a string and return the NotebookNode object.


Read a notebook from a string and return the NotebookNode object.

    This function properly handles notebooks of any version. The notebook
    returned will always be in the current version's format.

    Parameters
    ----------
    s : unicode
        The raw unicode string to read the notebook from.
    format : (u'json', u'ipynb', u'py')
        The format that the string is in.

    Returns
    -------
    nb : NotebookNode
        The notebook that was read.


Convert to a notebook having notebook metadata.


Helps us validate the parameters for the request

    :param valid_options: a list of strings of valid options for the
                          api request
    :param params: a dict, the key-value store which we really only care about
                   the key which has tells us what the user is using for the
                   API request

    :returns: None or throws an exception if the validation fails


Does the name match my requirements?

        To match, a name must match config.testMatch OR config.include
        and it must not match config.exclude


Is the class a wanted test class?

        A class must be a unittest.TestCase subclass, or match test name
        requirements. Classes that start with _ are always excluded.


Is the file a wanted test file?

        The file must be a python source file and match testMatch or
        include, and not match exclude. Files that match ignore are *never*
        wanted, regardless of plugin, testMatch, include or exclude settings.


Is the method a test method?


Is the module a test module?

        The tail of the module name must match test requirements. One exception:
        we always want __main__.


Get current datetime for every file.


List command to use if we have a newer pydb installed


The printing (as opposed to the parsing part of a 'list'
        command.


Generates a multiplying factor used to convert two currencies


Converts an amount of money from one currency to another on a specified date.


Return the given stream's encoding or a default.

    There are cases where sys.std* might not actually be a stream, so
    check for the encoding attribute prior to returning it, and return
    a default if it doesn't exist or evaluates as False. `default'
    is None if not provided.


run your main spider here
        as for branch spider result data, you can return everything or do whatever with it
        in your own code

        :return: None


Read version info from a file without importing it


start the heart beating


Redirect input streams and set a display hook.


Create the Kernel object itself


construct connection function, which handles tunnels.


Returns the root if this is a nested type, or itself if its the root.


Searches for the specified method, and returns its descriptor.


Define the command line options for the plugin.


Check if directory is eligible for test discovery


Converts protobuf message to JSON format.

  Args:
    message: The protocol buffers message instance to serialize.
    including_default_value_fields: If True, singular primitive fields,
        repeated fields, and map fields will always be serialized.  If
        False, only serialize non-empty fields.  Singular message fields
        and oneof fields are not affected by this option.

  Returns:
    A string containing the JSON formatted protocol buffer message.


Parses a JSON representation of a protocol message into a message.

  Args:
    text: Message JSON representation.
    message: A protocol beffer message to merge into.

  Returns:
    The same message passed as argument.

  Raises::
    ParseError: On JSON parsing problems.


Convert a JSON object into a message.

  Args:
    value: A JSON object.
    message: A WKT or regular protocol message to record the data.

  Raises:
    ParseError: In case of convert problems.


Convert a JSON representation into Value message.


Convert a JSON representation into Struct message.


Return true if 'ext' links to a dynamic lib in the same package


call each func from func list.

    return the last func value or None if func list is empty.


ensure there is only one newline between usage and the first heading
        if there is no description


Update config options with the provided dictionary of options.


initialize the app


Get the pid from the pid file.

        If the  pid file doesn't exist a :exc:`PIDFileError` is raised.


Construct an argument parser using the function decorations.


Find the real name of the magic.


Highlight a block of text. Reimplemented to highlight selectively.


Reimplemented to temporarily enable highlighting if disabled.


Reimplemented to highlight selectively.


Copy the currently selected text to the clipboard, removing prompts.


Called immediately after a prompt is finished, i.e. when some input
            will be processed and a new prompt displayed.


Reimplemented for auto-indentation.


Handle replies for tab completion.


Silently execute `expr` in the kernel and call `callback` with reply

        the `expr` is evaluated silently in the kernel (without) output in
        the frontend. Call `callback` with the
        `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument

        Parameters
        ----------
        expr : string
            valid string to be executed by the kernel.
        callback : function
            function accepting one argument, as a string. The string will be
            the `repr` of the result of evaluating `expr`

        The `callback` is called with the `repr()` of the result of `expr` as
        first argument. To get the object, do `eval()` on the passed value.

        See Also
        --------
        _handle_exec_callback : private method, deal with calling callback with reply


Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``

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

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


Handles replies for code execution.


Handle requests for raw_input.


Handle shutdown signal, only if from other console.


Attempts to execute file with 'path'. If 'hidden', no output is
            shown.


Attempts to interrupt the running kernel.

        Also unsets _reading flag, to avoid runtime errors
        if raw_input is called again.


Resets the widget to its initial state if ``clear`` parameter or
        ``clear_on_kernel_restart`` configuration setting is True, otherwise
        prints a visual indication of the fact that the kernel restarted, but
        does not clear the traces from previous usage of the kernel before it
        was restarted.  With ``clear=True``, it is similar to ``%clear``, but
        also re-writes the banner and aborts execution if necessary.


Process a reply for an execution request that resulted in an error.


Process a reply for a successful execution request.


Called whenever the document's content changes. Display a call tip
            if appropriate.


Add plugin to my list of plugins to call, if it has the attribute
        I'm bound to.


Call all plugins, returning the first non-None result.


Load plugins by iterating the `nose.plugins` entry point.


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

    Parameters
    ----------
    s : str
        The raw string containing valid inline LateX.
    alt : str
        The alt text to use for the HTML.


Given a math expression, renders it in a closely-clipped bounding
    box to an image file.

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

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

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

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

    *format*
       The output format, eg. 'svg', 'pdf', 'ps' or 'png'.  If not
       provided, will be deduced from the filename.


Completes measuring time interval and updates counter.


Return a generator yielding a Process class instance for all
    running processes on the local machine.

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

    The sorting order in which processes are yielded is based on
    their PIDs.


Utility method returning process information as a hashable
        dictionary.

        If 'attrs' is specified it must be a list of strings reflecting
        available Process class's attribute names (e.g. ['get_cpu_times',
        'name']) else all public (read only) attributes are assumed.

        'ad_value' is the value which gets assigned to a dict key in case
        AccessDenied exception is raised when retrieving that particular
        process information.


The process name.


The process executable path. May also be an empty string.


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

        When interval is > 0.0 compares process times to system CPU
        times elapsed before and after the interval (blocking).

        When interval is 0.0 or None compares process times to system CPU
        times elapsed since last call, returning immediately.
        In this case is recommended for accuracy that this function be
        called with at least 0.1 seconds between calls.


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

        If 'grouped' is True the mapped regions with the same 'path'
        are grouped together and the different memory fields are summed.

        If 'grouped' is False every mapped region is shown as a single
        entity and the namedtuple will also include the mapped region's
        address space ('addr') and permission set ('perms').


Return whether this process is running.


Resume process execution.


Wait for process to terminate and, if process is a children
        of the current one also return its exit code, else None.


Converts Duration to string format.

    Returns:
      A string converted from self. The string format will contains
      3, 6, or 9 fractional digits depending on the precision required to
      represent the exact Duration value. For example: "1s", "1.010s",
      "1.000000100s", "-3.100s"


Initializes the kernel inside GTK.

        This is meant to run only once at startup, so it does its job and
        returns False to ensure it doesn't get run again by GTK.


Hijack a few key functions in GTK for IPython integration.

        Modifies pyGTK's main and main_quit with a dummy so user code does not
        block IPython.  This allows us to use %run to run arbitrary pygtk
        scripts from a long-lived IPython session, and when they attempt to
        start or stop

        Returns
        -------
        The original functions that have been hijacked:
        - gtk.main
        - gtk.main_quit


Is the given identifier defined in one of the namespaces which shadow
    the alias and magic namespaces?  Note that an identifier is different
    than ifun, because it can not contain a '.' character.


Create the default transformers.


Register a transformer instance.


Unregister a transformer instance.


Create the default checkers.


Register a checker instance.


Create the default handlers.


Register a handler instance by name with esc_strings.


Unregister a handler instance by name with esc_strings.


Calls the enabled transformers in order of increasing priority.


Prefilter multiple input lines of text.

        This is the main entry point for prefiltering multiple lines of
        input.  This simply calls :meth:`prefilter_line` for each line of
        input.

        This covers cases where there are multiple lines in the user entry,
        which is the case when the user goes back to a multiline history
        entry and presses enter.


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


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


Handle alias input lines.


Execute the line in a shell, empty return value


Execute magic functions.


Handle lines which can be auto-executed, quoting if requested.


Try to get some help for the object.

        obj? or ?obj   -> basic information.
        obj?? or ??obj -> more details.


Reimplemented to hide on certain key presses and on text edit focus
            changes.


Reimplemented to cancel the hide timer.


Reimplemented to paint the background panel.


Attempts to show the specified call line and docstring at the
            current cursor location. The docstring is possibly truncated for
            length.


Attempts to show the specified tip at the current cursor location.


Create a property that proxies attribute ``proxied_attr`` through
    the local attribute ``local_attr``.


Canonicalizes a path relative to a given working directory.  That
    is, the path, if not absolute, is interpreted relative to the
    working directory, then converted to absolute form.

    :param cwd: The working directory.
    :param path: The path to canonicalize.

    :returns: The absolute path.


Schema validation helper.  Performs JSONSchema validation.  If a
    schema validation error is encountered, an exception of the
    designated class is raised with the validation error message
    appropriately simplified and passed as the sole positional
    argument.

    :param instance: The object to schema validate.
    :param schema: The schema to use for validation.
    :param exc_class: The exception class to raise instead of the
                      ``jsonschema.ValidationError`` exception.
    :param prefix: Positional arguments are interpreted as a list of
                   keys to prefix to the path contained in the
                   validation error.
    :param kwargs: Keyword arguments to pass to the exception
                   constructor.


Retrieve a read-only subordinate mapping.  All values are
        stringified, and sensitive values are masked.  The subordinate
        mapping implements the context manager protocol for
        convenience.


Return a CouchDB document, given its ID, revision and database name.


Give reST format README for pypi.


Return True if in a venv and no system site packages.


Parallel word frequency counter.

    view - An IPython DirectView
    fnames - The filenames containing the split data.


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

	Can't subclass the `View` as it breaks inheritance (super in particular),
	so we monkey-patch instead.

	Based on http://stackoverflow.com/a/8429311


Return list of shell aliases to auto-define.


Define a new alias after validating it.

        This will raise an :exc:`AliasError` if there are validation
        problems.


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


Transform alias to system command string.


Expand an alias in the command line

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

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


produces rst from nose help


Yields substrings for which the same escape code applies.


Returns a QColor for a given color code, or None if one cannot be
            constructed.


Returns a QTextCharFormat that encodes the current style attributes.


Generate a one-time jwt with an age in seconds


Run by housekeeper thread


Get common prefix for completions

    Return the longest common prefix of a list of strings, but with special
    treatment of escape characters that might precede commands in IPython,
    such as %magic functions. Used in tab completion.

    For a more general function, see os.path.commonprefix


Reimplemented to ensure a console-like behavior in the underlying
            text widgets.


Reimplemented to suggest a size that is 80 characters wide and
            25 lines high.


Returns whether text can be cut to the clipboard.


Returns whether text can be pasted from the clipboard.


Clear the console.

        Parameters:
        -----------
        keep_input : bool, optional (default True)
            If set, restores the old input buffer if a new prompt is written.


Executes source or the input buffer, possibly prompting for more
        input.

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

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

        hidden : bool, optional (default False)

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

        interactive : bool, optional (default False)

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

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

        Returns:
        --------
        A boolean indicating whether the source was executed.


Sets the text in the input buffer.

        If the console is currently executing, this call has no *immediate*
        effect. When the execution is finished, the input buffer will be updated
        appropriately.


Print the contents of the ConsoleWidget to the specified QPrinter.


Moves the prompt to the top of the viewport.


Sets the font to the default fixed-width font for this platform.


A low-level method for appending content to the end of the buffer.

        If 'before_prompt' is enabled, the content will be inserted before the
        current prompt, if there is one.


Appends HTML at the end of the console buffer.


Appends HTML, then returns the plain text version of it.


Appends plain text, processing ANSI codes if enabled.


Clears the "temporary text" buffer, i.e. all the text following
            the prompt region.


fill the area below the active editting zone with text


Filter key events for the paging widget to create console-like
            interface.


Convenience method that returns a cursor for the last character.


Convenience method that returns a cursor with text selected between
            the positions 'start' and 'end'.


Inserts plain text using the specified cursor, processing ANSI codes
            if enabled.


Ensures that the cursor is inside the editing region. Returns
            whether the cursor was moved.


Cancels the current editing task ala Ctrl-G in Emacs.


Displays text using the pager if it exceeds the height of the
        viewport.

        Parameters:
        -----------
        html : bool, optional (default False)
            If set, the text will be interpreted as HTML instead of plain text.


Called immediately after a new prompt is displayed.


Scrolls the viewport so that the specified cursor is at the top.


Expands the vertical scrollbar beyond the range set by Qt.


Copy a default config file into the active profile directory.

        Default configuration files are kept in :mod:`IPython.config.default`.
        This function moves these from that location to the working profile
        directory.


Create a profile dir by profile name and path.

        Parameters
        ----------
        path : unicode
            The path (directory) to put the profile directory in.
        name : unicode
            The name of the profile.  The name of the profile directory will
            be "profile_<profile>".


Convert a cmp= function into a key= function


Read a file and close it.  Returns the file source.


Take multiple lines of input.

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

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


Write data to both channels.


add a new handler for new hearts


add a new handler for heart failure


a heart just beat


Converts a list into a list of lists with equal batch_size.

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


Generator for walking a directory tree.
    Starts at specified root folder, returning files that match our pattern.
    Optionally will also recurse through sub-folders.

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

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


Extract configuration data from a bdist_wininst .exe

    Returns a ConfigParser.RawConfigParser, or None


Ensure that the importer caches dont have stale info for `path`


Verify that there are no conflicting "old-style" packages


When easy_install is about to run bdist_egg on a source dist, that
        source dist might have 'setup_requires' directives, requiring
        additional fetching. Ensure the fetcher options given to easy_install
        are available to that command as well.


Create directories under ~.


Return True if `name` is a considered as an archive file.


return a mutable proxy for the `obj`.

    all modify on the proxy will not apply on origin object.


return a readonly proxy for the `obj`.

    all modify on the proxy will not apply on origin object.


Create a new section cell with a given integer level.


Create a new metadata node.


Create a new author.


Whether `path` is a directory, to which the user has write access.


On Windows, remove leading and trailing quotes from filenames.


Return the 'home' directory, as a unicode string.

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

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

    Parameters
    ----------

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


Return the XDG_CONFIG_HOME, if it is defined and exists, else None.

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


Get the IPython directory for this platform and user.

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


Find the path to an IPython module in this version of IPython.

    This will always find the version of the module that is in this importable
    IPython package. This will always return the path to the ``.py``
    version of the module.


Determine whether a target is out of date.

    target_outdated(target,deps) -> 1/0

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

    If target doesn't exist or is older than any file listed in deps, return
    true, otherwise return false.


Make an MD5 hash of a file, ignoring any differences in line
    ending characters.


Check for old config files, and present a warning if they exist.

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

    This should mitigate confusion with the transition to the new
    config system in 0.11.


Updates the suggestions' dictionary for an object upon visiting its page


Return this path as a relative path,
        based from the current working directory.


Return a list of path objects that match the pattern.

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

        For example, path('/users').glob('*/bin/*') returns a list
        of all the files users have in their bin directories.


r""" Open this file, read all lines, return them in a list.

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

        This uses 'U' mode in Python 2.3 and later.


Enable event loop integration with PyGTK.

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

        Notes
        -----
        This methods sets the PyOS_InputHook for PyGTK, which allows
        the PyGTK to integrate with terminal based applications like
        IPython.


Connect to the database, and create tables if necessary.


Prepares and runs an SQL query for the history database.

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

        Returns
        -------
        Tuples as :meth:`get_range`


get info about a session

        Parameters
        ----------

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

        Returns
        -------

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

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


Get lines of history from a string of ranges, as used by magic
        commands %hist, %save, %macro, etc.

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

        Returns
        -------
        Tuples as :meth:`get_range`


Give the current session a name in the history database.


Clear the session history, releasing all object references, and
        optionally open a new session.


Write any entries in the cache to the database.


This can be called from the main thread to safely stop this thread.

        Note that it does not attempt to write out remaining history before
        exiting. That should be done by calling the HistoryManager's
        end_session method.


Return the number of CPUs on the system


Return a list of namedtuple representing the CPU times
    for every CPU available on the system.


Return mounted disk partitions as a list of nameduples


Make a nice string representation of a pair of numbers.

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


Return a string summarizing the call stack.


A decorator to cache the result of an expensive operation.

    Only applies to methods with no arguments.


Combine a list of regexes into one that matches any of them.


Remove a file, and don't get annoyed if it doesn't exist.


List all profiles in the ipython_dir and cwd.


Start a cluster for a given profile.


Stop a cluster for a given profile.


Find the full path to a .bat or .exe using the win32api module.


Callback for _system.


remove records from collection whose parameters match kwargs


Resolve the URL to this point.

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


Makes the HTTP request.


Run a reporting function on a number of morfs.

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

            report_fn(code_unit, analysis)

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


Call pdb.set_trace in the calling frame, first restoring
    sys.stdout to the real output stream. Note that sys.stdout is NOT
    reset to whatever it was before the call once pdb is done!


Test must finish within specified time limit to pass.

    Example use::

      @timed(.1)
      def test_that_fails():
          time.sleep(.2)


Load all IPython extensions in IPythonApp.extensions.

        This uses the :meth:`ExtensionManager.load_extensions` to load all
        the extensions listed in ``self.extensions``.


run the pre-flight code, specified via exec_lines


Run files from profile startup directory


Run files from IPythonApp.exec_files


Run code or file specified at the command-line


Run module specified at the command-line.


Return the contents of a data file of ours.


HTML-escape the text in `t`.


Generate an HTML report for `morfs`.

        `morfs` is a list of modules or filenames.


Make local instances of static files for HTML report.


Compute a hash that changes if the file needs to be re-reported.


Read the last status in `directory`.


Write the current status to `directory`.


Sort and compare two lists.

    By default it does it in place, thus modifying the lists. Use inplace = 0
    to avoid that (at the cost of temporary copy creation).


Get a slice of a sequence with variable step. Specify start,stop,step.


Read configuration from setup.cfg.


Read existing configuration from MANIFEST.in.

    We use that to ignore anything the MANIFEST.in ignores.


List all files versioned by git in the current directory.


Skips over a field value.

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

  Raises:
    ParseError: In case an invalid field value is found.


Parses an integer.

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

  Returns:
    The integer value.

  Raises:
    ValueError: Thrown Iff the text is not a valid integer.


Convert protobuf message to text format.

    Args:
      message: The protocol buffers message.


Merges a single scalar field into a message.

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

    Raises:
      ParseError: In case of text parsing problems.


Consume one token of a string literal.

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

    Returns:
      The token parsed.
    Raises:
      ParseError: When the wrong format data is found.


Shutdown a kernel by its kernel uuid.

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


Kill a kernel by its kernel uuid.

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


Return a dictionary of ports for a kernel.

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

        Returns
        =======
        port_dict : dict
            A dict of key, value pairs where the keys are the names
            (stdin_port,iopub_port,shell_port) and the values are the
            integer port numbers for those channels.


Start a kernel for a notebok an return its kernel_id.

        Parameters
        ----------
        notebook_id : uuid
            The uuid of the notebook to associate the new kernel with. If this
            is not None, this kernel will be persistent whenever the notebook
            requests a kernel.


Shutdown a kernel and remove its notebook association.


Interrupt a kernel.


Create a new iopub stream.


Create a new hb stream.


convert ark timestamp to unix timestamp


Reset all OneTimeProperty attributes that may have fired already.


Export the contents of the ConsoleWidget as HTML.

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

    filename : str
        The file to be saved.

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

    inline : bool, optional [default True]
        If True, include images as inline PNGs.  Otherwise, include them as
        links to external PNG files, mimicking web browsers' "Web Page,
        Complete" behavior.


Export the contents of the ConsoleWidget as XHTML with inline SVGs.

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

    filename : str
        The file to be saved.

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


Transforms a Qt-generated HTML string into a standards-compliant one.

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


Returns a unique instance of `klass` or None


Builds a query for included terms in a text search.


Builds a query for both included & excluded terms in a text search.


Query for if date_field is within number of "days" ago.


Converts queries to case insensitive for special fields.


Close the connection.


Register command line options


Verify whether a method has the required attributes
        The method is considered a match if it matches all attributes
        for any attribute group.
        .


Rotate the kill ring, then yank back the new top.


backport a few patches from newer pyzmq

    These can be removed as we bump our minimum pyzmq version


websocket url matching the current request

        turns http[s]://host[:port] into
                ws[s]://host[:port]


Reserialize a reply message using JSON.

        This takes the msg list from the ZMQ socket, unserializes it using
        self.session and then serializes the result using JSON. This method
        should be used by self._on_zmq_reply to build messages that can
        be sent back to the browser.


Inject the first message, which is the document cookie,
        for authentication.


callback for delayed heartbeat start

        Only start the hb loop if we haven't been closed during the wait.


Get the current block index, validating and checking status.

        Returns None if the demo is finished


Move the current seek pointer to the given block.

        You can use negative indices to seek from the end, with identical
        semantics to those of Python lists.


Show a single block on screen


Processes a collection in series

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

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

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

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

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


Processes a collection in parallel batches,
    each batch processes in series on a single process.
    Running batches in parallel can be more effficient that splitting a list across cores as in spin.parallel
    because of parallel processing has high IO requirements.

    Parameters
    ----------
    collection : list
        i.e. list of Record objects
    method : method to call on each Record
    processes : int
        number of processes to run on [defaults to number of cores on machine]
    batch_size : int
        lenght of each batch [defaults to number of elements / number of processes]

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

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

    >>> import turntable
    >>> collection = range(100)
    >>> def jam(record):
    >>>     return record + 2
    >>> collection = turntable.spin.batch(collection, jam)

    Note
    ----

    lambda functions do not work in parallel


Processes a collection in parallel.

    Parameters
    ----------
    collection : list
        i.e. list of Record objects
    method : method to call on each Record
    processes : int
        number of processes to run on [defaults to number of cores on machine]
    batch_size : int
        lenght of each batch [defaults to number of elements / number of processes]

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

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

    >>> import turntable
    >>> collection = range(100)
    >>> def jam(record):
    >>>     return record + 2
    >>> collection = turntable.spin.parallel(collection, jam)

    Note
    ----

    lambda functions do not work in parallel


Get source from  a traceback object.

    A tuple of two things is returned: a list of lines of context from
    the source code, and the index of the current line within that list.
    The optional second argument specifies the number of lines of context
    to return, which are centered around the current line.

    .. Note ::
       This is adapted from inspect.py in the python 2.4 standard library,
       since a bug in the 2.3 version of inspect prevents it from correctly
       locating source lines in a traceback frame.


Create a countdown.


Cleanup routine to shut down all subprocesses we opened.


A modifier hook function.  This is called in priority order prior
        to invoking the ``Action`` for the step.  This allows a
        modifier to alter the context, or to take over subsequent
        action invocation.

        :param ctxt: The context object.
        :param pre_mod: A list of the modifiers preceding this
                        modifier in the list of modifiers that is
                        applicable to the action.  This list is in
                        priority order.
        :param post_mod: A list of the modifiers following this
                         modifier in the list of modifiers that is
                         applicable to the action.  This list is in
                         priority order.
        :param action: The action that will be performed.

        :returns: A ``None`` return value indicates that the modifier
                  is taking no action.  A non-``None`` return value
                  should consist of a ``StepResult`` object; this will
                  suspend further ``pre_call()`` processing and
                  proceed to the ``post_call()`` processing.  This
                  implementation returns a ``StepResult`` with state
                  ``SKIPPED`` if the condition does not evaluate to
                  ``True``.


sync relevant results from self.client to our results attribute.


call spin after the method.


Get all messages that are currently ready.


Gets a message if there is one that is ready.


`get_onlys` is a sugar for multi-`property`.

    ``` py
    name, age = get_onlys('_name', '_age')

    # equals:

    @property
    def name(self):
        return getattr(self, '_name')

    @property
    def age(self):
        return getattr(self, '_age')
    ```


Parses a database URL.


Easily create a trivial completer for a command.

    Takes either a list of completions, or all completions in string (that will
    be split on whitespace).

    Example::

        [d:\ipython]|1> import ipy_completers
        [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
        [d:\ipython]|3> foo b<TAB>
        bar baz
        [d:\ipython]|3> foo ba


Returns a list containing the completion possibilities for an import line.

    The line looks like this :
    'import xml.d'
    'from xml.dom import'


Complete files that end in .py or .ipy for the %run command.


Completer function for cd, which only returns directories.


Append numbers in sequential order to the filename or folder name
	Numbers should be appended before the extension on a filename.


Set the modified time of a file


wrap a function that returns a dir, making sure it exists


Get closer to your EOL


Open a connection over the serial line and receive data lines


Escape an XML attribute. Value can be unicode.


Configures the xunit plugin.


Writes an Xunit-formatted XML file

        The file includes a report of test errors and failures.


Add error output to Xunit report.


Add failure output to Xunit report.


Add success output to Xunit report.


create & start main thread

        :return: None


Pick two at random, use the LRU of the two.

    The content of loads is ignored.

    Assumes LRU ordering of loads, with oldest first.


Pick two at random using inverse load as weight.

    Return the less loaded of the two.


Existing engine with ident `uid` became unavailable.


Deal with jobs resident in an engine that died.


Dispatch job submission to appropriate handlers.


Audit all waiting tasks for expired timeouts.


check location dependencies, and run if they are met.


Save a message for later submission when its dependencies are met.


dispatch method for result replies


handle a real task result, either success or failure


handle an unmet dependency


dep_id just finished. Update our dependency
        graph and submit any jobs that just became runable.

        Called with dep_id=None to update entire graph for hwm, but without finishing
        a task.


Generate a new log-file with a default header.

        Raises RuntimeError if the log has already been started


Write the sources to a log.

        Inputs:

        - line_mod: possibly modified input, such as the transformations made
        by input prefilters or input handlers of various kinds.  This should
        always be valid Python.

        - line_ori: unmodified input line from the user.  This is not
        necessarily valid Python.


Fully stop logging and close log file.

        In order to start logging again, a new logstart() call needs to be
        made, possibly (though not necessarily) with a new filename, mode and
        other options.


Create a worksheet by name with with a list of cells.


Adds a target 'string' for dispatching


Adds a target regexp for dispatching


Yield all 'value' targets, without priority


do a bit of validation of the notebook dir


Delete a notebook's id only. This doesn't delete the actual notebook.


Does a notebook exist?


Return a full path to a notebook given its notebook_id.


Get the representation of a notebook in format by notebook_id.


Get the NotebookNode representation of a notebook by notebook_id.


Save an existing notebook by notebook_id.


Save an existing notebook object by notebook_id.


Delete notebook by notebook_id.


Load the default config file from the default ipython_dir.

    This is useful for embedded shells.


This has to be in a method, for TerminalIPythonApp to be available.


initialize the InteractiveShell instance


optionally display the banner


Return a string representation of a value and its type for readable
    error messages.


Get a list of all the traits of this class.

        This method is just like the :meth:`traits` method, but is unbound.

        The TraitTypes returned don't know anything about the values
        that the various HasTrait's instances are holding.

        This follows the same algorithm as traits does and does not allow
        for any simple way of specifying merely that a metadata name
        exists, but has any value.  This is because get_metadata returns
        None if a metadata key doesn't exist.


Get metadata values for trait by key.


Validates that the value is a valid object instance.


Instantiate a default value instance.

        This is called when the containing HasTraits classes'
        :meth:`__new__` method is called to ensure that a unique instance
        is created for each HasTraits instance.


return whether this dependency has become impossible.


Represent this dependency as a dict. For json compatibility.


Scans through all children of node and gathers the
    text. If node has non-text child-nodes then
    NotTextNodeError is raised.


Get the number of credits remaining at AmbientSMS


Send a mesage via the AmbientSMS API server


Inteface for sending web requests to the AmbientSMS API Server


Called for each file
        Must return file content
        Can be wrapped

        :type f: static_bundle.files.StaticFileResult
        :type text: str|unicode
        :rtype: str|unicode


Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If
    when is a time it sets the date to the epoch. If when is None or a datetime it returns when.
    Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a
    datetime with tzinfo set in which case it remains the same.


Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called
    on the datetime to convert it to the provided timezone. It will be converted to UTC if no
    timezone is provided.


Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is
    called on the datetime to convert it to the provided timezone. It will be converted to UTC if
    no timezone is provided.


Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is
    interpreted as UTC. If tzin is set it will be interpreted as this timestamp instead. By default
    the output datetime will have UTC time. If tzout is set it will be converted in this timezone
    instead.


Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be
    converted to the requested timezone otherwise it defaults to UTC.


Return the datetime truncated to the precision of the provided unit.


Return the date for the day of this week.


print a binary tree


parallel reduce followed by broadcast of the result


Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the
    current platform.


Normalizes a path maintaining the final slashes.

    Some environment variables need the final slash in order to work.

    Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used
    in the Visual Studio projects.

    :param unicode path:
        The path to normalize.

    :rtype: unicode
    :returns:
        Normalized path


Returns a version of a path that is unique.

    Given two paths path1 and path2:
        CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on
        the host OS. Takes account of case, slashes and relative paths.

    :param unicode path:
        The original path.

    :rtype: unicode
    :returns:
        The unique path.


Replaces all slashes and backslashes with the target separator

    StandardPath:
        We are defining that the standard-path is the one with only back-slashes in it, either
        on Windows or any other platform.

    :param bool strip:
        If True, removes additional slashes from the end of the path.


Copy a file from source to target.

    :param  source_filename:
        @see _DoCopyFile

    :param  target_filename:
        @see _DoCopyFile

    :param bool md5_check:
        If True, checks md5 files (of both source and target files), if they match, skip this copy
        and return MD5_SKIP

        Md5 files are assumed to be {source, target} + '.md5'

        If any file is missing (source, target or md5), the copy will always be made.

    :param  copy_symlink:
        @see _DoCopyFile

    :raises FileAlreadyExistsError:
        If target_filename already exists, and override is False

    :raises NotImplementedProtocol:
        If file protocol is not accepted

        Protocols allowed are:
            source_filename: local, ftp, http
            target_filename: local, ftp

    :rtype: None | MD5_SKIP
    :returns:
        MD5_SKIP if the file was not copied because there was a matching .md5 file

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Copy a file locally to a directory.

    :param unicode source_filename:
        The filename to copy from.

    :param unicode target_filename:
        The filename to copy to.

    :param bool copy_symlink:
        If True and source_filename is a symlink, target_filename will also be created as
        a symlink.

        If False, the file being linked will be copied instead.


Copies files into directories, according to a file mapping

    :param list(tuple(unicode,unicode)) file_mapping:
        A list of mappings between the directory in the target and the source.
        For syntax, @see: ExtendedPathMask

    :rtype: list(tuple(unicode,unicode))
    :returns:
        List of files copied. (source_filename, target_filename)

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Moves a directory.

    :param unicode source_dir:

    :param unicode target_dir:

    :raises NotImplementedError:
        If trying to move anything other than:
            Local dir -> local dir
            FTP dir -> FTP dir (same host)


Reads a file and returns its contents. Works for both local and remote files.

    :param unicode filename:

    :param bool binary:
        If True returns the file as is, ignore any EOL conversion.

    :param unicode encoding:
        File's encoding. If not None, contents obtained from file will be decoded using this
        `encoding`.

    :param None|''|'\n'|'\r'|'\r\n' newline:
        Controls universal newlines.
        See 'io.open' newline parameter documentation for more details.

    :returns str|unicode:
        The file's contents.
        Returns unicode string when `encoding` is not None.

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Lists the files in the given directory

    :type directory: unicode | unicode
    :param directory:
        A directory or URL

    :rtype: list(unicode) | list(unicode)
    :returns:
        List of filenames/directories found in the given directory.
        Returns None if the given directory does not exists.

        If `directory` is a unicode string, all files returned will also be unicode

    :raises NotImplementedProtocol:
        If file protocol is not local or FTP

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Create a file with the given contents.

    :param unicode filename:
        Filename and path to be created.

    :param unicode contents:
        The file contents as a string.

    :type eol_style: EOL_STYLE_XXX constant
    :param eol_style:
        Replaces the EOL by the appropriate EOL depending on the eol_style value.
        Considers that all content is using only "\n" as EOL.

    :param bool create_dir:
        If True, also creates directories needed in filename's path

    :param unicode encoding:
        Target file's content encoding. Defaults to sys.getfilesystemencoding()
        Ignored if `binary` = True

    :param bool binary:
        If True, file is created in binary mode. In this case, `contents` must be `bytes` and not
        `unicode`

    :return unicode:
        Returns the name of the file created.

    :raises NotImplementedProtocol:
        If file protocol is not local or FTP

    :raises ValueError:
        If trying to mix unicode `contents` without `encoding`, or `encoding` without
        unicode `contents`

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Create directory including any missing intermediate directory.

    :param unicode directory:

    :return unicode|urlparse.ParseResult:
        Returns the created directory or url (see urlparse).

    :raises NotImplementedProtocol:
        If protocol is not local or FTP.

    .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information


Deletes a directory.

    :param unicode directory:

    :param bool skip_on_error:
        If True, ignore any errors when trying to delete directory (for example, directory not
        found)

    :raises NotImplementedForRemotePathError:
        If trying to delete a remote directory.


Create a symbolic link at `link_path` pointing to `target_path`.

    :param unicode target_path:
        Link target

    :param unicode link_path:
        Fullpath to link name

    :param bool override:
        If True and `link_path` already exists as a link, that link is overridden.


Read the target of the symbolic link at `path`.

    :param unicode path:
        Path to a symbolic link

    :returns unicode:
        Target of a symbolic link


Checks if a given path is local, raise an exception if not.

    This is used in filesystem functions that do not support remote operations yet.

    :param unicode path:

    :raises NotImplementedForRemotePathError:
        If the given path is not local


Replaces eol on each line by the given eol_style.

    :param unicode contents:
    :type eol_style: EOL_STYLE_XXX constant
    :param eol_style:


Verifies if a filename match with given patterns.

    :param str filename: The filename to match.
    :param list(str) masks: The patterns to search in the filename.
    :return bool:
        True if the filename has matched with one pattern, False otherwise.


Searches for files in a given directory that match with the given patterns.

    :param str dir_: the directory root, to search the files.
    :param list(str) in_filters: a list with patterns to match (default = all). E.g.: ['*.py']
    :param list(str) out_filters: a list with patterns to ignore (default = none). E.g.: ['*.py']
    :param bool recursive: if True search in subdirectories, otherwise, just in the root.
    :param bool include_root_dir: if True, includes the directory being searched in the returned paths
    :param bool standard_paths: if True, always uses unix path separators "/"
    :return list(str):
        A list of strings with the files that matched (with the full path in the filesystem).


os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly.

    This is not necessary in Python 3.

    :param path:
        .. seealso:: os.path.expanduser


A context manager to replace and restore a value using a getter and setter.

    :param object obj: The object to replace/restore.
    :param object key: The key to replace/restore in the object.
    :param object value: The value to replace.

    Example::

      with PushPop2(sys.modules, 'alpha', None):
        pytest.raises(ImportError):
          import alpha


turn any valid targets argument into a list of integer ids


all ME and Task queue messages come through here, as well as
        IOPub traffic.


Route registration requests and queries from clients.


handler to attach to heartbeater.
        called when a previously registered heart fails to respond to beat request.
        triggers unregistration


Save the submission of a task.


save an iopub message into the db


Register a new engine.


Unregister an engine that explicitly requested to leave.


Second half of engine registration, called after our HeartMonitor
        has received a beat from the Engine's Heart.


handle shutdown request.


Purge results from memory. This method is more valuable before we move
        to a DB based message storage mechanism.


decompose a TaskRecord dict into subsection of reply for get_result


Get the result of 1 or more messages.


go to the path


return a standard message


subprocess run on here


Returns whether a reply from the kernel originated from a request
            from this frontend.


Annotate a single file.

        `cu` is the CodeUnit for the file to annotate.


Return a CouchDB database instance from a database string.


Make sure a DB specifier exists, creating it if necessary.


check packers for binary data and datetime support.


Return the nested message dict.

        This format is different from what is sent over the wire. The
        serialize/unserialize methods converts this nested message dict to the wire
        format, which is a list of message parts.


Sign a message with HMAC digest. If no auth, return b''.

        Parameters
        ----------
        msg_list : list
            The [p_header,p_parent,p_content] part of the message list.


Serialize the message components to bytes.

        This is roughly the inverse of unserialize. The serialize/unserialize
        methods work with full message lists, whereas pack/unpack work with
        the individual message parts in the message list.

        Parameters
        ----------
        msg : dict or Message
            The nexted message dict as returned by the self.msg method.

        Returns
        -------
        msg_list : list
            The list of bytes objects to be sent with the format:
            [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
             buffer1,buffer2,...]. In this list, the p_* entities are
            the packed or serialized versions, so if JSON is used, these
            are utf8 encoded JSON strings.


Build and send a message via stream or socket.

        The message format used by this function internally is as follows:

        [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
         buffer1,buffer2,...]

        The serialize/unserialize methods convert the nested message dict into this
        format.

        Parameters
        ----------

        stream : zmq.Socket or ZMQStream
            The socket-like object used to send the data.
        msg_or_type : str or Message/dict
            Normally, msg_or_type will be a msg_type unless a message is being
            sent more than once. If a header is supplied, this can be set to
            None and the msg_type will be pulled from the header.

        content : dict or None
            The content of the message (ignored if msg_or_type is a message).
        header : dict or None
            The header dict for the message (ignores if msg_to_type is a message).
        parent : Message or dict or None
            The parent or parent header describing the parent of this message
            (ignored if msg_or_type is a message).
        ident : bytes or list of bytes
            The zmq.IDENTITY routing path.
        subheader : dict or None
            Extra header keys for this message's header (ignored if msg_or_type
            is a message).
        buffers : list or None
            The already-serialized buffers to be appended to the message.
        track : bool
            Whether to track.  Only for use with Sockets, because ZMQStream
            objects cannot track messages.

        Returns
        -------
        msg : dict
            The constructed message.
        (msg,tracker) : (dict, MessageTracker)
            if track=True, then a 2-tuple will be returned,
            the first element being the constructed
            message, and the second being the MessageTracker


Send a raw message via ident path.

        This method is used to send a already serialized message.

        Parameters
        ----------
        stream : ZMQStream or Socket
            The ZMQ stream or socket to use for sending the message.
        msg_list : list
            The serialized list of messages to send. This only includes the
            [p_header,p_parent,p_content,buffer1,buffer2,...] portion of
            the message.
        ident : ident or list
            A single ident or a list of idents to use in sending.


Receive and unpack a message.

        Parameters
        ----------
        socket : ZMQStream or Socket
            The socket or stream to use in receiving.

        Returns
        -------
        [idents], msg
            [idents] is a list of idents and msg is a nested message dict of
            same format as self.msg returns.


Split the identities from the rest of the message.

        Feed until DELIM is reached, then return the prefix as idents and
        remainder as msg_list. This is easily broken by setting an IDENT to DELIM,
        but that would be silly.

        Parameters
        ----------
        msg_list : a list of Message or bytes objects
            The message to be split.
        copy : bool
            flag determining whether the arguments are bytes or Messages

        Returns
        -------
        (idents, msg_list) : two lists
            idents will always be a list of bytes, each of which is a ZMQ
            identity. msg_list will be a list of bytes or zmq.Messages of the
            form [HMAC,p_header,p_parent,p_content,buffer1,buffer2,...] and
            should be unpackable/unserializable via self.unserialize at this
            point.


Copy a SVG document to the clipboard.

    Parameters:
    -----------
    string : basestring
        A Python string containing a SVG document.


Convert a SVG document to a QImage.

    Parameters:
    -----------
    string : basestring
        A Python string containing a SVG document.

    size : QSize, optional
        The size of the image that is produced. If not specified, the SVG
        document's default size is used.

    Raises:
    -------
    ValueError
        If an invalid SVG string is provided.

    Returns:
    --------
    A QImage of format QImage.Format_ARGB32.


Make an object info dict with all fields present.


Wrapper around inspect.getsource.

    This can be modified by other projects to provide customized source
    extraction.

    Inputs:

    - obj: an object whose source code we will attempt to extract.

    Optional inputs:

    - is_binary: whether the object is known to come from a binary source.
    This implementation will skip returning any output for binary objects, but
    custom extractors may know how to meaningfully process them.


Find the absolute path to the file where an object was defined.

    This is essentially a robust wrapper around `inspect.getabsfile`.

    Returns None if no file can be found.

    Parameters
    ----------
    obj : any Python object

    Returns
    -------
    fname : str
      The absolute path to the file where the object was defined.


Find the line number in a file where an object was defined.

    This is essentially a robust wrapper around `inspect.getsourcelines`.

    Returns None if no file can be found.

    Parameters
    ----------
    obj : any Python object

    Returns
    -------
    lineno : int
      The line number where the object definition starts.


Return the definition header for any callable object.

        If any exception is generated, None is returned instead and the
        exception is suppressed.


Return a header string with proper colors.


Generic message when no information is found.


Print the definition header for any callable object.

        If the object is a class, print the constructor information.


Print the docstring for any object.

        Optional:
        -formatter: a function to run the docstring through for specially
        formatted docstrings.

        Examples
        --------

        In [1]: class NoInit:
           ...:     pass

        In [2]: class NoDoc:
           ...:     def __init__(self):
           ...:         pass

        In [3]: %pdoc NoDoc
        No documentation found for NoDoc

        In [4]: %pdoc NoInit
        No documentation found for NoInit

        In [5]: obj = NoInit()

        In [6]: %pdoc obj
        No documentation found for obj

        In [5]: obj2 = NoDoc()

        In [6]: %pdoc obj2
        No documentation found for obj2


Print the source code for an object.


Show the whole file where an object was defined.


Show detailed information about an object.

        Optional arguments:

        - oname: name of the variable pointing to the object.

        - formatter: special formatter for docstrings (see pdoc)

        - info: a structure with some information fields which may have been
        precomputed already.

        - detail_level: if set to 1, more information is given.


Start the Twisted reactor in a separate thread, if not already done.
    Returns the reactor.
    The thread will automatically be destroyed when all the tests are done.


By wrapping a test function with this decorator, you can return a
    twisted Deferred and the test will wait for the deferred to be triggered.
    The whole test function will run inside the Twisted event loop.

    The optional timeout parameter specifies the maximum duration of the test.
    The difference with timed() is that timed() will still wait for the test
    to end, while deferred() will stop the test when its timeout has expired.
    The latter is more desireable when dealing with network tests, because
    the result may actually never arrive.

    If the callback is triggered, the test has passed.
    If the errback is triggered or the timeout expires, the test has failed.

    Example::

        @deferred(timeout=5.0)
        def test_resolve():
            return reactor.resolve("www.python.org")

    Attention! If you combine this decorator with other decorators (like
    "raises"), deferred() must be called *first*!

    In other words, this is good::

        @raises(DNSLookupError)
        @deferred()
        def test_error():
            return reactor.resolve("xxxjhjhj.biz")

    and this is bad::

        @deferred()
        @raises(DNSLookupError)
        def test_error():
            return reactor.resolve("xxxjhjhj.biz")


Exclude NoSet objec

    .. code-block::

        >>> coerce(NoSet, 'value')
        'value'


Encodes the stored ``data`` to XML and returns
        an ``lxml.etree`` value.


Helper function for merge.

        Takes a dictionary whose values are lists and returns a dict with
        the elements of each list as keys and the original keys as values.