Add an identity to the `DiscoInfo` object.

        :Parameters:
            - `item_name`: name of the item.
            - `item_category`: category of the item.
            - `item_type`: type of the item.
        :Types:
            - `item_name`: `unicode`
            - `item_category`: `unicode`
            - `item_type`: `unicode`

        :returns: the identity created.
        :returntype: `DiscoIdentity`


Create error response for the a "get" or "set" iq stanza.

        :Parameters:
            - `cond`: error condition name, as defined in XMPP specification.

        :return: new `Iq` object with the same "id" as self, "from" and "to"
            attributes swapped, type="error" and containing <error /> element
            plus payload of `self`.
        :returntype: `Iq`


Create result response for the a "get" or "set" iq stanza.

        :return: new `Iq` object with the same "id" as self, "from" and "to"
            attributes replaced and type="result".
        :returntype: `Iq`


Request a TLS-encrypted connection.

        [initiating entity only]


Verify the peer certificate on the `TLSConnectedEvent`.


Default certificate verification callback for TLS connections.

        :Parameters:
            - `cert`: certificate information
        :Types:
            - `cert`: `CertificateData`

        :return: computed verification result.


Parse the command-line arguments and run the tool.


Do the expiration of dictionary items.

        Remove items that expired by now from the dictionary.

        :Return: time, in seconds, when the next item expires or `None`
        :returntype: `float`


Do the expiration of a dictionary item.

        Remove the item if it has expired by now.

        :Parameters:
            - `key`: key to the object.
        :Types:
            - `key`: any hashable value


Decode error element of the stanza.


Set stanza payload to a single item.

        All current stanza content of will be dropped.
        Marks the stanza dirty.

        :Parameters:
            - `payload`: XML element or stanza payload object to use
        :Types:
            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`


Add new the stanza payload.

        Marks the stanza dirty.

        :Parameters:
            - `payload`: XML element or stanza payload object to add
        :Types:
            - `payload`: :etree:`ElementTree.Element` or `StanzaPayload`


Return list of stanza payload objects.

        :Parameters:
            - `specialize`: If `True`, then return objects of specialized
              `StanzaPayload` classes whenever possible, otherwise the
              representation already available will be used (often
              `XMLPayload`)

        :Returntype: `list` of `StanzaPayload`


Serialize an XML element into a unicode string.

    This should work the same on Python2 and Python3 and with all
    :etree:`ElementTree` implementations.

    :Parameters:
        - `element`: the XML element to serialize
    :Types:
        - `element`: :etree:`ElementTree.Element`


Bind to a resource.

        [initiating entity only]

        :Parameters:
            - `resource`: the resource name to bind to.
        :Types:
            - `resource`: `unicode`

        XMPP stream is authenticated for bare JID only. To use
        the full JID it must be bound to a resource.


Serialize an XMPP element.

    Utility function for debugging or logging.

        :Parameters:
            - `element`: the element to serialize
        :Types:
            - `element`: :etree:`ElementTree.Element`

        :Return: serialized element
        :Returntype: `unicode`


Add a new namespace prefix.

        If the root element has not yet been emitted the prefix will
        be declared there, otherwise the prefix will be declared on the
        top-most element using this namespace in every stanza.

        :Parameters:
            - `namespace`: the namespace URI
            - `prefix`: the prefix string
        :Types:
            - `namespace`: `unicode`
            - `prefix`: `unicode`


Return the opening tag of the stream root element.

        :Parameters:
            - `stream_from`: the 'from' attribute of the stream. May be `None`.
            - `stream_to`: the 'to' attribute of the stream. May be `None`.
            - `version`: the 'version' of the stream.
            - `language`: the 'xml:lang' of the stream
        :Types:
            - `stream_from`: `unicode`
            - `stream_to`: `unicode`
            - `version`: `unicode`
            - `language`: `unicode`


Split an element of attribute qname into namespace and local
        name.

        :Parameters:
            - `name`: element or attribute QName
            - `is_element`: `True` for an element, `False` for an attribute
        :Types:
            - `name`: `unicode`
            - `is_element`: `bool`

        :Return: namespace URI, local name
        :returntype: `unicode`, `unicode`


Make up a new namespace prefix, which won't conflict
        with `_prefixes` and prefixes declared in the current scope.

        :Parameters:
            - `declared_prefixes`: namespace to prefix mapping for the current
              scope
        :Types:
            - `declared_prefixes`: `unicode` to `unicode` dictionary

        :Returns: a new prefix
        :Returntype: `unicode`


Return namespace-prefixed tag or attribute name.

        Add appropriate declaration to `declarations` when neccessary.

        If no prefix for an element namespace is defined, make the elements
        namespace default (no prefix). For attributes, make up a prefix in such
        case.

        :Parameters:
            - `name`: QName ('{namespace-uri}local-name')
              to convert
            - `is_element`: `True` for element, `False` for an attribute
            - `declared_prefixes`: mapping of prefixes already declared
              at this scope
            - `declarations`: XMLNS declarations on the current element.
        :Types:
            - `name`: `unicode`
            - `is_element`: `bool`
            - `declared_prefixes`: `unicode` to `unicode` dictionary
            - `declarations`: `unicode` to `unicode` dictionary

        :Returntype: `unicode`


Build namespace declarations and remove obsoleted mappings
        from `declared_prefixes`.

        :Parameters:
            - `declarations`: namespace to prefix mapping of the new
              declarations
            - `declared_prefixes`: namespace to prefix mapping of already
              declared prefixes.
        :Types:
            - `declarations`: `unicode` to `unicode` dictionary
            - `declared_prefixes`: `unicode` to `unicode` dictionary

        :Return: string of namespace declarations to be used in a start tag
        :Returntype: `unicode`


Recursive XML element serializer.

        :Parameters:
            - `element`: the element to serialize
            - `level`: nest level (0 - root element, 1 - stanzas, etc.)
            - `declared_prefixes`: namespace to prefix mapping of already
              declared prefixes.
        :Types:
            - `element`: :etree:`ElementTree.Element`
            - `level`: `int`
            - `declared_prefixes`: `unicode` to `unicode` dictionary

        :Return: serialized element
        :Returntype: `unicode`


Serialize a stanza.

        Must be called after `emit_head`.

        :Parameters:
            - `element`: the element to serialize
        :Types:
            - `element`: :etree:`ElementTree.Element`

        :Return: serialized element
        :Returntype: `unicode`


Update user information.

        :Parameters:
            - `presence`: a presence stanza with user information update.
        :Types:
            - `presence`: `MucPresence`


Get a room user with given nick or JID.

        :Parameters:
            - `nick_or_jid`: the nickname or room JID of the user requested.
            - `create`: if `True` and `nick_or_jid` is a JID, then a new
              user object will be created if there is no such user in the room.
        :Types:
            - `nick_or_jid`: `unicode` or `JID`
            - `create`: `bool`

        :return: the named user or `None`
        :returntype: `MucRoomUser`


Called when current stream changes.

        Mark the room not joined and inform `self.handler` that it was left.

        :Parameters:
            - `stream`: the new stream.
        :Types:
            - `stream`: `pyxmpp.stream.Stream`


Send a join request for the room.

        :Parameters:
            - `password`: password to the room.
            - `history_maxchars`: limit of the total number of characters in
              history.
            - `history_maxstanzas`: limit of the total number of messages in
              history.
            - `history_seconds`: send only messages received in the last
              `history_seconds` seconds.
            - `history_since`: Send only the messages received since the
              dateTime specified (UTC).
        :Types:
            - `password`: `unicode`
            - `history_maxchars`: `int`
            - `history_maxstanzas`: `int`
            - `history_seconds`: `int`
            - `history_since`: `datetime.datetime`


Send a subject change request to the room.

        :Parameters:
            - `subject`: the new subject.
        :Types:
            - `subject`: `unicode`


Send a nick change request to the room.

        :Parameters:
            - `new_nick`: the new nickname requested.
        :Types:
            - `new_nick`: `unicode`


Get own room JID or a room JID for given `nick`.

        :Parameters:
            - `nick`: a nick for which the room JID is requested.
        :Types:
            - `nick`: `unicode`

        :return: the room JID.
        :returntype: `JID`


Process successful result of a room configuration form request.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Presence`


Request a configuration form for the room.

        When the form is received `self.handler.configuration_form_received` will be called.
        When an error response is received then `self.handler.error` will be called.

        :return: id of the request stanza.
        :returntype: `unicode`


Process success response for a room configuration request.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Presence`


Change the stream assigned to `self`.

        :Parameters:
            - `stream`: the new stream to be assigned to `self`.
        :Types:
            - `stream`: `pyxmpp.stream.Stream`


Create and return a new room state object and request joining
        to a MUC room.

        :Parameters:
            - `room`: the name of a room to be joined
            - `nick`: the nickname to be used in the room
            - `handler`: is an object to handle room events.
            - `password`: password for the room, if any
            - `history_maxchars`: limit of the total number of characters in
              history.
            - `history_maxstanzas`: limit of the total number of messages in
              history.
            - `history_seconds`: send only messages received in the last
              `history_seconds` seconds.
            - `history_since`: Send only the messages received since the
              dateTime specified (UTC).

        :Types:
            - `room`: `JID`
            - `nick`: `unicode`
            - `handler`: `MucRoomHandler`
            - `password`: `unicode`
            - `history_maxchars`: `int`
            - `history_maxstanzas`: `int`
            - `history_seconds`: `int`
            - `history_since`: `datetime.datetime`

        :return: the room state object created.
        :returntype: `MucRoomState`


Process a groupchat message from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Message`

        :return: `True` if the message was properly recognized as directed to
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


Process an error message from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Message`

        :return: `True` if the message was properly recognized as directed to
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


Process an presence error from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Presence`

        :return: `True` if the stanza was properly recognized as generated by
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


Process an available presence from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Presence`

        :return: `True` if the stanza was properly recognized as generated by
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`


Get a parameter value.

        If parameter is not set, return `local_default` if it is not `None`
        or the PyXMPP global default otherwise.

        :Raise `KeyError`: if parameter has no value and no global default

        :Return: parameter value


Validator for string lists to be used with `add_setting`.


List known settings.

        :Parameters:
            - `basic`: When `True` then limit output to the basic settings,
              when `False` list only the extra settings.


Make a command-line option parser.

        The returned parser may be used as a parent parser for application
        argument parser.

        :Parameters:
            - `settings`: list of PyXMPP2 settings to consider. By default
              all 'basic' settings are provided.
            - `option_prefix`: custom prefix for PyXMPP2 options. E.g.
              ``'--xmpp'`` to differentiate them from not xmpp-related
              application options.
            - `add_help`: when `True` a '--help' option will be included
              (probably already added in the application parser object)
        :Types:
            - `settings`: list of `unicode`
            - `option_prefix`: `str`
            - `add_help`:

        :return: an argument parser object.
        :returntype: :std:`argparse.ArgumentParser`


Compare two International Domain Names.

    :Parameters:
        - `domain1`: domains name to compare
        - `domain2`: domains name to compare
    :Types:
        - `domain1`: `unicode`
        - `domain2`: `unicode`

    :return: True `domain1` and `domain2` are equal as domain names.


Prepare localpart of the JID

        :Parameters:
            - `data`: localpart of the JID
        :Types:
            - `data`: `unicode`

        :raise JIDError: if the local name is too long.
        :raise pyxmpp.xmppstringprep.StringprepError: if the
            local name fails Nodeprep preparation.


Prepare domainpart of the JID.

        :Parameters:
            - `data`: Domain part of the JID
        :Types:
            - `data`: `unicode`

        :raise JIDError: if the domain name is too long.


Unicode string JID representation.

        :return: JID as Unicode string.


Check if IPv6 is available.

    :Return: `True` when an IPv6 socket can be created.


Check if IPv4 is available.

    :Return: `True` when an IPv4 socket can be created.


Reorder SRV records using their priorities and weights.

    :Parameters:
        - `records`: SRV records to shuffle.
    :Types:
        - `records`: `list` of :dns:`dns.rdtypes.IN.SRV`

    :return: reordered records.
    :returntype: `list` of :dns:`dns.rdtypes.IN.SRV`


Stop the resolver threads.


Start looking up an A or AAAA record.

        `callback` will be called with a list of (family, address) tuples
        on success. Family is :std:`socket.AF_INET` or :std:`socket.AF_INET6`,
        the address is IPv4 or IPv6 literal. The list will be empty on error.

        :Parameters:
            - `hostname`: the host name to look up
            - `callback`: a function to be called with a list of received
              addresses
            - `allow_cname`: `True` if CNAMEs should be followed
        :Types:
            - `hostname`: `unicode`
            - `callback`: function accepting a single argument
            - `allow_cname`: `bool`


Star an XMPP session and send a message, then exit.

    :Parameters:
        - `source_jid`: sender JID
        - `password`: sender password
        - `target_jid`: recipient JID
        - `body`: message body
        - `subject`: message subject
        - `message_type`: message type
        - `message_thread`: message thread id
        - `settings`: other settings
    :Types:
        - `source_jid`: `pyxmpp2.jid.JID` or `basestring`
        - `password`: `basestring`
        - `target_jid`: `pyxmpp.jid.JID` or `basestring`
        - `body`: `basestring`
        - `subject`: `basestring`
        - `message_type`: `basestring`
        - `settings`: `pyxmpp2.settings.XMPPSettings`


Compute the authentication handshake value.

        :return: the computed hash value.
        :returntype: `str`


Authenticate on the server.

        [component only]


Set `_state` and notify any threads waiting for the change.


Start establishing TCP connection with given address.

        One of: `port` or `service` must be provided and `addr` must be
        a domain name and not an IP address if `port` is not given.

        When `service` is given try an SRV lookup for that service
        at domain `addr`. If `service` is not given or `addr` is an IP address,
        or the SRV lookup fails, connect to `port` at host `addr` directly.

        [initiating entity only]

        :Parameters:
            - `addr`: peer name or IP address
            - `port`: port number to connect to
            - `service`: service name (to be resolved using SRV DNS records)


Same as `connect`, but assumes `lock` acquired.


Start resolving the SRV record.


Handle SRV lookup result.

        :Parameters:
            - `addrs`: properly sorted list of (hostname, port) tuples


Start hostname resolution for the next name to try.

        [called with `lock` acquired]


Handler DNS address record lookup result.

        :Parameters:
            - `name`: the name requested
            - `port`: port number to connect to
            - `addrs`: list of (family, address) tuples


Start connecting to the next address on the `_dst_addrs` list.

        [ called with `lock` acquired ]


Handle connection success.


Continue connecting.

        [called with `lock` acquired]

        :Return: `True` when just connected


Write raw data to the socket.

        :Parameters:
            - `data`: data to send
        :Types:
            - `data`: `bytes`


Make the `stream` the target for this transport instance.

        The 'stream_start', 'stream_end' and 'stream_element' methods
        of the target will be called when appropriate content is received.

        :Parameters:
            - `stream`: the stream handler to receive stream content
              from the transport
        :Types:
            - `stream`: `StreamBase`


Send stream head via the transport.

        :Parameters:
            - `stanza_namespace`: namespace of stream stanzas (e.g.
              'jabber:client')
            - `stream_from`: the 'from' attribute of the stream. May be `None`.
            - `stream_to`: the 'to' attribute of the stream. May be `None`.
            - `version`: the 'version' of the stream.
            - `language`: the 'xml:lang' of the stream
        :Types:
            - `stanza_namespace`: `unicode`
            - `stream_from`: `unicode`
            - `stream_to`: `unicode`
            - `version`: `unicode`
            - `language`: `unicode`


Send an element via the transport.


Stop current thread until the channel is readable.

        :Return: `False` if it won't be readable (e.g. is closed)


Stop current thread until the channel is writable.

        :Return: `False` if it won't be readable (e.g. is closed)


Request a TLS handshake on the socket ans switch
        to encrypted output.
        The handshake will start after any currently buffered data is sent.

        :Parameters:
            - `kwargs`: arguments for :std:`ssl.wrap_socket`


Return the peer certificate.

        :ReturnType: `pyxmpp2.cert.Certificate`


Initiate starttls handshake over the socket.


Handle the 'channel hungup' state. The handler should not be writable
        after this.


Handle an error reported.


Disconnect the stream gracefully.


Same as `_close` but expects `lock` acquired.


Feed the stream reader with data received.

        [ called with `lock` acquired ]

        If `data` is None or empty, then stream end (peer disconnected) is
        assumed and the stream is closed.

        `lock` is acquired during the operation.

        :Parameters:
            - `data`: data received from the stream socket.
        :Types:
            - `data`: `unicode`


Pass an event to the target stream or just log it.


Handle an end tag.

        Call the handler's 'stream_end' method with
        an the root element (built by the `start` method).

        On the first level below root, sent the built element tree
        to the handler via the 'stanza methods'.

        Any tag below will be just added to the tree builder.


Start threads for an IOHandler.


Add a TimeoutHandler to the pool.


Start threads for a TimeoutHandler.


Remove a TimeoutHandler from the pool.


Start the threads.


Wait up to `timeout` seconds, raise any exception from the
        threads.


Initialize authentication when the connection is established
        and we are the initiator.


Unregister legacy authentication handlers after successfull
        authentication.


Try to authenticate using the first one of allowed authentication
        methods left.

        [client only]


Handle legacy authentication timeout.

        [client only]


Handle legacy authentication error.

        [client only]


Handle success of the legacy authentication.


Handle in-band registration error.

        [client only]

        :Parameters:
            - `stanza`: the error stanza received or `None` on timeout.
        :Types:
            - `stanza`: `pyxmpp.stanza.Stanza`


Submit a registration form.

        [client only]

        :Parameters:
            - `form`: the filled-in form. When form is `None` or its type is
              "cancel" the registration is to be canceled.

        :Types:
            - `form`: `pyxmpp.jabber.dataforms.Form`


Handle registration success.

        [client only]

        Clean up registration stuff, change state to "registered" and initialize
        authentication.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `pyxmpp.iq.Iq`


Request software version information from a remote entity.

    When a valid response is received the `callback` will be handled
    with a `VersionPayload` instance as its only argument. The object will
    provide the requested infromation.

    In case of error stanza received or invalid response the `error_callback`
    (if provided) will be called with the offending stanza (which can
    be ``<iq type='error'/>`` or ``<iq type='result'>``) as its argument.

    The same function will be called on timeout, with the argument set to
    `None`.

    :Parameters:
        - `stanza_processor`: a object used to send the query and handle
          response. E.g. a `pyxmpp2.client.Client` instance
        - `target_jid`: the JID of the entity to query
        - `callback`: function to be called with a valid response
        - `error_callback`: function to be called on error
    :Types:
        - `stanza_processor`: `StanzaProcessor`
        - `target_jid`: `JID`


Set up stream element handlers.

        Scans the `handlers` list for `StreamFeatureHandler`
        instances and updates `_element_handlers` mapping with their
        methods decorated with @`stream_element_handler`


Handle a stream event.

        Called when connection state is changed.

        Should not be called with self.lock acquired!


Send stream start tag.


Same as `send` but assume `lock` is acquired.


Handle stanza received from the stream.


Process stream error element received.

        :Parameters:
            - `error`: error received

        :Types:
            - `error`: `StreamErrorElement`


Mark stream authenticated as `me`.

        :Parameters:
            - `me`: local JID just authenticated
            - `restart_stream`: `True` when stream should be restarted (needed
              after SASL authentication)
        :Types:
            - `me`: `JID`
            - `restart_stream`: `bool`


Authentication properties of the stream.

        Derived from the transport with 'local-jid' and 'service-type' added.


Fix an incoming stanza.

        Ona server replace the sender address with authorized client JID.


Initialize `Register` from an XML node.

        :Parameters:
            - `xmlnode`: the jabber:x:register XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


Return Data Form for the `Register` object.

        Convert legacy fields to a data form if `self.form` is `None`, return `self.form` otherwise.

        :Parameters:
            - `form_type`: If "form", then a form to fill-in should be
              returned. If "sumbit", then a form with submitted data.
        :Types:
            - `form_type`: `unicode`

        :return: `self.form` or a form created from the legacy fields
        :returntype: `pyxmpp.jabber.dataforms.Form`


Make `Register` object for submitting the registration form.

        Convert form data to legacy fields if `self.form` is `None`.

        :Parameters:
            - `form`: The form to submit. Its type doesn't have to be "submit"
              (a "submit" form will be created here), so it could be the form
              obtained from `get_form` just with the data entered.

        :return: new registration element
        :returntype: `Register`


Initialize Delay object from an XML node.

        :Parameters:
            - `xmlnode`: the jabber:x:delay XML element.
        :Types:
            - `xmlnode`: `libxml2.xmlNode`


Accept any incoming connections.


Activate an plan in a CREATED state.


Execute the PreparedBillingAgreement by creating and executing a
		matching BillingAgreement.


Create, validate and process a WebhookEventTrigger given a Django
		request object.

		The webhook_id parameter expects the ID of the Webhook that was
		triggered (defaults to settings.PAYPAL_WEBHOOK_ID). This is required
		for Webhook verification.

		The process is three-fold:
		1. Create a WebhookEventTrigger object from a Django request.
		2. Verify the WebhookEventTrigger as a Paypal webhook using the SDK.
		3. If valid, process it into a WebhookEvent object (and child resource).


Make an ArgumentParser that accepts DNS RRs


Go through each line of the text and ensure that
    a name is defined.  Use '@' if there is none.


Parse a zonefile into a dict.
    @text must be flattened--each record must be on one line.
    Also, all comments must be removed.


Quote a field in a list of DNS records.
    Return the new data records.


This function can be used to build a python package representation of pyschema classes.
    One module is created per namespace in a package matching the namespace hierarchy.

    Args:
        classes: A collection of classes to build the package from
        target_folder: Root folder of the package
        parent_package: Prepended on all import statements in order to support absolute imports.
            parent_package is not used when building the package file structure
        indent: Indent level. Defaults to 4 spaces


Generate Python source code for one specific class

    Doesn't include or take into account any dependencies between record types


Temporarily disable automatic registration of records in the auto_store

    Decorator factory. This is _NOT_ thread safe

    >>> @no_auto_store()
    ... class BarRecord(Record):
    ...     pass
    >>> BarRecord in auto_store
    False


Create a Record instance from a json-compatible dictionary

    The dictionary values should have types that are json compatible,
    as if just loaded from a json serialized record string.

    :param dct:
        Python dictionary with key/value pairs for the record

    :param record_store:
        Record store to use for schema lookups (when $schema field is present)

    :param schema:
        PySchema Record class for the record to load.
        This will override any $schema fields specified in `dct`


Create a Record instance from a json serialized dictionary

    :param s:
        String with a json-serialized dictionary

    :param record_store:
        Record store to use for schema lookups (when $schema field is present)

    :param loader:
        Function called to fetch attributes from json. Typically shouldn't be used by end users

    :param schema:
        PySchema Record class for the record to load.
        This will override any $schema fields specified in `s`

    :param record_class:
        DEPRECATED option, old name for the `schema` parameter


Add record class to record store for retrieval at record load time.

            Can be used as a class decorator


Return a dictionary the field definition

        Should contain all fields that are required for the definition of this field in a pyschema class


Decorator for mixing in additional functionality into field type

        Example:

        >>> @Integer.mixin
        ... class IntegerPostgresExtensions:
        ...     postgres_type = 'INT'
        ...
        ...     def postgres_dump(self, obj):
        ...         self.dump(obj) + "::integer"

        Is roughly equivalent to:

        >>> Integer.postgres_type = 'INT'
        ...
        ... def postgres_dump(self, obj):
        ...     self.dump(obj) + "::integer"
        ...
        ... Integer.postgres_dump = postgres_dump


Create proper PySchema class from cls

        Any methods and attributes will be transferred to the
        new object


Return a python dict representing the jsonschema of a record

    Any references to sub-schemas will be URI fragments that won't be
    resolvable without a root schema, available from get_root_schema_dict.


Converts a file object with json serialised pyschema records
        to a stream of pyschema objects

    Can be used as job.reader in luigi.hadoop.JobTask


Set a value at the front of an OrderedDict

    The original dict isn't modified, instead a copy is returned


Send a message upstream to a de-multiplexed application.

        If stream_name is includes will send just to that upstream steam, if not included will send ot all upstream
        steams.


Handle a downstream message coming from an upstream steam.

        if there is not handling method set for this method type it will propagate the message further downstream.

        This is called as part of the co-routine of an upstream steam, not the same loop as used for upstream messages
        in the de-multiplexer.


Rout the message down the correct stream.


Handle the disconnect message.

        This is propagated to all upstream applications.


Capture downstream websocket.send messages from the upstream applications.


Handle downstream `websocket.close` message.

        Will disconnect this upstream application from receiving any new frames.

        If there are not more upstream applications accepting messages it will then call `close`.


creator method to build FxCurve

        :param float fx_spot: fx spot rate
        :param RateCurve domestic_curve: domestic discount curve
        :param RateCurve foreign_curve: foreign discount curve
        :return:


Decorator to retry a function 'max_retries' amount of times

    :param tuple exceptions: Exceptions to be caught for retries
    :param int interval: Interval between retries in seconds
    :param int max_retries: Maximum number of retries to have, if
        set to -1 the decorator will loop forever
    :param function success: Function to indicate success criteria
    :param int timeout: Timeout interval in seconds, if -1 will retry forever
    :raises MaximumRetriesExceeded: Maximum number of retries hit without
        reaching the success criteria
    :raises TypeError: Both exceptions and success were left None causing the
        decorator to have no valid exit criteria.

    Example:
        Use it to decorate a function!

        .. sourcecode:: python

            from retry import retry

            @retry(exceptions=(ArithmeticError,), success=lambda x: x > 0)
            def foo(bar):
                if bar < 0:
                    raise ArithmeticError('testing this')
                return bar
            foo(5)
            # Should return 5
            foo(-1)
            # Should raise ArithmeticError
            foo(0)
            # Should raise MaximumRetriesExceeded


Button action event


Byte-for-byte comparison on an arbitrary number of files in parallel.

    This operates by opening all files in parallel and comparing
    chunk-by-chunk. This has the following implications:

        - Reads the same total amount of data as hash comparison.
        - Performs a *lot* of disk seeks. (Best suited for SSDs)
        - Vulnerable to file handle exhaustion if used on its own.

    :param paths: List of potentially identical files.
    :type paths: iterable

    :returns: A dict mapping one path to a list of all paths (self included)
              with the same contents.

    .. todo:: Start examining the ``while handles:`` block to figure out how to
        minimize thrashing in situations where read-ahead caching is active.
        Compare savings by read-ahead to savings due to eliminating false
        positives as quickly as possible. This is a 2-variable min/max problem.

    .. todo:: Look into possible solutions for pathological cases of thousands
        of files with the same size and same pre-filter results. (File handle
        exhaustion)


Group a list of file handles based on equality of the next chunk of
    data read from them.

    :param handles: A list of open handles for file-like objects with
        otentially-identical contents.
    :param chunk_size: The amount of data to read from each handle every time
        this function is called.

    :returns: Two lists of lists:

        * Lists to be fed back into this function individually
        * Finished groups of duplicate paths. (including unique files as
          single-file lists)

    :rtype: ``(list, list)``

    .. attention:: File handles will be closed when no longer needed
    .. todo:: Discard chunk contents immediately once they're no longer needed


High-level code to walk a set of paths and find duplicate groups.

    :param exact: Whether to compare file contents by hash or by reading
                  chunks in parallel.
    :type exact: :class:`~__builtins__.bool`

    :param paths: See :meth:`~fastdupes.getPaths`
    :param ignores: See :meth:`~fastdupes.getPaths`
    :param min_size: See :meth:`~fastdupes.sizeClassifier`

    :returns: A list of groups of files with identical contents
    :rtype: ``[[path, ...], [path, ...]]``


Specify query string to use with the collection.

        Returns: :py:class:`SearchResult`


Returns entity in correct collection.

        If the "href" value in result doesn't match the current collection,
        try to find the collection that the "href" refers to.


When you pass a quote character, returns you an another one if possible


Tries to escape the values that are passed to filter as correctly as possible.

    No standard way is followed, but at least it is simple.


import summarizers on-demand


Construct an elementary rotation matrix describing a rotation around the x, y, or z-axis.

  Parameters
  ----------

  axis          - Axis around which to rotate ("x", "y", or "z")
  rotationAngle - the rotation angle in radians

  Returns
  -------

  The rotation matrix

  Example usage
  -------------

  rotmat = elementaryRotationMatrix("y", pi/6.0)


Take the astrometric parameter standard uncertainties and the uncertainty correlations as quoted in
    the Gaia catalogue and construct the covariance matrix.

    Parameters
    ----------

    cvec : array_like
        Array of shape (15,) (1 source) or (n,15) (n sources) for the astrometric parameter standard
        uncertainties and their correlations, as listed in the Gaia catalogue [ra_error, dec_error,
        parallax_error, pmra_error, pmdec_error, ra_dec_corr, ra_parallax_corr, ra_pmra_corr,
        ra_pmdec_corr, dec_parallax_corr, dec_pmra_corr, dec_pmdec_corr, parallax_pmra_corr,
        parallax_pmdec_corr, pmra_pmdec_corr]. Units are (mas^2, mas^2/yr, mas^2/yr^2).

    parallax : array_like (n elements)
        Source parallax (mas).

    radial_velocity : array_like (n elements)
        Source radial velocity (km/s, does not have to be from Gaia RVS!). If the radial velocity is not
        known it can be set to zero.

    radial_velocity_error : array_like (n elements)
        Source radial velocity  uncertainty (km/s). If the radial velocity is not know this can be set to
        the radial velocity dispersion for the population the source was drawn from.

    Returns
    -------

    Covariance matrix as a 6x6 array.


Calculate radial velocity error from V and the spectral type. The value of the error is an average over
  the sky.

  Parameters
  ----------

  vmag - Value of V-band magnitude.
  spt  - String representing the spectral type of the star.

  Returns
  -------

  The radial velocity error in km/s.


Calculate the angular distance between pairs of sky coordinates.

    Parameters
    ----------

    phi1 : float
        Longitude of first coordinate (radians).
    theta1 : float
        Latitude of first coordinate (radians).
    phi2 : float
        Longitude of second coordinate (radians).
    theta2 : float
        Latitude of second coordinate (radians).

    Returns
    -------

    Angular distance in radians.


Rotates Cartesian coordinates from one reference system to another using the rotation matrix with
        which the class was initialized. The inputs  can be scalars or 1-dimensional numpy arrays.

        Parameters
        ----------

        x - Value of X-coordinate in original reference system
        y - Value of Y-coordinate in original reference system
        z - Value of Z-coordinate in original reference system

        Returns
        -------

        xrot - Value of X-coordinate after rotation
        yrot - Value of Y-coordinate after rotation
        zrot - Value of Z-coordinate after rotation


Converts sky coordinates from one reference system to another, making use of the rotation matrix with
        which the class was initialized. Inputs can be scalars or 1-dimensional numpy arrays.

        Parameters
        ----------

        phi   - Value of the azimuthal angle (right ascension, longitude) in radians.
        theta - Value of the elevation angle (declination, latitude) in radians.

        Returns
        -------

        phirot   - Value of the transformed azimuthal angle in radians.
        thetarot - Value of the transformed elevation angle in radians.


Transform the astrometric covariance matrix to its representation in the new coordinate system.

        Parameters
        ----------

        phi       - The longitude-like angle of the position of the source (radians).
        theta     - The latitude-like angle of the position of the source (radians).
        covmat    - Covariance matrix (5x5) of the astrometric parameters.

        Returns
        -------

        covmat_rot - Covariance matrix in its representation in the new coordinate system.


Make the plot with radial velocity performance predictions.

  :argument args: command line arguments


A utility function for selecting the first non-null query.

    Parameters:

      funcs: One or more functions

    Returns:

       A function that, when called with a :class:`Node`, will
       pass the input to each `func`, and return the first non-Falsey
       result.

    Examples:

       >>> s = Soupy("
hi
")
       >>> s.apply(either(Q.find('a'), Q.find('p').text))
       Scalar('hi')


Convert to unicode, and add quotes if initially a string


Call `func` on each element in the collection.

        If multiple functions are provided, each item
        in the output will be a tuple of each
        func(item) in self.

        Returns a new Collection.

        Example:

            >>> col = Collection([Scalar(1), Scalar(2)])
            >>> col.each(Q * 10)
            Collection([Scalar(10), Scalar(20)])
            >>> col.each(Q * 10, Q - 1)
            Collection([Scalar((10, 0)), Scalar((20, 1))])


Return a new Collection excluding some items

        Parameters:

            func : function(Node) -> Scalar

                A function that, when called on each item
                in the collection, returns a boolean-like
                value. If no function is provided, then
                truthy items will be removed.

        Returns:

            A new Collection consisting of the items
            where bool(func(item)) == False


Return a new Collection with some items removed.

        Parameters:

            func : function(Node) -> Scalar

                A function that, when called on each item
                in the collection, returns a boolean-like
                value. If no function is provided, then
                false-y items will be removed.

        Returns:

            A new Collection consisting of the items
            where bool(func(item)) == True

        Examples:

            node.find_all('a').filter(Q['href'].startswith('http'))


Return a new Collection with the first few items removed.

        Parameters:

            func : function(Node) -> Node

        Returns:

            A new Collection, discarding all items
            before the first item where bool(func(item)) == True


Zip the items of this collection with one or more
        other sequences, and wrap the result.

        Unlike Python's zip, all sequences must be the same length.

        Parameters:

            others: One or more iterables or Collections

        Returns:

            A new collection.

        Examples:

            >>> c1 = Collection([Scalar(1), Scalar(2)])
            >>> c2 = Collection([Scalar(3), Scalar(4)])
            >>> c1.zip(c2).val()
            [(1, 3), (2, 4)]


Return potential locations of IACA installation.


Yild all groups of simple regex-like expression.

    The only special character is a dash (-), which take the preceding and the following chars to
    compute a range. If the range is non-sensical (e.g., b-a) it will be empty

    Example:
    >>> list(group_iterator('a-f'))
    ['a', 'b', 'c', 'd', 'e', 'f']
    >>> list(group_iterator('148'))
    ['1', '4', '8']
    >>> list(group_iterator('7-9ab'))
    ['7', '8', '9', 'a', 'b']
    >>> list(group_iterator('0B-A1'))
    ['0', '1']


Very reduced regular expressions for describing a group of registers.

    Only groups in square bracktes and unions with pipes (|) are supported.

    Examples:
    >>> list(register_options('PMC[0-3]'))
    ['PMC0', 'PMC1', 'PMC2', 'PMC3']
    >>> list(register_options('MBOX0C[01]'))
    ['MBOX0C0', 'MBOX0C1']
    >>> list(register_options('CBOX2C1'))
    ['CBOX2C1']
    >>> list(register_options('CBOX[0-3]C[01]'))
    ['CBOX0C0', 'CBOX0C1', 'CBOX1C0', 'CBOX1C1', 'CBOX2C0', 'CBOX2C1', 'CBOX3C0', 'CBOX3C1']
    >>> list(register_options('PMC[0-1]|PMC[23]'))
    ['PMC0', 'PMC1', 'PMC2', 'PMC3']


Return a LIKWID event string from an event tuple or keyword arguments.

    *event_tuple* may have two or three arguments: (event, register) or
    (event, register, parameters)

    Keyword arguments will be overwritten by *event_tuple*.

    >>> eventstr(('L1D_REPLACEMENT', 'PMC0', None))
    'L1D_REPLACEMENT:PMC0'
    >>> eventstr(('L1D_REPLACEMENT', 'PMC0'))
    'L1D_REPLACEMENT:PMC0'
    >>> eventstr(('MEM_UOPS_RETIRED_LOADS', 'PMC3', {'EDGEDETECT': None, 'THRESHOLD': 2342}))
    'MEM_UOPS_RETIRED_LOADS:PMC3:EDGEDETECT:THRESHOLD=0x926'
    >>> eventstr(event='DTLB_LOAD_MISSES_WALK_DURATION', register='PMC3')
    'DTLB_LOAD_MISSES_WALK_DURATION:PMC3'


Compile list of minimal runs for given events.


Report analysis outcome in human readable form.


Round float to next multiple of base.


Split list of integers into blocks of block_size and return block indices.

    First block element will be located at initial_boundary (default 0).

    >>> blocking([0, -1, -2, -3, -4, -5, -6, -7, -8, -9], 8)
    [0,-1]
    >>> blocking([0], 8)
    [0]
    >>> blocking([0], 8, initial_boundary=32)
    [-4]


Run complete anaylysis and return results.


Strip whitespaces and comments from asm lines.


Let user interactively select byte increment.


Insert IACA marker into list of ASM instructions at given indices.


Add IACA markers to an assembly file.

    If instrumentation fails because loop increment could not determined automatically, a ValueError
    is raised.

    :param input_file: file-like object to read from
    :param output_file: file-like object to write to
    :param block_selection: index of the assembly block to instrument, or 'auto' for automatically
                            using block with the
                            most vector instructions, or 'manual' to read index to prompt user
    :param pointer_increment: number of bytes the pointer is incremented after the loop or
                              - 'auto': automatic detection, otherwise RuntimeError is raised
                              - 'auto_with_manual_fallback': like auto with fallback to manual input
                              - 'manual': prompt user
    :param debug: output additional internal analysis information. Only works with manual selection.
    :return: the instrumented assembly block


Execute command line interface.


Setup and execute model with given blocking length


Check arguments passed by user that are not checked by argparse itself.


Comand line interface of picklemerge.


Create a sympy.Symbol with positive and integer assumptions.


Check that information about kernel makes sens and is valid.


Set constant of name to value.

        :param name: may be a str or a sympy.Symbol
        :param value: must be an int


Return the offset from the iteration center in number of elements.

        The order of indices used in access is preserved.


Yield loop stack dictionaries in order from outer to inner.


Return the order of indices as they appear in array references.

        Use *source* and *destination* to filter output


Return a dictionary of lists of sympy accesses, for each variable.

        Use *source* and *destination* to filter output


Return sympy expressions translating global_iterator to loop indices.

        If global_iterator is given, an integer is returned


Return global iterator sympy expression


Transform a dictionary of indices to a global iterator integer.

        Inverse of global_iterator_to_indices().


Print kernel information in human readble format.


Print variables information in human readble format.


Print constants information in human readble format.


Print source code of kernel.


Convert mathematical expressions to a sympy representation.

        May only contain paranthesis, addition, subtraction and multiplication from AST.


Return a tuple of offsets of an ArrayRef object in all dimensions.

        The index order is right to left (c-code order).
        e.g. c[i+1][j-2] -> (-2, +1)

        If aref is actually a c_ast.ID, None will be returned.


Return base name of ArrayRef object.

        e.g. c[i+1][j-2] -> 'c'


Generate constants declarations

        :return: list of declarations


Return array declarations.


Return kernel loop nest including any preceding pragmas and following swaps.


Generate initialization statements for arrays.

        :param array_dimensions: dictionary of array dimensions

        :return: list of nodes


Generate false if branch with dummy calls

        Requires kerncraft.h to be included, which defines dummy(...) and var_false.

        :return: dummy statement


Build and return kernel function declaration


Build and return scalar variable declarations


Generate and return compilable source code with kernel function from AST.

        :param openmp: if true, OpenMP code will be generated
        :param as_filename: if true, will save to file and return filename
        :param name: name of kernel function


Generate and return kernel call ast.


Generate and return compilable source code from AST.


Run an IACA analysis and return its outcome.

        *asm_block* controls how the to-be-marked block is chosen. "auto" (default) results in
        the largest block, "manual" results in interactive and a number in the according block.

        *pointer_increment* is the number of bytes the pointer is incremented after the loop or
           - 'auto': automatic detection, RuntimeError is raised in case of failure
           - 'auto_with_manual_fallback': automatic detection, fallback to manual input
           - 'manual': prompt user


Compile source to executable with likwid capabilities and return the executable name.


Convert any string to a sympy object or None.


Return identifier which is either the machine file name or sha256 checksum of data.


Return a cachesim.CacheSimulator object based on the machine description.

        :param cores: core count (default: 1)


Return best fitting bandwidth according to number of threads, read and write streams.

        :param cache_level: integer of cache (0 is L1, 1 is L2 ...)
        :param read_streams: number of read streams expected
        :param write_streams: number of write streams expected
        :param threads_per_core: number of threads that are run on each core
        :param cores: if not given, will choose maximum bandwidth for single NUMA domain


Return tuple of compiler and compiler flags.

        Selects compiler and flags from machine description file, commandline arguments or call
        arguements.


Parse events in machine description to tuple representation used in Benchmark module.

        Examples:
        >>> parse_perfctr_event('PERF_EVENT:REG[0-3]')
        ('PERF_EVENT', 'REG[0-3]')
        >>> parse_perfctr_event('PERF_EVENT:REG[0-3]:STAY:FOO=23:BAR=0x23')
        ('PERF_EVENT', 'REG[0-3]', {'STAY': None, 'FOO': 23, 'BAR': 35})


Enforce that no ranges overlap in internal storage.


Align iteration with cacheline boundary.


Return a list with number of loaded cache lines per memory hierarchy level.


Return a list with number of hit cache lines per memory hierarchy level.


Return a list with number of missed cache lines per memory hierarchy level.


Return a list with number of stored cache lines per memory hierarchy level.


Return a list with number of evicted cache lines per memory hierarchy level.


Return verbose information about the predictor.


Report gathered analysis data in human readable form.


Return True iff this function should be considered public.


Return True iff this method should be considered public.


Parse the given file-like object and return its Module object.


Consume one token and verify it is of the expected kind.


Skip tokens in the stream until a certain token kind is reached.

        If `value` is specified, tokens whose values are different will also
        be skipped.


Parse a single docstring and return its value.


Parse a 'from x import y' statement.

        The purpose is to find __future__ statements.


Parse the 'y' part in a 'from x import y' statement.


Use docutils to check docstrings are valid RST.


Load the source for the specified file.


Trusted commands cannot be run remotely

    :param f:
    :return:


Escape newlines in any responses


Attempt to restart the bot.


Resume playback if bot is paused


List bot variables and values


Make the current window fullscreen


Set a variable.


Allow commands to have a last parameter of 'cookie=somevalue'

        TODO somevalue will be prepended onto any output lines so
        that editors can distinguish output from certain kinds
        of events they have sent.

        :param line:
        :return:


Draw a daisy at x, y


load context-free grammar


Replaces HTML special characters by readable characters.

    As taken from Leif K-Brooks algorithm on:
    http://groups-beta.google.com/group/comp.lang.python


Returns True when the url generates a "404 Not Found" error.


Determine the MIME-type of the document behind the url.

    MIME is more reliable than simply checking the document extension.
    Returns True when the MIME-type starts with anything in the list of types.


Draws a image form path, in x,y and resize it to width, height dimensions.


Draw a rectangle from x, y of width, height.

        :param startx: top left x-coordinate
        :param starty: top left y-coordinate

        :param width: height  Size of rectangle.
        :roundness: Corner roundness defaults to 0.0 (a right-angle).
        :draw: If True draws immediately.
        :fill: Optionally pass a fill color.

        :return: path representing the rectangle.


Set the current rectmode.

        :param mode: CORNER, CENTER, CORNERS
        :return: rectmode if mode is None or valid.


Set the current ellipse drawing mode.

        :param mode: CORNER, CENTER, CORNERS
        :return: ellipsemode if mode is None or valid.


Draw an arrow.

        Arrows can be two types: NORMAL or FORTYFIVE.

        :param x: top left x-coordinate
        :param y: top left y-coordinate
        :param width: width of arrow
        :param type:  NORMAL or FORTYFIVE
        :draw:  If True draws arrow immediately

        :return: Path object representing the arrow.


Move relatively to the last point.


Draw a line using relative coordinates.


Set the current transform mode.

        :param mode: CENTER or CORNER


Set a scale at which to draw objects.

        1.0 draws objects at their natural size

        :param x: Scale on the horizontal plane
        :param y: Scale on the vertical plane


Stop applying strokes to new paths.

        :return: stroke color before nostroke was called.


Set the stroke width.

        :param w: Stroke width.
        :return: If no width was specified then current width is returned.


Set the font to be used with new text instances.

        :param fontpath: path to truetype or opentype font.
        :param fontsize: size of font

        :return: current current fontpath (if fontpath param not set)
        Accepts TrueType and OpenType files. Depends on FreeType being
        installed.


Returns the height of a string of text according to the current
        font settings.

        :param txt: string to measure
        :param width: width of a line of text in a block


Graph background color.


Visualization of a node's id.


Visualization of a single edge between two nodes.


Visualization of the label accompanying an edge.


Creates a new style which inherits from the default style,
        or any other style which name is supplied to the optional template parameter.


Returns a copy of all styles and a copy of the styleguide.


Check the rules for each node in the graph and apply the style.


Returns a copy of the styleguide for the given graph.


Loads all possible TUIO profiles and returns a dictionary with the
        profile addresses as keys and an instance of a profile as the value


Tells the connection manager to receive the next 1024 byte of messages
        to analyze.


copytree that works even if folder already exists


Returns a Google news query formatted as a GoogleSearch list object.


Returns a Google blogs query formatted as a GoogleSearch list object.


Creates a unique filename in the cache for the id.


Returns the age of the cache entry, in days.


Returns a list of points where the circle and the line intersect.
            Returns an empty list when the circle and the line do not intersect.


Returns a BezierPath object with the transformation applied.


Returns bounds that encompass the intersection of the two.
            If there is no overlap between the two, None is returned.


Prints an error message, the help message and quits


Draws an outlined path of the input text


Returns a Yahoo web query formatted as a YahooSearch list object.


Returns a Yahoo images query formatted as a YahooSearch list object.


Returns a Yahoo news query formatted as a YahooSearch list object.


Flattens the given layers on the canvas.

        Merges the given layers with the indices in the list
        on the bottom layer in the list.
        The other layers are discarded.


Exports the flattened canvas.

        Flattens the canvas.
        PNG retains the alpha channel information.
        Other possibilities are JPEG and GIF.


Moves the layer up in the stacking order.


Moves the layer down in the stacking order.


Creates a copy of the current layer.

        This copy becomes the top layer on the canvas.


Increases or decreases the contrast in the layer.

        The given value is a percentage to increase
        or decrease the image contrast,
        for example 1.2 means contrast at 120%.


Inverts the layer.


Positions the layer at the given coordinates.

        The x and y parameters define where to position
        the top left corner of the layer,
        measured from the top left of the canvas.


Resizes the layer to the given width and height.

        When width w or height h is a floating-point number,
        scales percentual,
        otherwise scales to the given size in pixels.


Rotates the layer.

        Rotates the layer by given angle.
        Positive numbers rotate counter-clockwise,
        negative numbers rotate clockwise.

        Rotate commands are executed instantly,
        so many subsequent rotates will distort the image.


Flips the layer, either HORIZONTAL or VERTICAL.


Increases or decreases the sharpness in the layer.

        The given value is a percentage to increase
        or decrease the image sharpness,
        for example 0.8 means sharpness at 80%.


Returns a histogram for each RGBA channel.

        Returns a 4-tuple of lists, r, g, b, and a.
        Each list has 255 items, a count for each pixel value.


Initialise bot namespace with info in shoebot.data

        :param filename: Will be set to __file__ in the namespace


Return False if bot should quit


Sets a new accessible variable.

        :param v: Variable.


Creates a new table.

        Creates a table with the given name,
        containing the list of given fields.
        Since SQLite uses manifest typing, no data type need be supplied.
        The primary key is "id" by default,
        an integer that can be set or otherwise autoincrements.


Creates a table index.

        Creates an index on the given table,
        on the given field with unique values enforced or not,
        in ascending or descending order.


Commits any pending transactions and closes the database.


Edits the row with given id.


Deletes the row with given id.


Get the next available event or None

    :param block:
    :param timeout:
    :return: None or (event, data)


Publish an event ot any subscribers.

    :param event_t:  event type
    :param data:     event data
    :param extra_channels:
    :param wait:
    :return:


Sets call_transform_mode to point to the
        center_transform or corner_transform


Doesn't store exactly the same items as Nodebox for ease of implementation,
        it has enough to get the Nodebox Dentrite example working.


Load changed code into the execution environment.

        Until the code is executed correctly, it will be
        in the 'tenuous' state.


Attempt to known good or tenuous source.


Context in which the user can run the source in a custom manner.

        If no exceptions occur then the source will move from 'tenuous'
        to 'known good'.

        >>> with run_context() as (known_good, source, ns):
        >>> ...  exec source in ns
        >>> ...  ns['draw']()


Boids keep a small distance from other boids.

        Ensures that boids don't collide into each other,
        in a smoothly accelerated motion.


Returns the angle towards which the boid is steering.


Tendency towards a particular place.


Returns a copy of the layout for the given graph.


Remove nodes and edges and reset the layout.


Remove edges between nodes with given id's.


Returns the edge between the nodes with given id1 and id2.


Iterates the graph layout and updates node positions.


Removes all nodes with less or equal links than depth.


Calculates betweenness centrality and returns an node id -> weight dictionary.
        Node betweenness weights are updated in the process.


Calculates eigenvector centrality and returns an node id -> weight dictionary.
        Node eigenvalue weights are updated in the process.


Returns nodes sorted by betweenness centrality.
        Nodes with a lot of passing traffic will be at the front of the list.


Returns nodes with the given category attribute.


Returns a list of leaves, nodes connected to leaves, etc.


The number of edges in relation to the total number of possible edges.


Compute a cubic Bezier approximation of an elliptical arc.

    (x1, y1) and (x2, y2) are the corners of the enclosing rectangle.
    The coordinate system has coordinates that increase to the right and down.
    Angles, measured in degress, start with 0 to the right (the positive X axis)
    and increase counter-clockwise.
    The arc extends from start_angle to start_angle+extent.
    I.e. start_angle=0 and extent=180 yields an openside-down semi-circle.

    The resulting coordinates are of the form (x1,y1, x2,y2, x3,y3, x4,y4)
    such that the curve goes from (x1, y1) to (x4, y4) with (x2, y2) and
    (x3, y3) as their respective Bezier control points.


The angle in degrees between two vectors.


If size is not set, otherwise set size to DEFAULT_SIZE
        and return it.

        This means, only the first call to size() is valid.


Passes the drawqueue to the sink for rendering


Reflects the point x, y through origin x0, y0.


Returns true when x, y is on the path stroke outline.


Exports the path as SVG.

        Uses the filename given when creating this object.
        The file is automatically updated to reflect
        changes to the path.


Handle right mouse button clicks


Hide the variables window


Toggle fullscreen from outside the GUI,
        causes the GUI to updated and run all its actions.


Widget Action to set Windowed Mode.


Widget Action to Close the window, triggering the quit event.


Widget Action to Toggle fullscreen from the GUI


Widget Action to toggle showing the variables window.


Called from main loop, if your sink needs to handle GUI events
        do it here.

        Check any GUI flags then call Gtk.main_iteration to update things.


GUI callback for key pressed


Create an object, if fill, stroke or strokewidth
        is not specified, get them from the _canvas

        :param clazz:
        :param args:
        :param kwargs:
        :return:


Returns an Image object of the current surface. Used for displaying
        output in Jupyter notebooks. Adapted from the cairo-jupyter project.


Set the canvas size

        Only the first call will actually be effective.

        :param w: Width
        :param h: height


Set animation framerate.

        :param framerate: Frames per second to run bot.
        :return: Current framerate of animation.


Set callbacks for input events


Returns the color and its complement in a list.


Returns a list of complementary colors.

    The complement is the color 180 degrees across
    the artistic RYB color wheel.
    The list contains darker and softer contrasting
    and complementing colors.


Returns a list with the split complement of the color.

    The split complement are the two colors to the left and right
    of the color's complement.


Returns the left half of the split complement.

    A list is returned with the same darker and softer colors
    as in the complementary list, but using the hue of the
    left split complement instead of the complement itself.


Returns the right half of the split complement.


Returns a triad of colors.

    The triad is made up of this color and two other colors
    that together make up an equilateral triangle on
    the artistic color wheel.


Returns a tetrad of colors.

    The tetrad is made up of this color and three other colors
    that together make up a cross on the artistic color wheel.


Guesses the shade and hue name of a color.

    If the given color is named in the named_colors list, return that name.
    Otherwise guess its nearest hue and shade range.


A dictionary of all aggregated words.

    They keys in the dictionary correspond to subfolders in the aggregated cache.
    Each key has a list of words. Each of these words is the name of an XML-file
    in the subfolder. The XML-file contains color information harvested from the web
    (or handmade).


Returns a list of colors drawn from a morgueFile image.

    With the Web library installed,
    downloads a thumbnail from morgueFile and retrieves pixel colors.


Returns the name of the nearest named hue.

        For example,
        if you supply an indigo color (a color between blue and violet),
        the return value is "violet". If primary is set  to True,
        the return value is "purple".

        Primary colors leave out the fuzzy lime, teal,
        cyan, azure and violet hues.


Returns a mix of two colors.


Rectangle swatch for this color.


Returns a list of colors based on pixel values in the image.

        The Core Image library must be present to determine pixel colors.
        F. Albers: http://nodebox.net/code/index.php/shared_2007-06-11-11-37-05


Sorts the list by cmp1, then cuts it into n pieces which are sorted by cmp2.

        If you want to cluster by hue, use n=12 (since there are 12 primary/secondary hues).
        The resulting list will not contain n even slices:
        n is used rather to slice up the cmp1 property of the colors,
        e.g. cmp1=brightness and n=3 will cluster colors by brightness >= 0.66, 0.33, 0.0


Returns a list that is a repetition of the given list.

        When oscillate is True,
        moves from the end back to the beginning,
        and then from the beginning to the end, and so on.


Rectangle swatches for all the colors in the list.


Fancy random ovals for all the colors in the list.


Returns intermediary colors for given list of colors.


Populates the list with a number of gradient colors.

        The list has Gradient.steps colors that interpolate between
        the fixed base Gradient.colors.

        The spread parameter controls the midpoint of the gradient,
        you can shift it right and left. A separate gradient is
        calculated for each half and then glued together.


Returns a copy of the range.

        Optionally, supply a color to get a range copy
        limited to the hue of that color.


Returns a color with random values in the defined h, s b, a ranges.

        If a color is given, use that color's hue and alpha,
        and generate its saturation and brightness from the shade.
        The hue is varied with the given d.

        In this way you could have a "warm" color range
        that returns all kinds of warm colors.
        When a red color is given as parameter it would generate
        all kinds of warm red colors.


Returns True if the given color is part of this color range.

        Check whether each h, s, b, a component of the color
        falls within the defined range for that component.

        If the given color is grayscale,
        checks against the definitions for black and white.


Returns the color information as XML.

        The XML has the following structure:
        <colors query="">
            <color name="" weight="" />
                <rgb r="" g="" b="" />
                <shade name="" weight="" />
            </color>
        </colors>

        Notice that ranges are stored by name and retrieved in the _load()
        method with the shade() command - and are thus expected to be
        shades (e.g. intense, warm, ...) unless the shade() command would
        return any custom ranges as well. This can be done by appending custom
        ranges to the shades list.


Saves the color information in the cache as XML.


Returns a random color within the theme.

        Fetches a random range (the weight is taken into account,
        so ranges with a bigger weight have a higher chance of propagating)
        and hues it with the associated color.


Returns a number of random colors from the theme.


fseq messages associate a unique frame id with a set of set
        and alive messages


Returns a generator list of tracked objects which are recognized with
        this profile and are in the current session.


Returns coordinates for point at t on the spline.
            Calculates the coordinates of x and y for a point at t on the cubic bezier spline,
            and its control points, based on the de Casteljau interpolation algorithm.
            The t parameter is a number between 0.0 and 1.0,
            x0 and y0 define the starting point of the spline,
            x1 and y1 its control point,
            x3 and y3 the ending point of the spline,
            x2 and y2 its control point.
            If the handles parameter is set, returns not only the point at t,
            but the modified control points of p0 and p3 should this point split the path as well.


Returns the length of the path.
            Calculates the length of each spline in the path, using n as a number of points to measure.
            When segmented is True, returns a list containing the individual length of each spline
            as values between 0.0 and 1.0, defining the relative length of each spline
            in relation to the total path length.


Yields all elements as PathElements


Iterate through a gtk container, `parent`,
    and return the widget with the name `name`.


Find shoebot executable


Returns the meta description in the page.


Returns the meta keywords in the page.


Returns a sorted copy of the list.


Returns a copy of the list without duplicates.


Tries to interpret the next 8 bytes of the data
    as a 64-bit signed integer.


Converts a typetagged OSC message to a Python list.


Given OSC data, tries to call the callback with the
        right address.


Sends decoded OSC data to an appropriate calback


Adds a callback to our set of callbacks,
        or removes the callback with name if callback
        is None.


Check whether there is no more content to expect.


Send new source code to the bot

        :param source:
        :param good_cb: callback called if code was good
        :param bad_cb: callback called if code was bad (will get contents of exception)
        :return:


Close outputs of process.


Get responses to commands sent


If python-gi-cairo is not installed, using PangoCairo.create_context
    dies with an unhelpful KeyError, check for that and output somethig
    useful.


Determines if an item in a paragraph is a list.

    If all of the lines in the markup start with a "*" or "1."
    this indicates a list as parsed by parse_paragraphs().
    It can be drawn with draw_list().


Uses mimetex to generate a GIF-image from the LaTeX equation.


Draws list markup with indentation in NodeBox.

    Draw list markup at x, y coordinates
    using indented bullets or numbers.
    The callback is a command that takes a str and an int.


This is a very poor algorithm to draw Wikipedia tables in NodeBox.


Returns a list of images found in the markup.

        An image has a pathname, a description in plain text
        and a list of properties Wikipedia uses to size and place images.

        # A Wikipedia image looks like:
        # [[Image:Columbia Supercomputer - NASA Advanced Supercomputing Facility.jpg|right|thumb|
        #   The [[NASA]] [[Columbia (supercomputer)|Columbia Supercomputer]].]]
        # Parts are separated by "|".
        # The first part is the image file, the last part can be a description.
        # In between are display properties, like "right" or "thumb".


Creates a link from the table to paragraph and vice versa.

        Finds the first heading above the table in the markup.
        This is the title of the paragraph the table belongs to.


Returns a list of tables in the markup.

        A Wikipedia table looks like:
        {| border="1"
        |-
        |Cell 1 (no modifier - not aligned)
        |-
        |align="right" |Cell 2 (right aligned)
        |-
        |}


Returns a list of words that appear in bold in the article.

        Things like table titles are not added to the list,
        these are probably bold because it makes the layout nice,
        not necessarily because they are important.


Given a Variable and a value, cleans it out


Convenience method that works with all 2.x versions of Python
    to determine whether or not something is listlike.


Convenience method that works with all 2.x versions of Python
    to determine whether or not something is stringlike.


Sets up the initial relations between this element and
        other elements.


Finds the last element beneath this object to be parsed.


Returns the first item that matches the given criteria and
        appears after this Tag in the document.


Returns the siblings of this Tag that match the given
        criteria and appear after this Tag in the document.


Returns the closest sibling to this Tag that matches the
        given criteria and appears before this Tag in the document.


Returns the siblings of this Tag that match the given
        criteria and appear before this Tag in the document.


Returns the parents of this Tag that match the given
        criteria.


Encodes an object to a string in some encoding, or to Unicode.
        .


Cheap function to invert a hash.


Used in a call to re.sub to replace HTML, XML, and numeric
        entities with the appropriate Unicode characters. If HTML
        entities are being converted, any unrecognized entities are
        escaped.


Recursively destroys the contents of this tree.


Renders the contents of this tag as a string in the given
        encoding. If encoding is None, returns a Unicode string..


Return only the first child of this Tag matching the given
        criteria.


Returns true iff the given string is the name of a
        self-closing tag according to this parser.


Adds a certain piece of text to the tree as a NavigableString
        subclass.


Handle a processing instruction as a ProcessingInstruction
        object, possibly one with a %SOUP-ENCODING% slot into which an
        encoding will be plugged later.


Handle character references as data.


Treat a bogus SGML declaration as raw data. Treat a CDATA
        declaration as a CData object.


Beautiful Soup can detect a charset included in a META tag,
        try to convert the document to that charset, and re-parse the
        document from the beginning.


Changes a MS smart quote character to an XML or HTML
        entity.


Given a string and its encoding, decodes the string into Unicode.
        %encoding is a string recognized by encodings.aliases


Given a document, tries to detect its XML encoding.


Scale context based on difference between bot size and widget


Draw just the exposed part of the backing store, scaled to fit


Creates a recording surface for the bot to draw on

        :param size: The width and height of bot


Return a JSON string representation of a Python data structure.

        >>> JSONEncoder().encode({"foo": ["bar", "baz"]})
        '{"foo": ["bar", "baz"]}'


Called when CairoCanvas needs a cairo context to draw on


Function to output to a cairo surface

        target is a cairo Context or filename
        if file_number is set, then files will be numbered
        (this is usually set to the current frame number)


Create canvas and sink for attachment to a bot

    canvas is what draws images, 'sink' is the final consumer of the images

    :param src: Defaults for title or outputfile if not specified.

    :param format: CairoImageSink image format, if using buff instead of outputfile
    :param buff: CairoImageSink buffer object to send output to

    :param outputfile: CairoImageSink output filename e.g. "hello.svg"
    :param multifile: CairoImageSink if True,

    :param title: ShoebotWindow - set window title
    :param fullscreen: ShoebotWindow - set window title
    :param show_vars: ShoebotWindow - display variable window

    Two kinds of sink are provided: CairoImageSink and ShoebotWindow

    ShoebotWindow

    Displays a window to draw shoebot inside.

    CairoImageSink

    Output to a filename (or files if multifile is set), or a buffer object.


Return True if the buffer was saved


Called when a slider is adjusted.


var was added in the bot while it ran, possibly
        by livecoding

        :param v:
        :return:


var was added in the bot

        :param v:
        :return:


Returns cached copies unless otherwise specified.


Expand the path with color information.

    Attempts to extract fill and stroke colors
    from the element and adds it to path attributes.


Returns a copy of the event handler, remembering the last node clicked.


Drags given node to mouse location.


Displays a popup when hovering over a node.


Returns a cached textpath of the given text in queue.


Draws a popup rectangle with a rotating text queue.


write FILENAME
        Write a local copy of FILENAME using FILENAME_tweaks for local tweaks.


Amend a filename with a suffix.

    amend_filename("foo.txt", "_tweak") --> "foo_tweak.txt"


check FILENAME
        Check that FILENAME has not been edited since writing.


Check that a checker's visitors are correctly named.

    A checker has methods named visit_NODETYPE, but it's easy to mis-name
    a visit method, and it will never be called.  This decorator checks
    the class to see that all of its visitors are named after an existing
    node class.


Parse the pylint output-format=parseable lines into PylintError tuples.


The edx_lint command entry point.


Print the help string for the edx_lint command.


Parse the description in the README file

    CommandLine:
        python -c "import setup; print(setup.parse_description())"


Create a transformation class object

    Parameters
    ----------
    name : str
        Name of the transformation
    transform : callable ``f(x)``
        A function (preferably a `ufunc`) that computes
        the transformation.
    inverse : callable ``f(x)``
        A function (preferably a `ufunc`) that computes
        the inverse of the transformation.
    breaks : callable ``f(limits)``
        Function to compute the breaks for this transform.
        If None, then a default good enough for a linear
        domain is used.
    minor_breaks : callable ``f(major, limits)``
        Function to compute the minor breaks for this
        transform. If None, then a default good enough for
        a linear domain is used.
    _format : callable ``f(breaks)``
        Function to format the generated breaks.
    domain : array_like
        Domain over which the transformation is valid.
        It should be of length 2.
    doc : str
        Docstring for the class.
    **kwargs : dict
        Attributes of the transform, e.g if base is passed
        in kwargs, then `t.base` would be a valied attribute.

    Returns
    -------
    out : trans
        Transform class


Return a trans object

    Parameters
    ----------
    t : str | callable | type | trans
        name of transformation function

    Returns
    -------
    out : trans


Calculate breaks in data space and return them
        in transformed space.

        Expects limits to be in *transform space*, this
        is the same space as that where the domain is
        specified.

        This method wraps around :meth:`breaks_` to ensure
        that the calculated breaks are within the domain
        the transform. This is helpful in cases where an
        aesthetic requests breaks with limits expanded for
        some padding, yet the expansion goes beyond the
        domain of the transform. e.g for a probability
        transform the breaks will be in the domain
        ``[0, 1]`` despite any outward limits.

        Parameters
        ----------
        limits : tuple
            The scale limits. Size 2.

        Returns
        -------
        out : array_like
            Major breaks


Transform from date to a numerical format


Rescale numeric vector to have specified minimum and maximum.

    Parameters
    ----------
    x : array_like | numeric
        1D vector of values to manipulate.
    to : tuple
        output range (numeric vector of length two)
    _from : tuple
        input range (numeric vector of length two).
        If not given, is calculated from the range of x

    Returns
    -------
    out : array_like
        Rescaled values

    Examples
    --------
    >>> x = [0, 2, 4, 6, 8, 10]
    >>> rescale(x)
    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])
    >>> rescale(x, to=(0, 2))
    array([0. , 0.4, 0.8, 1.2, 1.6, 2. ])
    >>> rescale(x, to=(0, 2), _from=(0, 20))
    array([0. , 0.2, 0.4, 0.6, 0.8, 1. ])


Rescale numeric vector to have specified maximum.

    Parameters
    ----------
    x : array_like | numeric
        1D vector of values to manipulate.
    to : tuple
        output range (numeric vector of length two)
    _from : tuple
        input range (numeric vector of length two).
        If not given, is calculated from the range of x.
        Only the 2nd (max) element is essential to the
        output.

    Returns
    -------
    out : array_like
        Rescaled values

    Examples
    --------
    >>> x = [0, 2, 4, 6, 8, 10]
    >>> rescale_max(x, (0, 3))
    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])

    Only the 2nd (max) element of the parameters ``to``
    and ``_from`` are essential to the output.

    >>> rescale_max(x, (1, 3))
    array([0. , 0.6, 1.2, 1.8, 2.4, 3. ])
    >>> rescale_max(x, (0, 20))
    array([ 0.,  4.,  8., 12., 16., 20.])

    If :python:`max(x) < _from[1]` then values will be
    scaled beyond the requested (:python:`to[1]`) maximum.

    >>> rescale_max(x, to=(1, 3), _from=(-1, 6))
    array([0., 1., 2., 3., 4., 5.])


Truncate infinite values to a range.

    Parameters
    ----------
    x : array_like
        Values that should have infinities squished.
    range : tuple
        The range onto which to squish the infinites.
        Must be of size 2.

    Returns
    -------
    out : array_like
        Values with infinites squished.

    Examples
    --------
    >>> squish_infinite([0, .5, .25, np.inf, .44])
    [0.0, 0.5, 0.25, 1.0, 0.44]
    >>> squish_infinite([0, -np.inf, .5, .25, np.inf], (-10, 9))
    [0.0, -10.0, 0.5, 0.25, 9.0]


Squish values into range.

    Parameters
    ----------
    x : array_like
        Values that should have out of range values squished.
    range : tuple
        The range onto which to squish the values.
    only_finite: boolean
        When true, only squishes finite values.

    Returns
    -------
    out : array_like
        Values with out of range values squished.

    Examples
    --------
    >>> squish([-1.5, 0.2, 0.5, 0.8, 1.0, 1.2])
    [0.0, 0.2, 0.5, 0.8, 1.0, 1.0]

    >>> squish([-np.inf, -1.5, 0.2, 0.5, 0.8, 1.0, np.inf], only_finite=False)
    [0.0, 0.0, 0.2, 0.5, 0.8, 1.0, 1.0]


Determine if range of vector is close to zero.

    Parameters
    ----------
    x : array_like | numeric
        Value(s) to check. If it is an array_like, it
        should be of length 2.
    tol : float
        Tolerance. Default tolerance is the `machine epsilon`_
        times :math:`10^2`.

    Returns
    -------
    out : bool
        Whether ``x`` has zero range.

    Examples
    --------
    >>> zero_range([1, 1])
    True
    >>> zero_range([1, 2])
    False
    >>> zero_range([1, 2], tol=2)
    True

    .. _machine epsilon: https://en.wikipedia.org/wiki/Machine_epsilon


Expand a range with a multiplicative or additive constants

    Similar to :func:`expand_range` but both sides of the range
    expanded using different constants

    Parameters
    ----------
    range : tuple
        Range of data. Size 2
    expand : tuple
        Length 2 or 4. If length is 2, then the same constants
        are used for both sides. If length is 4 then the first
        two are are the Multiplicative (*mul*) and Additive (*add*)
        constants for the lower limit, and the second two are
        the constants for the upper limit.
    zero_width : int | float | timedelta
        Distance to use if range has zero width

    Returns
    -------
    out : tuple
        Expanded range

    Examples
    --------
    >>> expand_range_distinct((3, 8))
    (3, 8)
    >>> expand_range_distinct((0, 10), (0.1, 0))
    (-1.0, 11.0)
    >>> expand_range_distinct((0, 10), (0.1, 0, 0.1, 0))
    (-1.0, 11.0)
    >>> expand_range_distinct((0, 10), (0.1, 0, 0, 0))
    (-1.0, 10)
    >>> expand_range_distinct((0, 10), (0, 2))
    (-2, 12)
    >>> expand_range_distinct((0, 10), (0, 2, 0, 2))
    (-2, 12)
    >>> expand_range_distinct((0, 10), (0, 0, 0, 2))
    (0, 12)
    >>> expand_range_distinct((0, 10), (.1, 2))
    (-3.0, 13.0)
    >>> expand_range_distinct((0, 10), (.1, 2, .1, 2))
    (-3.0, 13.0)
    >>> expand_range_distinct((0, 10), (0, 0, .1, 2))
    (0, 13.0)


Append 2 extra breaks at either end of major

        If breaks of transform space are non-equidistant,
        :func:`minor_breaks` add minor breaks beyond the first
        and last major breaks. The solutions is to extend those
        breaks (in transformed space) before the minor break call
        is made. How the breaks depends on the type of transform.


Determine good units for representing a sequence of timedeltas


Convert sequence of numerics to timedelta


Convert timedelta to a number corresponding to the
        appropriate units. The appropriate units are those
        determined with the object is initialised.


Round to multiple of any number.


Return the minimum and maximum of x

    Parameters
    ----------
    x : array_like
        Sequence
    na_rm : bool
        Whether to remove ``nan`` values.
    finite : bool
        Whether to consider only finite values.

    Returns
    -------
    out : tuple
        (minimum, maximum) of x


Return nearest long integer to x


Check if value is close to an integer

    Parameters
    ----------
    x : float
        Numeric value to check

    Returns
    -------
    out : bool


Helper to format and tidy up


Get a set of evenly spaced colors in HLS hue space.

    h, l, and s should be between 0 and 1

    Parameters
    ----------

    n_colors : int
        number of colors in the palette
    h : float
        first hue
    l : float
        lightness
    s : float
        saturation

    Returns
    -------
    palette : list
        List of colors as RGB hex strings.

    See Also
    --------
    husl_palette : Make a palette using evenly spaced circular
        hues in the HUSL system.

    Examples
    --------
    >>> len(hls_palette(2))
    2
    >>> len(hls_palette(9))
    9


Utility for making hue palettes for color schemes.

    Parameters
    ----------
    h : float
        first hue. In the [0, 1] range
    l : float
        lightness. In the [0, 1] range
    s : float
        saturation. In the [0, 1] range
    color_space : 'hls' | 'husl'
        Color space to use for the palette

    Returns
    -------
    out : function
        A discrete color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        equally spaced colors. Though the palette
        is continuous, since it is varies the hue it
        is good for categorical data. However if ``n``
        is large enough the colors show continuity.

    Examples
    --------
    >>> hue_pal()(5)
    ['#db5f57', '#b9db57', '#57db94', '#5784db', '#c957db']
    >>> hue_pal(color_space='husl')(5)
    ['#e0697e', '#9b9054', '#569d79', '#5b98ab', '#b675d7']


Utility for making a brewer palette

    Parameters
    ----------
    type : 'sequential' | 'qualitative' | 'diverging'
        Type of palette. Sequential, Qualitative or
        Diverging. The following abbreviations may
        be used, ``seq``, ``qual`` or ``div``.

    palette : int | str
        Which palette to choose from. If is an integer,
        it must be in the range ``[0, m]``, where ``m``
        depends on the number sequential, qualitative or
        diverging palettes. If it is a string, then it
        is the name of the palette.

    Returns
    -------
    out : function
        A color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        colors. The maximum value of ``n`` varies
        depending on the parameters.

    Examples
    --------
    >>> brewer_pal()(5)
    ['#EFF3FF', '#BDD7E7', '#6BAED6', '#3182BD', '#08519C']
    >>> brewer_pal('qual')(5)
    ['#7FC97F', '#BEAED4', '#FDC086', '#FFFF99', '#386CB0']
    >>> brewer_pal('qual', 2)(5)
    ['#1B9E77', '#D95F02', '#7570B3', '#E7298A', '#66A61E']
    >>> brewer_pal('seq', 'PuBuGn')(5)
    ['#F6EFF7', '#BDC9E1', '#67A9CF', '#1C9099', '#016C59']

    The available color names for each palette type can be
    obtained using the following code::

        import palettable.colorbrewer as brewer

        print([k for k in brewer.COLOR_MAPS['Sequential'].keys()])
        print([k for k in brewer.COLOR_MAPS['Qualitative'].keys()])
        print([k for k in brewer.COLOR_MAPS['Diverging'].keys()])


Create a n color gradient palette

    Parameters
    ----------
    colors : list
        list of colors
    values : list, optional
        list of points in the range [0, 1] at which to
        place each color. Must be the same size as
        `colors`. Default to evenly space the colors
    name : str
        Name to call the resultant MPL colormap

    Returns
    -------
    out : function
        Continuous color palette that takes a single
        parameter either a :class:`float` or a sequence
        of floats maps those value(s) onto the palette
        and returns color(s). The float(s) must be
        in the range [0, 1].

    Examples
    --------
    >>> palette = gradient_n_pal(['red', 'blue'])
    >>> palette([0, .25, .5, .75, 1])
    ['#ff0000', '#bf0040', '#7f0080', '#3f00c0', '#0000ff']


Create a continuous palette using an MPL colormap

    Parameters
    ----------
    name : str
        Name of colormap
    lut : None | int
        This is the number of entries desired in the lookup table.
        Default is ``None``, leave it up Matplotlib.

    Returns
    -------
    out : function
        Continuous color palette that takes a single
        parameter either a :class:`float` or a sequence
        of floats maps those value(s) onto the palette
        and returns color(s). The float(s) must be
        in the range [0, 1].

    Examples
    --------
    >>> palette = cmap_pal('viridis')
    >>> palette([.1, .2, .3, .4, .5])
    ['#482475', '#414487', '#355f8d', '#2a788e', '#21918c']


Create a discrete palette using an MPL Listed colormap

    Parameters
    ----------
    name : str
        Name of colormap
    lut : None | int
        This is the number of entries desired in the lookup table.
        Default is ``None``, leave it up Matplotlib.

    Returns
    -------
    out : function
        A discrete color palette that takes a single
        :class:`int` parameter ``n`` and returns ``n``
        colors. The maximum value of ``n`` varies
        depending on the parameters.

    Examples
    --------
    >>> palette = cmap_d_pal('viridis')
    >>> palette(5)
    ['#440154', '#3b528b', '#21918c', '#5cc863', '#fde725']


Create a palette from a list of values

    Parameters
    ----------
    values : sequence
        Values that will be returned by the palette function.

    Returns
    -------
    out : function
        A function palette that takes a single
        :class:`int` parameter ``n`` and returns ``n`` values.

    Examples
    --------
    >>> palette = manual_pal(['a', 'b', 'c', 'd', 'e'])
    >>> palette(3)
    ['a', 'b', 'c']


Scale data continuously

        Parameters
        ----------
        x : array_like
            Continuous values to scale
        palette : callable ``f(x)``
            Palette to use
        na_value : object
            Value to use for missing values.
        trans : trans
            How to transform the data before scaling. If
            ``None``, no transformation is done.

        Returns
        -------
        out : array_like
            Scaled values


Map values to a continuous palette

        Parameters
        ----------
        x : array_like
            Continuous values to scale
        palette : callable ``f(x)``
            palette to use
        na_value : object
            Value to use for missing values.
        oob : callable ``f(x)``
            Function to deal with values that are
            beyond the limits

        Returns
        -------
        out : array_like
            Values mapped onto a palette


Register a parser for a attribute type.

        Parsers will be used to parse `str` type objects from either
        the commandline arguments or environment variables.

        Args:
            type: the type the decorated function will be responsible
                for parsing a environment variable to.


Used to patch cookiecutter's ``run_hook`` function.

    This patched version ensures that the temple.yaml file is created before
    any cookiecutter hooks are executed


Uses cookiecutter to generate files for the project.

    Monkeypatches cookiecutter's "run_hook" to ensure that the temple.yaml file is
    generated before any hooks run. This is important to ensure that hooks can also
    perform any actions involving temple.yaml


Sets up a new project from a template

    Note that the `temple.constants.TEMPLE_ENV_VAR` is set to 'setup' during the duration
    of this function.

    Args:
        template (str): The git SSH path to a template
        version (str, optional): The version of the template to use when updating. Defaults
            to the latest version


Parses Github's link header for pagination.

    TODO eventually use a github client for this


Update package with latest template. Must be inside of the project
    folder to run.

    Using "-e" will prompt for re-entering the template parameters again
    even if the project is up to date.

    Use "-v" to update to a particular version of a template.

    Using "-c" will perform a check that the project is up to date
    with the latest version of the template (or the version specified by "-v").
    No updating will happen when using this option.


List packages created with temple. Enter a github user or
    organization to list all templates under the user or org.
    Using a template path as the second argument will list all projects
    that have been started with that template.

    Use "-l" to print the Github repository descriptions of templates
    or projects.


Switch a project's template to a different template.


Returns True if inside a git repo, False otherwise


Return True if the target branch exists.


Raises `ExistingBranchError` if the specified branch exists.


Raises `InvalidTempleProjectError` if repository is not a temple project


Determine the current git branch


Cleans up temporary resources

    Tries to clean up:

    1. The temporary update branch used during ``temple update``
    2. The primary update branch used during ``temple update``


Given an old version and new version, check if the cookiecutter.json files have changed

    When the cookiecutter.json files change, it means the user will need to be prompted for
    new context

    Args:
        template (str): The git SSH path to the template
        old_version (str): The git SHA of the old version
        new_version (str): The git SHA of the new version

    Returns:
        bool: True if the cookiecutter.json files have been changed in the old and new versions


Apply a template to a temporary directory and then copy results to target.


Writes the temple YAML configuration


Obtains the configuration used for cookiecutter templating

    Args:
        template: Path to the template
        default_config (dict, optional): The default configuration
        version (str, optional): The git SHA or branch to use when
            checking out template. Defaults to latest version

    Returns:
        tuple: The cookiecutter repo directory and the config dict


Decorator that sets the temple command env var to value


Perform a github API call

        Args:
            verb (str): Can be "post", "put", or "get"
            url (str): The base URL with a leading slash for Github API (v3)
            auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object


Deploys the package and documentation.

    Proceeds in the following steps:

    1. Ensures proper environment variables are set and checks that we are on Circle CI
    2. Tags the repository with the new version
    3. Creates a standard distribution and a wheel
    4. Updates version.py to have the proper version
    5. Commits the ChangeLog, AUTHORS, and version.py file
    6. Pushes to PyPI
    7. Pushes the tags and newly committed files

    Raises:
        `EnvironmentError`:
            - Not running on CircleCI
            - `*_PYPI_USERNAME` and/or `*_PYPI_PASSWORD` environment variables
               are missing
            - Attempting to deploy to production from a branch that isn't master


Record a purchase in Sailthru

    Arguments:
        sailthru_client (object): SailthruClient
        email (str): user's email address
        item (dict): Sailthru required information about the course
        purchase_incomplete (boolean): True if adding item to shopping cart
        message_id (str): Cookie used to identify marketing campaign
        options (dict): Sailthru purchase API options (e.g. template name)

    Returns:
        False if retryable error, else True


Get course information using the Sailthru content api or from cache.

    If there is an error, just return with an empty response.

    Arguments:
        course_id (str): course key of the course
        course_url (str): LMS url for course info page.
        sailthru_client (object): SailthruClient
        site_code (str): site code
        config (dict): config options

    Returns:
        course information from Sailthru


Get course information using the Ecommerce course api.

    In case of error returns empty response.
    Arguments:
        course_id (str): course key of the course
        site_code (str): site code

    Returns:
        course information from Ecommerce