def save_db(db_obj, fname):
    """Save the database.
    Args:
        db_obj: Instance of type IndexStructurePacked or IndexStructureGapped.

        fname: File name (string) of save file.

    Returns:
        -
    """
    import pickle
    with open(fname, 'wb') as file:
        pickle.dump(db_obj, file)


def is_mkey(sline):
    """
    Check if the given splitted line is a main key.

    Parameters
    ----------
    sline : list of str
        given splitted line
    """
    return sline[0][0] == '#'


def alpine_to_hostspec(arch):
    """
    See: abuild source code/functions.sh.in: arch_to_hostspec()
    """
    mapping = {'aarch64': 'aarch64-alpine-linux-musl', 'armel':
        'armv5-alpine-linux-musleabi', 'armhf':
        'armv6-alpine-linux-musleabihf', 'armv7':
        'armv7-alpine-linux-musleabihf', 'mips': 'mips-alpine-linux-musl',
        'mips64': 'mips64-alpine-linux-musl', 'mipsel':
        'mipsel-alpine-linux-musl', 'mips64el':
        'mips64el-alpine-linux-musl', 'ppc': 'powerpc-alpine-linux-musl',
        'ppc64': 'powerpc64-alpine-linux-musl', 'ppc64le':
        'powerpc64le-alpine-linux-musl', 's390x': 's390x-alpine-linux-musl',
        'x86': 'i586-alpine-linux-musl', 'x86_64': 'x86_64-alpine-linux-musl'}
    if arch in mapping:
        return mapping[arch]
    raise ValueError("Can not map Alpine architecture '" + arch +
        "' to the right hostspec value")


def create_token_lst(s, str_to_token):
    """create token list:
    'True or False' -> [True, lambda..., False]"""
    s = s.replace('(', ' ( ')
    s = s.replace(')', ' ) ')
    out = []
    for it in s.split():
        if it in ['not', 'and', 'or']:
            out.append(it)
        else:
            out.append(str_to_token[it])
    return out


def crc(data):
    """Calculate 16-bit CRC-16-CCITT for data."""
    rem = 65535
    for d in bytearray(data):
        rem ^= d << 8
        for _ in range(8):
            rem <<= 1
            if rem & 65536:
                rem ^= 4129
            rem &= 65535
    return rem ^ 65535


def _to_rgba(color):
    """
    Converts a color to RGBA.

    Parameters
    ----------
    color : int, float or list
        If numeric, is interpreted as gray-value between 0 and 1. If list, has to have length 3 or 4 and is interpreted
        as RGB / RGBA depending on length (again, with values in [0, 1]).

    Returns
    -------
    list

    """
    if isinstance(color, (int, float)):
        result = [color, color, color, 1]
    elif isinstance(color, list):
        if len(color) == 3:
            result = color + [1]
        elif len(color) == 4:
            result = color.copy()
        else:
            assert False, f'len({color}) = {len(color)} has to be in [3, 4]'
    else:
        assert False, f'color specification not understood: {color}'
    return result


def cum_pattern(data):
    """
        [Description] : Utility method to calculate cumulative sum of sequential no.s if sign is same.
    """
    prev = 0
    out = []
    for l in data:
        new = l + prev if l * prev > 0 else l
        out.append(new)
        prev = new
    return out


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def prune_full_conflicts(data):
    """removes values that have all other values as conflicts"""
    all_vals, to_pop = set(data), set()
    for val in data:
        conflicts = set(data[val].get('conflicts', set()))
        conflicts.intersection_update(all_vals)
        conflicts.update(set([val]))
        if len(conflicts) == len(all_vals):
            to_pop.add(val)
    for val in to_pop:
        data.pop(val)


@classmethod
def set_suppress(cls, suppress):
    """
        Turn on/off exception suppression for methods decorated by :class:`SuppressException`

        :param suppress: boolean True/False
        """
    cls._suppress = suppress


@classmethod
def render(cls, **kwargs):
    """
        Render the LICENSE file
        """
    cls._check()
    kwargs = cls._add_year_to_kwargs(kwargs)
    template = cls.jinja_env.get_template(cls.id)
    return template.render(**kwargs)


def mkTimeTuple(timeString):
    """Convert a 'dd/mm/yyyy' formatted string to a tuple for use in the time module."""
    list = [0] * 9
    dd, mm, yyyy = list(map(int, timeString.split('/')))
    list[:3] = [yyyy, mm, dd]
    return tuple(list)


@classmethod
def getHeapUsage(cls):
    """Returns the JavaScript heap usage.
It is the total usage of the corresponding isolate not scoped to a particular Runtime.
        """
    return cls.build_send_payload('getHeapUsage', {}), cls.convert_payload({
        'usedSize': {'class': float, 'optional': False}, 'totalSize': {
        'class': float, 'optional': False}})


def getExpression():
    """Return the filter expression."""


def getid(obj):
    """Return id if argument is a Resource.

    Abstracts the common pattern of allowing both an object or an object's ID
    (UUID) as a parameter when dealing with relationships.
    """
    try:
        if obj.uuid:
            return obj.uuid
    except AttributeError:
        pass
    try:
        return obj.id
    except AttributeError:
        return obj


def replace_all(text, replace_dict):
    """
    Replace multiple strings in a text.

    .. note::

        Replacements are made successively, without any warranty on the order         in which they are made.

    :param text: Text to replace in.
    :param replace_dict: Dictionary mapping strings to replace with their             substitution.
    :returns: Text after replacements.

    >>> replace_all("foo bar foo thing", {"foo": "oof", "bar": "rab"})
    'oof rab oof thing'
    """
    for i, j in replace_dict.items():
        text = text.replace(i, j)
    return text


def get_trello_board(trello_token, board_id):
    """ Get the JSON data for a specific board.
    """
    client = trello_token.client
    return client.boards.get(board_id=board_id)


def expand(function):
    """Useful for functional operations like map."""
    return lambda args: function(*args)


@classmethod
def get_by_example_skiplist(cls, collection, index_id, example_data,
    allow_multiple=True, skip=None, limit=None):
    """
            This will find all documents matching a given example, using the specified skiplist index.

            :param collection Collection instance
            :param index_id ID of the index which should be used for the query
            :param example_data The example document
            :param allow_multiple If the query can return multiple documents
            :param skip  The number of documents to skip in the query
            :param limit The maximal amount of documents to return. The skip is applied before the limit restriction.

            :returns Single document / Document list
        """
    kwargs = {'index': index_id, 'skip': skip, 'limit': limit}
    return cls._construct_query(name='by-example-skiplist', collection=
        collection, example=example_data, multiple=allow_multiple, **kwargs)


def broadcast_greater(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Returns the result of element-wise **greater than** (>) comparison operation with broadcasting.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_greater(x, y) = [[ 1.,  1.,  1.],
                                  [ 0.,  0.,  0.]]

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_logic.cc:L82

    Parameters
    ----------
    lhs : NDArray
        First input to the function
    rhs : NDArray
        Second input to the function

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def normalize_db_spectrogram(db_spec, high=20.0, low=-100.0):
    """
    Normalizes db spectrum with zero mean and unit variance.
    In normal cases, librosa generates db spectrum having -100dB as maximum.

    Args:
        db_spec: db spectrum
        high (float): maximum decibel value
        low (float): minimum decibel value

    Returns:
        normalized db spectrum
    """
    mid = (low + high) / 2.0
    scale = high - mid
    return (db_spec - mid) / scale


@classmethod
def tfa_change_status(cls, val):
    """
        Create an instance of this class set to the ``tfa_change_status`` tag
        with value ``val``.

        :param TfaChangeStatusType val:
        :rtype: EventType
        """
    return cls('tfa_change_status', val)


@staticmethod
def internally_instrumented(fn):
    """Tag the method as instrumented.

        This tag will prevent any decoration from being applied to the
        method. Use this if you are orchestrating your own calls to
        :func:`.collection_adapter` in one of the basic SQLAlchemy
        interface methods, or to prevent an automatic ABC method
        decoration from wrapping your implementation::

            # normally an 'extend' method on a list-like class would be
            # automatically intercepted and re-implemented in terms of
            # SQLAlchemy events and append().  your implementation will
            # never be called, unless:
            @collection.internally_instrumented
            def extend(self, items): ...

        """
    fn._sa_instrumented = True
    return fn


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def rgb_to_hex(color):
    """
    Return color as #rrggbb for the given color values.
    """
    [red, green, blue] = color.split(',')
    return '#%02x%02x%02x' % (int(red), int(green), int(blue))


def depthfilereader(depth_file, plasmid_length, cutoff):
    """
    Function that parse samtools depth file and creates 3 dictionaries that
    will be useful to make the outputs of this script, both the tabular file
    and the json file that may be imported by pATLAS

    Parameters
    ----------
    depth_file: str
        the path to depth file for each sample
    plasmid_length: dict
        a dictionary that stores length of all plasmids in fasta given as input
    cutoff: str
        the cutoff used to trim the unwanted matches for the minimum coverage
        results from mapping. This is then converted into a float within this
        function in order to compare with the value returned from the perc_value_per_ref.

    Returns
    -------
    percentage_basescovered: dict
            stores the percentage of the total sequence of a
            reference/accession (plasmid) in a dictionary
    """
    depth_dic_coverage = {}
    for line in depth_file:
        tab_split = line.split()
        reference = '_'.join(tab_split[0].strip().split('_')[0:3])
        position = tab_split[1]
        numreadsalign = float(tab_split[2].rstrip())
        if reference not in depth_dic_coverage:
            depth_dic_coverage[reference] = {}
        depth_dic_coverage[reference][position] = numreadsalign
    percentage_basescovered = {}
    for ref in depth_dic_coverage:
        perc_value_per_ref = float(len(depth_dic_coverage[ref])) / float(
            plasmid_length[ref])
        if perc_value_per_ref >= float(cutoff):
            percentage_basescovered[ref] = perc_value_per_ref
    return percentage_basescovered


def validate_int(value, label, low=None, high=None):
    """Validates that the given value represents an integer.

    There are several ways to represent an integer in Python (e.g. 2, 2L, 2.0). This method allows
    for all such representations except for booleans. Booleans also behave like integers, but
    always translate to 1 and 0. Passing a boolean to an API that expects integers is most likely
    a developer error.
    """
    if value is None or isinstance(value, bool):
        raise ValueError('Invalid type for integer value: {0}.'.format(value))
    try:
        val_int = int(value)
    except TypeError:
        raise ValueError('Invalid type for integer value: {0}.'.format(value))
    else:
        if val_int != value:
            raise ValueError('{0} must be a numeric value and a whole number.'
                .format(label))
        if low is not None and val_int < low:
            raise ValueError('{0} must not be smaller than {1}.'.format(
                label, low))
        if high is not None and val_int > high:
            raise ValueError('{0} must not be larger than {1}.'.format(
                label, high))
        return val_int


def checkbit(packedint, offset):
    """
    Check for a bit flag in a given int value.

    Args:
        packedint: bit packed int
        offset: binary offset to check

    Returns:
        bool
    """
    bit = 1 << offset
    return packedint & bit > 0


def initialize(context):
    """Initializer called when used as a Zope 2 product."""


def get_tid(cursor):
    """Returns the most recent tid."""


def _interval_scan_away(lower, upper, n):
    """Scan for a representative with n=n whose envelope encloses lower and upper.
    Returns two things:
      True, if the interval is provably too small for the bound, else False
        (i.e. we found a representative whose envelope is totally enclosed between lower and upper).
      None, if no enclosing representative is found, else the representative.
    """
    if lower._inexact or upper._inexact:
        raise ValueError('enclose: can only scan exact numbers')
    elif lower.negative or upper.negative:
        raise ValueError('enclose: can only scan positive numbers')
    elif not lower < upper:
        raise ValueError(
            'enclose: can only scan ordered envelope, got [{}, {}]'.format(
            lower, upper))
    rep = lower.trunc(n)
    if rep.is_exactly_zero():
        rep = rep.explode(sided=True, full=False)
    else:
        rep = rep.explode(sided=False, full=False)
    while True:
        bound_lo, bound_hi = rep.bounds()
        bottom_enclosed = bound_lo <= lower
        top_enclosed = upper <= bound_hi
        if bottom_enclosed and top_enclosed:
            return False, rep
        elif not (bottom_enclosed or top_enclosed):
            if rep.interval_sided:
                rep = rep.away(const_p=False)
            else:
                return True, None
        elif bottom_enclosed:
            rep = rep.away(const_p=False)
        else:
            return False, None


def _len_list(obj):
    """Length of list (estimate).
    """
    n = len(obj)
    if n > 8:
        n += 6 + (n >> 3)
    elif n:
        n += 4
    return n


def FormatNameToPython(i):
    """
    Transform a (method) name into a form which can be used as a python
    attribute

    example::

        >>> FormatNameToPython('<clinit>')
        'clinit'

    :param i: name to transform
    :rtype: str
    """
    i = i.replace('<', '')
    i = i.replace('>', '')
    i = i.replace('$', '_')
    return i


def lua_protobuf_header(ltag):
    """Returns common header included by all produced files"""
    return (
        """
#ifndef LUA_PROTOBUF_H
#define LUA_PROTOBUF_H

#include <google/protobuf/message.h>

#ifdef __cplusplus
extern "C" {
#endif

#include <lua.h>

#if defined (WIN32)
  #if defined(lua_protobuf_NOLIB)
    #define LUA_PROTOBUF_EXPORT
  #else
    #if defined(lua_protobuf_EXPORTS)
      #define LUA_PROTOBUF_EXPORT __declspec(dllexport)
    #else
      #define LUA_PROTOBUF_EXPORT __declspec(dllimport)
    #endif /* lua_protobuf_EXPORTS */
  #endif /* lua_protobuf_NOLIB */
#else /* defined (_WIN32) */
 #define LUA_PROTOBUF_EXPORT
#endif

// type for callback function that is executed before Lua performs garbage
// collection on a message instance.
// if called function returns 1, Lua will free the memory backing the object
// if returns 0, Lua will not free the memory
typedef int (*lua_protobuf_gc_callback)(::google::protobuf::Message%s *msg, void *userdata);

// __index and __newindex functions for enum tables
LUA_PROTOBUF_EXPORT int lua_protobuf_enum_index(lua_State *L);
LUA_PROTOBUF_EXPORT int lua_protobuf_enum_newindex(lua_State *L);

// GC callback function that always returns true
LUA_PROTOBUF_EXPORT int lua_protobuf_gc_always_free(::google::protobuf::Message%s *msg, void *userdata);

#ifdef __cplusplus
}
#endif

#endif

"""
         % (ltag, ltag))


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def segment(segment):
    """Select a single segment."""
    return {'segment': segment}


def do_filesizeformat(value, binary=False):
    """Format the value like a 'human-readable' file size (i.e. 13 kB,
    4.1 MB, 102 Bytes, etc).  Per default decimal prefixes are used (Mega,
    Giga, etc.), if the second parameter is set to `True` the binary
    prefixes are used (Mebi, Gibi).
    """
    bytes = float(value)
    base = binary and 1024 or 1000
    prefixes = [binary and 'KiB' or 'kB', binary and 'MiB' or 'MB', binary and
        'GiB' or 'GB', binary and 'TiB' or 'TB', binary and 'PiB' or 'PB',
        binary and 'EiB' or 'EB', binary and 'ZiB' or 'ZB', binary and
        'YiB' or 'YB']
    if bytes == 1:
        return '1 Byte'
    elif bytes < base:
        return '%d Bytes' % bytes
    else:
        for i, prefix in enumerate(prefixes):
            unit = base ** (i + 2)
            if bytes < unit:
                return '%.1f %s' % (base * bytes / unit, prefix)
        return '%.1f %s' % (base * bytes / unit, prefix)


def get_params_list(*args, **kwargs):
    """Turn dict-like arguments into an ordered list of pairs."""
    params = []
    if args:
        if len(args) > 1:
            raise TypeError('Expected at most 1 arguments, got 2')
        arg = args[0]
        if hasattr(arg, 'items'):
            params.extend(arg.items())
        else:
            params.extend(list(arg))
    if kwargs:
        params.extend(kwargs.items())
    return params


def true():
    """
    Returns the logical value TRUE
    """
    return True


def is_ordered(v):
    """
    The invariant for all Vector operations.

    Returns `True` when the elements are correctly ordered.

    """
    try:
        it = v.iterkeys()
        x = next(it)
        while True:
            last, x = x, next(it)
            if x.uid < last.uid:
                return False
    except StopIteration:
        return True


def remove_tags(ARN=None, TagKeys=None):
    """
    Removes the specified set of tags from the specified Elasticsearch domain.
    See also: AWS API Documentation

    :example: response = client.remove_tags(
        ARN='string',
        TagKeys=[
            'string',
        ]
    )

    :type ARN: string
    :param ARN: [REQUIRED]
            Specifies the ARN for the Elasticsearch domain from which you want to delete the specified tags.

    :type TagKeys: list
    :param TagKeys: [REQUIRED]
            Specifies the TagKey list which you want to remove from the Elasticsearch domain.
            (string) --

    """
    pass


@staticmethod
def writeToSocket(thesocket, data):
    """Write to socket until all data written."""
    count = 0
    while count < len(data):
        count += thesocket.send(data[count:])


def graph_view_all():
    """View all curves in editor

    """
    pass


def apply_fit(xy, coeffs):
    """ Apply the coefficients from a linear fit to
        an array of x,y positions.

        The coeffs come from the 'coeffs' member of the
        'fit_arrays()' output.
    """
    x_new = coeffs[0][2] + coeffs[0][0] * xy[:, (0)] + coeffs[0][1] * xy[:, (1)
        ]
    y_new = coeffs[1][2] + coeffs[1][0] * xy[:, (0)] + coeffs[1][1] * xy[:, (1)
        ]
    return x_new, y_new


def project_format(file, environment):
    """
	Project Naming Formatter
	"""
    file = file.format(environment['project_name'])
    return file


def floyd_warshall(weight):
    """All pairs shortest paths by Floyd-Warshall

    :param weight: edge weight matrix
    :modifies: weight matrix to contain distances in graph
    :returns: True if there are negative cycles
    :complexity: :math:`O(|V|^3)`
    """
    V = range(len(weight))
    for k in V:
        for u in V:
            for v in V:
                weight[u][v] = min(weight[u][v], weight[u][k] + weight[k][v])
    for v in V:
        if weight[v][v] < 0:
            return True
    return False


def gpencil_modifier_move_down(modifier: str=''):
    """Move modifier down in the stack

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def bytes_2_human_readable(number_of_bytes, precision=1):
    """
    流量bytes转换为kb, mb, gb等单位
    """
    if number_of_bytes < 0:
        raise ValueError("!!! number_of_bytes can't be smaller than 0 !!!")
    step_to_greater_unit = 1024.0
    number_of_bytes = float(number_of_bytes)
    unit = 'bytes'
    if number_of_bytes / step_to_greater_unit >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'KB'
    if number_of_bytes / step_to_greater_unit >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'MB'
    if number_of_bytes / step_to_greater_unit >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'GB'
    if number_of_bytes / step_to_greater_unit >= 1:
        number_of_bytes /= step_to_greater_unit
        unit = 'TB'
    number_of_bytes = round(number_of_bytes, precision)
    return str(number_of_bytes) + ' ' + unit


@classmethod
def via_gpib(cls, address, name=None, **kwargs):
    """Return a Driver with an underlying GPIB Instrument resource.

        Parameters
        ----------
        address :
            The gpib address of the instrument.
        name :
            Unique name given within Lantz to the instrument for logging purposes.
            Defaults to one generated based on the class name if not provided.
        kwargs :
            keyword arguments passed to the Resource constructor on initialize.
        **kwargs :

        Returns
        -------

        """
    resource_name = 'GPIB::%s::INSTR' % address
    return cls(resource_name, name, **kwargs)


def create(cls, type):
    """Create an object of a given class."""
    clone = type.__new__(type)
    clone.__init__()
    return clone


@classmethod
def get_slowest_tests(cls, num=10):
    """Returns the slow num tests.

        :param num: The maximum number of results to be returned.
        :type num: int

        """
    cur = cls.get_cursor()
    q = (
        'SELECT file, module, class, func, AVG(elapsed) as elapsed FROM {} GROUP BY module, class, func ORDER BY elapsed DESC LIMIT {}'
        )
    cur.execute(q.format(cls.meta['table'], num))
    return cur.fetchall()


def callback(method):
    """
    decorator to mark a method to be a 'callback'. This will make Pyro
    raise any errors also on the callback side, and not only on the side
    that does the callback call.
    """
    method._pyroCallback = True
    return method


def re_encrypt(CiphertextBlob=None, SourceEncryptionContext=None,
    DestinationKeyId=None, DestinationEncryptionContext=None, GrantTokens=None
    ):
    """
    Encrypts data on the server side with a new customer master key (CMK) without exposing the plaintext of the data on the client side. The data is first decrypted and then reencrypted. You can also use this operation to change the encryption context of a ciphertext.
    Unlike other operations, ReEncrypt is authorized twice, once as ReEncryptFrom on the source CMK and once as ReEncryptTo on the destination CMK. We recommend that you include the "kms:ReEncrypt*" permission in your key policies to permit reencryption from or to the CMK. This permission is automatically included in the key policy when you create a CMK through the console, but you must include it manually when you create a CMK programmatically or when you set a key policy with the  PutKeyPolicy operation.
    See also: AWS API Documentation

    Examples
    The following example reencrypts data with the specified CMK.
    Expected Output:

    :example: response = client.re_encrypt(
        CiphertextBlob=b'bytes',
        SourceEncryptionContext={
            'string': 'string'
        },
        DestinationKeyId='string',
        DestinationEncryptionContext={
            'string': 'string'
        },
        GrantTokens=[
            'string',
        ]
    )

    :type CiphertextBlob: bytes
    :param CiphertextBlob: [REQUIRED]
            Ciphertext of the data to reencrypt.

    :type SourceEncryptionContext: dict
    :param SourceEncryptionContext: Encryption context used to encrypt and decrypt the data specified in the CiphertextBlob parameter.
            (string) --
            (string) --

    :type DestinationKeyId: string
    :param DestinationKeyId: [REQUIRED]
            A unique identifier for the CMK to use to reencrypt the data. This value can be a globally unique identifier, a fully specified ARN to either an alias or a key, or an alias name prefixed by 'alias/'.
            Key ARN Example - arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
            Alias ARN Example - arn:aws:kms:us-east-1:123456789012:alias/MyAliasName
            Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012
            Alias Name Example - alias/MyAliasName

    :type DestinationEncryptionContext: dict
    :param DestinationEncryptionContext: Encryption context to use when the data is reencrypted.
            (string) --
            (string) --

    :type GrantTokens: list
    :param GrantTokens: A list of grant tokens.
            For more information, see Grant Tokens in the AWS Key Management Service Developer Guide .
            (string) --

    :rtype: dict
    :return: {
        'CiphertextBlob': b'bytes',
        'SourceKeyId': 'string',
        'KeyId': 'string'
    }

    """
    pass


def get_ts_from_sentinel_filename(filename, start_date=True):
    """Get timestamp from the filename of a Sentinel scene, according to naming conventions.
    Currently works for S1, S2 (generated after the 6th of December, 2016) & S3.

    :param  filename: top-level SENTINEL product folder or file name
    :param start_date: boolean (default: True), False is Stop Date, optional
    :return: str

    >>> get_ts_from_sentinel_filename("S1M_BB_TTTR_LFPP_20200113T074619_YYYYMMDDTHHMMSS_OOOOOO_DDDDDD_CCCC.SAFE.zip")
    '20200113T074619'
    >>> get_ts_from_sentinel_filename("MMM_BB_TTTR_LFPP_YYYYMMDDTHHMMSS_20200113T002219_OOOOOO_DDDDDD_CCCC.SAFE.zip", False)
    '20200113T002219'
    >>> get_ts_from_sentinel_filename("S3M_OL_L_TTTTTT_yyyymmddThhmmss_YYYYMMDDTHHMMSS_YYYYMMDDTHHMMSS_i_GGG_c.SEN3")
    'yyyymmddThhmmss'
    >>> get_ts_from_sentinel_filename("S2AM_MSIXXX_YYYYMMDDHHMMSS_Nxxyy_ROOO_Txxxxx_<Product Discriminator>.SAFE")
    'YYYYMMDDHHMMSS'
    """
    if filename.startswith('S2'):
        return filename.split('_')[2]
    elif start_date:
        return filename.split('_')[4]
    else:
        return filename.split('_')[5]


def mergeusers(ui, base, divergent, other):
    """ merges the users from two divergent changesets using three-way merge
    and return the user that will be used as the author of resolved cset"""
    baseuser = base.user()
    divuser = divergent.user()
    othuser = other.user()
    if divuser == othuser:
        return divuser
    elif baseuser == divuser:
        return othuser
    elif baseuser == othuser:
        return divuser
    else:
        users = set(divuser.split(b', '))
        users.update(othuser.split(b', '))
        user = b', '.join(sorted(users))
        return user


def rectangle(target, throat_length='throat.length'):
    """
    Calculate surface area for a rectangular throat

    Only suitable for true 2D simulations

    Parameters
    ----------
    target : OpenPNM Object
        The object which this model is associated with. This controls the
        length of the calculated array, and also provides access to other
        necessary properties.

    throat_length : string
        Dictionary key to the throat length array.  Default is 'throat.length'.

    """
    return 2 * target[throat_length]


def qci(mask, tfilter=None):
    """
    Compute the quality control index (QCI) for each column, defined as:

    :math:`QCI=\\dfrac{\\sum_{t\\in T}X_{dt}}{|T|}`

    where
    :math:`T` is the set of timestamps in the analysis.
    :math:`X_{dt}` is a data point for column :math:`d` time t` that passed
    all quality control test.
    :math:`|T|` is the number of data points in the analysis.

    Parameters
    ----------
    mask : pandas DataFrame
        Test results mask, returned from pm.mask

    tfilter : pandas Series (optional)
        Time filter containing boolean values for each time index

    Returns
    -------
    pandas Series
        Quality control index
    """
    if tfilter is not None:
        mask = mask[tfilter]
    qci = mask.sum() / mask.shape[0]
    return qci


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def get_doc():
    """Get documentation of this resource

    :return: rst string
    :rtype: str
    """
    return """
    The ``hostgroup`` model is used to group several hosts.

    """


def determineIndentationAndTrailingWS(text):
    """ Get the indentation used in this document and whether there is
    any trailing whitespace.
    The text is analyzed to find the most used indentations.
    The result is -1 if tab indents are most common.
    A positive result means spaces are used; the amount
    signifies the amount of spaces per indentation.
    0 is returned if the indentation could not be determined.
    The second return value is the number of lines with trailing ws.
    """
    text = text[:32768]
    indents = {}
    indents[-1] = 0
    trailing = 0
    lines = text.splitlines()
    lines.insert(0, '')
    for i in range(len(lines)):
        line = lines[i]
        lineA = line.lstrip()
        lineB = line.rstrip()
        lineC = lineA.rstrip()
        indent = len(line) - len(lineA)
        if len(lineB) < len(line):
            trailing += 1
        line = lineC
        if line.startswith('#'):
            continue
        else:
            line = line.split('#', 1)[0].rstrip()
        if not line:
            continue
        if line.endswith(':'):
            if len(lines) > i + 2:
                line2 = lines[i + 1]
                tmp = line2.lstrip()
                if not tmp:
                    line2 = lines[i + 2]
                    tmp = line2.lstrip()
                if tmp:
                    ind2 = len(line2) - len(tmp)
                    ind3 = ind2 - indent
                    if line2.startswith('\t'):
                        indents[-1] += 1
                    elif ind3 > 0:
                        if ind3 not in indents:
                            indents[ind3] = 1
                        indents[ind3] += 1
    indent, maxvotes = 0, 0
    for nspaces in indents:
        if indents[nspaces] > maxvotes:
            indent, maxvotes = nspaces, indents[nspaces]
    return indent, trailing


@classmethod
def reassemble(cls, fields, document):
    """
        Take a previously assembled document and reassemble the given set of
        fields for it in place.
        """
    for field_name in cls._instructions:
        if field_name in fields:
            maker = cls._instructions[field_name]
            with maker.target(document):
                document[field_name] = maker()


def create_uvsphere(bm: 'bmesh.types.BMesh', u_segments: int, v_segments:
    int, diameter: float, matrix: 'mathutils.Matrix', calc_uvs: bool) ->dict:
    """Creates a grid with a variable number of subdivisions

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param u_segments: number of u segments
    :type u_segments: int
    :param v_segments: number of v segment
    :type v_segments: int
    :param diameter: diameter
    :type diameter: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


def download_target_dir():
    """Returns the directory to which the knots database will be
    downloaded."""
    import appdirs
    return appdirs.user_data_dir('pyknotid')


def noop(*args, **kwargs):
    """This function does nothing."""
    pass


def isNegativeThrow(n):
    """ensure type of n is of IntType,
    raise an exception if less than zero"""
    if n < 0:
        raise ValueError(
            'invalid value of argument n with value ({N}, value must be greater than or equall to 0)'
            .format(N=n))


@classmethod
def manifest_history(cls, options=None):
    """Provided history for subscription manifest"""
    cls.command_sub = 'manifest-history'
    return cls.execute(cls._construct_command(options))


def get_new_current(index, word, current):
    """
        Used for fetching new current value/tuple of strings.
    """
    current.pop(index)
    current.append(word)
    return tuple(current)


def normalize_url(url):
    """Return url after stripping trailing .json and trailing slashes."""
    if url.endswith('.json'):
        url = url[:-5]
    if url.endswith('/'):
        url = url[:-1]
    return url


@classmethod
def meta(cls):
    """
        The purpose of this function is to use the meta attribute in templates.
         example: "item.meta"
        :return: _meta attribute of class.
        """
    return cls._meta


def flip_names():
    """Flips (and corrects) the axis suffixes of the names of selected bones

    """
    pass


def is_valid_file_mode(file_mode):
    """Return True if the given "file_mode" represents a valid file I/O mode"""
    return file_mode in {'r', 'w', 'rb', 'wb', 'a', 'ab', 'r+', 'rb+', 'w+',
        'wb+', 'a+', 'ab+'}


def brush_colors_flip():
    """Toggle foreground and background brush colors

    """
    pass


def volume_regular_tetrahedron(a):
    """
    Calculates the volume of a regular tetrahedron from the edge length.
    """
    return 2 ** 0.5 / 12 * a ** 3


def _format_ipv6(a):
    """
        Format IPv6 address (from tuple of 16 bytes) compressing sequence of
        zero bytes to '::'. Ideally we would use the ipaddress module in
        Python3.3 but can't rely on having this.

        >>> _format_ipv6([0]*16)
        '::'
        >>> _format_ipv6(_parse_ipv6("::0012:5678"))
        '::12:5678'
        >>> _format_ipv6(_parse_ipv6("1234:0:5678::ff:0:1"))
        '1234:0:5678::ff:0:1'
    """
    left = []
    right = []
    current = 'left'
    for i in range(0, 16, 2):
        group = (a[i] << 8) + a[i + 1]
        if current == 'left':
            if group == 0 and i < 14:
                if (a[i + 2] << 8) + a[i + 3] == 0:
                    current = 'right'
                else:
                    left.append('0')
            else:
                left.append('%x' % group)
        elif group == 0 and len(right) == 0:
            pass
        else:
            right.append('%x' % group)
    if len(left) < 8:
        return ':'.join(left) + '::' + ':'.join(right)
    else:
        return ':'.join(left)


def delete(project, version=None):
    """Delete the egg stored for the given project and version. If should
        also delete the project if no versions are left"""


@classmethod
def default_user_agent(cls):
    """ Return the default user agent string for a Connection.
        """
    package = 'boltkit'
    version = '1.3.0'
    return '{}/{}'.format(package, version)


def useRealTypes(obj):
    """
Given an obj, return an obj replacing string values with 1st class types
    """
    for k in obj.keys():
        if type(obj[k]) is str:
            try:
                obj[k] = float(obj[k])
                obj[k] = int(obj[k])
            except:
                pass
    return obj


def customdata_skin_clear():
    """Clear vertex skin layer

    """
    pass


def highlight_source(linenumber, index, lines, offset=None):
    """Extracts a few relevant lines from a file content given as a list
        of lines, adding line number information and identifying
        a particular line.

        When dealing with a ``SyntaxError`` or its subclasses, offset is an
        integer normally used by Python to indicate the position of
        the error with a ``^``, like::

            if True
                  ^

        which, in this case, points to a missing colon. We use the same
        representation in this case.
    """
    if lines is None:
        return '', ''
    if index is None:
        print('problem in highlight_source(): index is None')
        index = 0
    new_lines = []
    problem_line = ''
    nb_digits = len(str(linenumber + index))
    no_mark = '       {:%d}: ' % nb_digits
    with_mark = '    -->{:%d}: ' % nb_digits
    if offset is not None:
        offset_mark = ' ' * (8 + nb_digits + offset) + '^'
    i = linenumber - index
    for line in lines:
        if i == linenumber:
            num = with_mark.format(i)
            problem_line = line
            new_lines.append(num + line.rstrip())
            if offset is not None:
                new_lines.append(offset_mark)
            break
        else:
            num = no_mark.format(i)
        new_lines.append(num + line.rstrip())
        i += 1
    return '\n'.join(new_lines), problem_line


def get_ifaces(pfilter):
    """Return all interfaces we care about"""
    skip_ifaces = ['carp', 'egress', 'enc', 'enc0', 'lo', 'pflog', 'pflog0']
    all_ifaces = list()
    for iface in pfilter.get_ifaces():
        if iface.name not in skip_ifaces:
            all_ifaces.append(iface.name)
    return all_ifaces


def atom_formal_charge(atom):
    """Get formal charge for an atom.

    Parameters
    ----------
    atom : rdkit.Chem.rdchem.Atom
        RDKit atom instance.

    Returns
    -------
    list
        List containing one int only.
    """
    return [atom.GetFormalCharge()]


def p_error(tok):
    """Called when when a bad token is encountered."""
    print('bad token {}'.format(tok))


def event(base_url: str) ->str:
    """
    Build the URL for an execution's event.
    """
    return '/'.join([base_url, 'events'])


def opt_to_kwargs(opt):
    """Get kwargs for seq2seq from opt."""
    kwargs = {}
    for k in ['numlayers', 'dropout', 'bidirectional', 'rnn_class',
        'lookuptable', 'decoder', 'numsoftmax', 'attention',
        'attention_length', 'attention_time', 'input_dropout']:
        if k in opt:
            kwargs[k] = opt[k]
    return kwargs


@classmethod
def network_control_change_policy(cls, val):
    """
        Create an instance of this class set to the
        ``network_control_change_policy`` tag with value ``val``.

        :param NetworkControlChangePolicyType val:
        :rtype: EventType
        """
    return cls('network_control_change_policy', val)


def obj_to_str(obj):
    """ get class string from object

    Examples
    --------

    >>> print(obj_to_str([1,2,3]).split('.')[-1])
    list

    >>> import numpy as np
    >>> print(obj_to_str(np.array([1,2,3])))
    numpy.ndarray

    """
    mod_str = obj.__class__.__module__
    name_str = obj.__class__.__name__
    if mod_str == '__main__':
        return name_str
    else:
        return '.'.join([mod_str, name_str])


def escape_rst(text):
    """Return input string with special characters escaped.

    This is a naive implementation. Works for some characters but is
    not thoroughly implemented.
    """
    return text.replace('\\\\', '\\\\\\\\').replace('*', '\\*').replace('_',
        '\\_').replace('+', '\\+').replace('-', '\\-').replace('\\-\\-',
        '\\-\u200b\\-')


def fit_notebook_to_window():
    """Fit notebook width to width of browser window.
    Thanks to https://stackoverflow.com/questions/21971449/how-do-i-increase-the-cell-width-of-the-jupyter-ipython-notebook-in-my-browser
    """
    from IPython.core.display import display, HTML
    display(HTML('<style>.container { width:100% !important; }</style>'))


def shell_escape(s):
    """
    Use `shlex.quote` instead of this
    """
    import io
    fp = io.StringIO()
    sq = "'" + '"' + "'" + '"' + "'"
    dollar = "'" + "'" + '$' + "'" + "'"
    print("'", end='', file=fp)
    for c in s:
        if c == "'":
            print(sq, end='', file=fp)
        elif c == '$':
            print(dollar, end='', file=fp)
        else:
            print(c, end='', file=fp)
    print("'", end='', file=fp)
    return fp.getvalue()


def parse_reference(reference):
    """
    parse provided image reference into <image_repository>:<tag>

    :param reference: str, e.g. (registry.fedoraproject.org/fedora:27)
    :return: collection (tuple or list), ("registry.fedoraproject.org/fedora", "27")
    """
    if ':' in reference:
        im, tag = reference.rsplit(':', 1)
        if '/' in tag:
            return reference, 'latest'
        else:
            return im, tag
    else:
        return reference, 'latest'


def mrt_delta_from_erf(erf, fract_efficiency=0.725, rad_trans_coeff=6.012):
    """Calculate the mean radiant temperature (MRT) delta as a result of an ERF.

    Args:
        erf: A number representing the effective radiant field (ERF) on the
            person in W/m2.
        fract_efficiency: A number representing the fraction of the body
            surface exposed to radiation from the environment. This is typically
            either 0.725 for a standing or supine person or 0.696 for a seated
            person. Default is 0.725 for a standing person.
        rad_trans_coeff: A number representing the radiant heat transfer coefficient
            in (W/m2-K).  Default is 6.012, which is almost always the case.
    """
    return erf / (fract_efficiency * rad_trans_coeff)


def configure(conf):
    """
	Configuration for gdc
	"""
    conf.find_gdc()
    conf.load('ar')
    conf.load('d')
    conf.common_flags_gdc()
    conf.d_platform_flags()


@classmethod
def enable(cls):
    """Enables inspector domain notifications.
        """
    return cls.build_send_payload('enable', {}), None


def _forever_cache_key(func, self, *args):
    """ Cache this function call forever.
    """
    return func.__name__, args


def frequency_counts(df, cols):
    """Get an overview over how many unicates, duplicates etc. this column contains.

  Answers the following question: How many entries appear
  exactly one time in the dataset? How many appear twice?
  How many appear X times?

  Returns a PySpark Dataframe.
  """
    if type(cols) == str:
        cols = [cols]
    return df.groupBy(cols).count().withColumnRenamed('count', 'freq').groupBy(
        'freq').count().withColumnRenamed('count', 'counts').orderBy('freq',
        ascending=True)


@staticmethod
def _get_dest_user_id():
    """Get the user id to use on the target host."""
    return 'wlp'


def make_row(conffile):
    """
    Generate a dictionary describing this conffile.
    """
    return {'hash': conffile.hexdigest(), 'environment': conffile.
        environment, 'host': conffile.host, 'path': conffile.remote, 'role':
        conffile.role, 'component': conffile.component}


@classmethod
def translate_db_fields(cls, data):
    """
        Translates field names from the database into field names used in our model

        this is for cases where we're saving a field under a different name than it's model property

        :param data: dict
        :rtype: dict
        """
    dst_data = data.copy().get('_properties', {})
    if data.get('_id', None):
        dst_data.update({'_id': data.copy().get('_id')})
    for name, prop in cls._properties.items():
        if prop.db_field_name in dst_data:
            dst_data[name] = dst_data.pop(prop.db_field_name)
        elif name in dst_data:
            dst_data[name] = dst_data.pop(name)
    return dst_data


def consistentChans(chan: str) ->str:
    """Convert channels to ensure consistency

    Parameters
    ----------
    chan : str
        Channel name

    Returns
    -------
    out : str
        Converted channel name
    """
    standardChans = ['Hx', 'Hy', 'Hz', 'Ex', 'Ey']
    if chan in standardChans:
        return chan
    if chan == 'Bx':
        return 'Hx'
    if chan == 'By':
        return 'Hy'
    if chan == 'Bz':
        return 'Hz'
    return chan


@staticmethod
def _from_db_object(exec_inst, db_exec_inst):
    """Converts a database entity to a formal object."""
    for field in exec_inst.fields:
        setattr(exec_inst, field, db_exec_inst[field])
    exec_inst.obj_reset_changes()
    return exec_inst


def _handle_ipc(config, ipc):
    """ If IPC is defined, update it.
    """
    if ipc is not None:
        config.ipc_port = ipc


def _snooze(filecnt):
    """Sleep for a little while.

        :param filecnt: The number of messages in the queue the last time
            through.  Runners can decide to continue to do work, or sleep for
            a while based on this value.  By default, the base runner only
            snoozes when there was nothing to do last time around.
        :type filecnt: int
        """


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


def shorten_hash(original_hash: int) ->int:
    """
    This function removes final bytes from a hash to get a hash that can be parsed in java as an int
    :param original_hash: the original hash of an object. This should have 36 bytes.
    :return: A in int parsed from the first 32 bytes of the original hash
    """
    max_signed_int_32_bit = 2 ** 31 - 1
    return original_hash % max_signed_int_32_bit


def perform_SRA_step(t, h, f, g, y, I_1, I_10):
    """
	Optimised step evaluation. Tested against a human-readable version in test_step_functions.py.
	"""
    fh_1 = f(t, y) * h
    g_1 = g(t + h)
    fh_2 = f(t + 3 / 4 * h, y + 3 / 4 * fh_1 + 1 / 2 * g_1 * I_10 / h) * h
    g_2 = g(t)
    E_N = I_10 / h * (g_2 - g_1)
    new_y = y + E_N + 1 / 3 * (fh_1 + 2 * fh_2) + I_1 * g_1
    E_D = (fh_2 - fh_1) / 6
    return new_y, E_D, E_N


def safe_repr(obj):
    """
    Return a string describing Python object `obj`.

    Avoids calling any Python magic methods, so should be safe to use
    as a 'last resort' in implementation of `__str__` and `__repr__`.
    """
    return '%s@%x' % (obj.__class__.__name__, id(obj))


def get_field_tot_area(x):
    """ Total area of a plate field. """
    if len(x) == 6:
        width = 10
    else:
        width = x[7]
    plate_area = width * x[1]
    stiff_area = (x[2] * x[3] + x[4] * x[5]) * (width // x[0])
    return plate_area, stiff_area


def division(first, second):
    """Division operation

    :param first: first operator
    :param second: second operator

    Returns:
        The result of a division operation
    """
    return first / second


def re_tab(s):
    """Return a tabbed string from an expanded one."""
    l = []
    p = 0
    for i in range(8, len(s), 8):
        if s[i - 2:i] == '  ':
            l.append(s[p:i].rstrip() + '\t')
            p = i
    if p == 0:
        return s
    else:
        l.append(s[p:])
        return ''.join(l)


@classmethod
def retrieve(cls, id, api_key=None, **params):
    """Return a deferred."""
    instance = cls(id, api_key, **params)
    d = instance.refresh()
    return d.addCallback(lambda _: instance)


@classmethod
def _stripe_object_set_total_tax_amounts(cls, target_cls, data, instance):
    """
        Set total tax amounts on Invoice instance
        :param target_cls:
        :param data:
        :param instance:
        :type instance: djstripe.models.Invoice
        :return:
        """
    from .billing import TaxRate
    pks = []
    for tax_amount_data in data.get('total_tax_amounts', []):
        tax_rate_data = tax_amount_data['tax_rate']
        if isinstance(tax_rate_data, str):
            tax_rate_data = {'tax_rate': tax_rate_data}
        tax_rate, _ = TaxRate._get_or_create_from_stripe_object(tax_rate_data,
            field_name='tax_rate', refetch=True)
        tax_amount, _ = target_cls.objects.update_or_create(invoice=
            instance, tax_rate=tax_rate, defaults={'amount':
            tax_amount_data['amount'], 'inclusive': tax_amount_data[
            'inclusive']})
        pks.append(tax_amount.pk)
    instance.total_tax_amounts.exclude(pk__in=pks).delete()


def _int_arg(s):
    """Convert a string argument to an integer for use in a template
    function.  May raise a ValueError.
    """
    return int(s.strip())


def dispatch_hook(key, hooks, hook_data, **kwargs):
    """Dispatches a hook dictionary on a given piece of data."""
    hooks = hooks or dict()
    hooks = hooks.get(key)
    if hooks:
        if hasattr(hooks, '__call__'):
            hooks = [hooks]
        for hook in hooks:
            _hook_data = hook(hook_data, **kwargs)
            if _hook_data is not None:
                hook_data = _hook_data
    return hook_data


@staticmethod
def name():
    """return the repo type name."""
    return 'cvs'


def _show_leading_zeros(spinbutton):
    """Adds leading zeros to the given gtk spinbutton"""
    adjustment = spinbutton.get_adjustment()
    value = int(adjustment.get_value())
    spinbutton.set_text(f'{value:02d}')
    return True


@classmethod
def update_port(cls, port, **kwargs):
    """Wrapper utility that updates a test port."""
    body = cls.ports_client.update_port(port['id'], **kwargs)
    return body['port']


def deprecation_string(a_callable, deprecation_version):
    """Generate an automatic deprecation string for a_callable.

    :param a_callable: The callable to substitute into deprecation_version.
    :param deprecation_version: A deprecation format warning string. This
        should have a single %s operator in it. a_callable will be turned into
        a nice python symbol and then substituted into deprecation_version.
    """
    if getattr(a_callable, '__self__', None) is not None:
        symbol = '%s.%s.%s' % (a_callable.__self__.__class__.__module__,
            a_callable.__self__.__class__.__name__, a_callable.__name__)
    elif getattr(a_callable, '__qualname__', None
        ) is not None and '<' not in a_callable.__qualname__:
        symbol = '%s.%s' % (a_callable.__module__, a_callable.__qualname__)
    else:
        symbol = '%s.%s' % (a_callable.__module__, a_callable.__name__)
    return deprecation_version % symbol


def pt_shift(pt=(0.0, 0.0), shift=[0.0, 0.0]):
    """Return given point shifted in N dimensions.
    """
    assert isinstance(pt, tuple)
    l_pt = len(pt)
    assert l_pt > 1
    for i in pt:
        assert isinstance(i, float)
    assert isinstance(shift, list)
    l_sh = len(shift)
    assert l_sh == l_pt
    for i in shift:
        assert isinstance(i, float)
    return tuple([(pt[i] + shift[i]) for i in range(l_pt)])


def scan_setup_py():
    """Validate the contents of setup.py against Versioneer's expectations."""
    found = set()
    setters = False
    errors = 0
    with open('setup.py', 'r') as f:
        for line in f.readlines():
            if 'import versioneer' in line:
                found.add('import')
            if 'versioneer.get_cmdclass()' in line:
                found.add('cmdclass')
            if 'versioneer.get_version()' in line:
                found.add('get_version')
            if 'versioneer.VCS' in line:
                setters = True
            if 'versioneer.versionfile_source' in line:
                setters = True
    if len(found) != 3:
        print('')
        print('Your setup.py appears to be missing some important items')
        print('(but I might be wrong). Please make sure it has something')
        print('roughly like the following:')
        print('')
        print(' import versioneer')
        print(' setup( version=versioneer.get_version(),')
        print('        cmdclass=versioneer.get_cmdclass(),  ...)')
        print('')
        errors += 1
    if setters:
        print("You should remove lines like 'versioneer.VCS = ' and")
        print("'versioneer.versionfile_source = ' . This configuration")
        print('now lives in setup.cfg, and should be removed from setup.py')
        print('')
        errors += 1
    return errors


def node_is_inline(node):
    """
    Test if a node is in an "inline" context.
    """
    return node.parent.tagname in ['paragraph']


def describe_luna_client(ClientArn=None, CertificateFingerprint=None):
    """
    Retrieves information about an HSM client.
    See also: AWS API Documentation

    :example: response = client.describe_luna_client(
        ClientArn='string',
        CertificateFingerprint='string'
    )

    :type ClientArn: string
    :param ClientArn: The ARN of the client.

    :type CertificateFingerprint: string
    :param CertificateFingerprint: The certificate fingerprint.

    :rtype: dict
    :return: {
        'ClientArn': 'string',
        'Certificate': 'string',
        'CertificateFingerprint': 'string',
        'LastModifiedTimestamp': 'string',
        'Label': 'string'
    }

    """
    pass


def render_pep440_pre(pieces):
    """TAG[.post.devDISTANCE] -- No -dirty.

    Exceptions:
    1: no tags. 0.post.devDISTANCE
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '.post.dev%d' % pieces['distance']
    else:
        rendered = '0.post.dev%d' % pieces['distance']
    return rendered


def to_hass_level(level):
    """Convert the given FutureNow (0-100) light level to Home Assistant (0-255)."""
    return int(level * 255 / 100)


@classmethod
def instance(cls):
    """Return a global IOLoop instance."""
    if cls._instance is None:
        cls._lock.acquire()
        try:
            if cls._instance is None:
                cls._instance = cls()
        finally:
            cls._lock.release()
    return cls._instance


@classmethod
def from_json(cls, json_obj):
    """
        Constructs a Variable from the provided json-object.

        Example
        --------
        >>> import json
        >>> with open("path_to_file.json") as infile:
        >>>     var = Variable.from_json(json.load(infile))
        """
    return cls(json_obj['name'], lb=json_obj['lb'], ub=json_obj['ub'], type
        =json_obj['type'])


def registrations():
    """Return an iterable of component registrations
        """


@classmethod
def deserialize_from_http_generics(cls, response, encoding=None):
    """Deserialize from HTTP response.

        Headers will tested for "content-type"

        :param response: The HTTP response
        :param encoding: The encoding to use if known for this service (will disable auto-detection)
        :raises ~azure.core.exceptions.DecodeError: If deserialization fails
        :returns: A dict or XML tree, depending of the mime-type
        """
    if response.content_type:
        mime_type = response.content_type.split(';')[0].strip().lower()
    else:
        mime_type = 'application/json'
    return cls.deserialize_from_text(response.text(encoding), mime_type,
        response=response)


@staticmethod
def _get_sdist_url_from_pypi(metadata: dict) ->str:
    """Return the sdist url looking for the pypi metadata

        :param metadata: pypi metadata
        :return: sdist url
        """
    for sdist_url in metadata['urls']:
        if sdist_url['packagetype'] == 'sdist':
            return sdist_url['url']


def get_ruleset_by_ord(rulesengine_db, ordinal):
    """gets ruleset by ordinal"""
    from src.praxxis.sqlite import connection
    from src.praxxis.util import error
    conn = connection.create_connection(rulesengine_db)
    cur = conn.cursor()
    get_ruleset_by_ord = (
        'SELECT Name FROM "RulesEngine" ORDER BY Active DESC, ID LIMIT ?,?')
    cur.execute(get_ruleset_by_ord, (ordinal - 1, ordinal))
    conn.commit()
    rows = cur.fetchall()
    conn.close()
    if rows == []:
        raise error.RulesetNotFoundError(ordinal)
    return rows[0][0]


@classmethod
def get_handlers(cls):
    """
        Get all registered handlers.
        """
    return cls._HANDLERS.values()


def _validateArgs(wordArgs):
    """
    Insures that the user cannot restore from 'all' backups.
    """
    if wordArgs['id'] == 'all':
        raise Exception("Cannot restore from 'all' backups.")


def has_x11():
    """
    Is Qt build against X11 server.
    """
    try:
        from PyQt5.QtGui import QX11Info
        return True
    except ImportError:
        return False


@classmethod
def as_detail(cls, *init_args, **init_kwargs):
    """
        Used for hooking up the actual detail-style endpoints, this returns a
        wrapper function that creates a new instance of the resource class &
        calls the correct view method for it.

        :param init_args: (Optional) Positional params to be persisted along
            for instantiating the class itself.

        :param init_kwargs: (Optional) Keyword params to be persisted along
            for instantiating the class itself.

        :returns: View function
        """
    return cls.as_view('detail', *init_args, **init_kwargs)


def decode_data_item(row, group, byteorder) ->int:
    """Converts the bytes of data items into an integer."""
    return int.from_bytes(row[group], byteorder=byteorder)


def connect(**kw):
    """Return a new Connection object."""


def from_url(url, db=None, **kwargs):
    """
    Returns an active Redis client generated from the given database URL.

    Will attempt to extract the database id from the path url fragment, if
    none is provided.
    """
    from redis.client import Redis
    return Redis.from_url(url, db, **kwargs)


def shorten_text(text, limit, symbol='[...]'):
    """Return a given text truncated at limit if longer than limit.

    On truncation, add symbol.
    """
    assert type(text) is str and type(symbol) is str and type(limit) is int
    if len(text) <= limit:
        return text
    return text[:limit - len(symbol)] + symbol


def render_git_describe_long(pieces):
    """TAG-DISTANCE-gHEX[-dirty].

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


@staticmethod
def render_vars():
    """Provide template's context."""
    return {}


def _url_encode(val):
    """Url-decode a string"""
    try:
        from urllib import urlencode
    except ImportError:
        from urllib.parse import urlencode
    return urlencode({'': val})[1:]


def merge_dicts(low_priority, high_priority):
    """
    Return a new dict that is a merge of low_priority and high_priority dicts.
    When keys collide, takes the value of higher_priority dict.
    :param low_priority: dict: shallow dictionary
    :param high_priority: dict: shallow dictionary
    :return dict
    """
    result_dict = low_priority.copy()
    result_dict.update(high_priority)
    return result_dict


def normalize_pep440(**kwd):
    """ Normalize the version.

        >>> normalize_pep440(**parse_pep440('1.2.3.4.rc5.post.dev'))
        '1.2.3.4rc5'
    """
    normalized = '.'.join(map(str, kwd['release']))
    if 'pre_release' in kwd:
        normalized += '%s%s' % kwd['pre_release']
    if 'post_release' in kwd:
        normalized += '.post' + str(kwd['post_release'])
    if 'dev_release' in kwd:
        normalized += '.dev' + str(kwd['dev_release'])
    if 'epoch' in kwd:
        normalized = '{}!{}'.format(kwd['epoch'], normalized)
    return normalized


def magnitude_to_moment(magnitude):
    """
    Convert moment magnitude Mw to scalar moment.

    :param magnitude: moment magnitude
    :returns: scalar moment [Nm]

    See :py:func:`moment_to_magnitude`.
    """
    return 10.0 ** (1.5 * (magnitude + 10.7)) * 1e-07


def save(sel_filename, version, time, scans, no_sensors, duration, sensors,
    scale_factors=None):
    """Create HAWC2 sel-file

    Parameters
    ----------
    sel_filename : str
        Filename
    version : str
        Version tag
    time : datetime.datetime
        Date and time of creation
    scans : int
        Number of scans/observations/rows
    no_sensors : int
        Number of sensors/channels/columns
    duration : int, float
        Duration of simulation
    sensors : array_like
        List of (name, unit, description)-tuples
    scale_factors : array_like, optional
        Array of scale factors. Only for BINARY format
    """
    lines = []
    linesep = '_' * 120
    lines.append(linesep)
    lines.append('  Version ID : %s' % version)
    lines.append(' ' * 60 + 'Time : %s' % time.strftime('%H:%M:%S'))
    lines.append(' ' * 60 + 'Date : %s' % time.strftime('%d:%m.%Y'))
    lines.append(linesep)
    lines.append('  Result file : %s.dat' % sel_filename[:-4])
    lines.append(linesep)
    lines.append('   Scans    Channels    Time [sec]      Format')
    lines.append('   %8s    %3s       %8.3f       %s' % (scans, no_sensors,
        duration, ('BINARY', 'ASCII')[scale_factors is None]))
    lines.append('')
    lines.append('  Channel   Variable Description               ')
    lines.append('')
    for nr, sensor in enumerate(sensors, 1):
        name, unit, description = sensor
        lines.append('  %4s      %-30s %-10s %s' % (nr, name[:30], unit[:10
            ], description[:512]))
    lines.append(linesep)
    if scale_factors is not None:
        lines.append('Scale factors:')
        for sf in scale_factors:
            lines.append('  %.5E' % sf)
    with open(sel_filename, 'w', encoding='utf-8') as f:
        f.write('\n'.join(lines))


def save_parameters(params, filepath, fileformat='h5'):
    """Save all layer parameters to an HDF5 file."""
    if fileformat == 'pkl':
        import pickle
        pickle.dump(params, open(filepath + '.pkl', str('wb')))
    else:
        import h5py
        with h5py.File(filepath, mode='w') as f:
            for i, p in enumerate(params):
                if i < 10:
                    j = '00' + str(i)
                elif i < 100:
                    j = '0' + str(i)
                else:
                    j = str(i)
                f.create_dataset('param_' + j, data=p)


def _parse_out_sequence_file(sample):
    """
    Removes keys in argument sample that are not in sample_keys and
        stores them in sequence_file_dict

    arguments:
            sample -- Sample object
            the dictionary inside the Sample object is changed

    returns a dictionary containing keys not in sample_keys to be used to
        create a SequenceFile object
    """
    sample_keys = ['sequencer_sample_name', 'sampleName', 'sample_project']
    sequence_file_dict = {}
    sample_dict = sample.get_uploadable_dict()
    for key in list(sample_dict.keys()):
        if key not in sample_keys:
            sequence_file_dict[key] = sample_dict[key]
    return sequence_file_dict


def render_pep440_old(pieces):
    """TAG[.postDISTANCE[.dev0]] .

    The ".dev0" means dirty.

    Eexceptions:
    1: no tags. 0.postDISTANCE[.dev0]
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance'] or pieces['dirty']:
            rendered += '.post%d' % pieces['distance']
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = '0.post%d' % pieces['distance']
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def get_tag_filtering_args(parsed_args, args):
    """Adds the tag arguments to an args list.

    Intended to be used to append the tags to an argument list that will be
    used for service client.

    :param parsed_args: Parsed argument object returned by argparse parse_args.
    :param args: The argument list to add tags to.
    """
    if parsed_args.tags:
        args['tags'] = ','.join(parsed_args.tags)
    if parsed_args.any_tags:
        args['any_tags'] = ','.join(parsed_args.any_tags)
    if parsed_args.not_tags:
        args['not_tags'] = ','.join(parsed_args.not_tags)
    if parsed_args.not_any_tags:
        args['not_any_tags'] = ','.join(parsed_args.not_any_tags)


@classmethod
def get_line(cls, node):
    """ Get the source line for a node """
    return cls.lines[node.lineno - 1].strip()


def is_instance_or_subclass(val, class_):
    """Return True if ``val`` is either a subclass or instance of ``class_``."""
    try:
        return issubclass(val, class_)
    except TypeError:
        return isinstance(val, class_)


def _to_bytes(nums):
    """
    Convert a list of 11-bit numbers to a bytearray.

    Args:
        nums (int[]): list of 11-bit numbers

    Returns:
        bytes: bytearray
    """
    buffer = 0
    num_of_bits = 0
    output = []
    for i in range(len(nums)):
        buffer |= nums[i] << num_of_bits
        num_of_bits += 11
        while num_of_bits >= 8:
            output.append(buffer & 255)
            buffer = buffer >> 8
            num_of_bits -= 8
    if num_of_bits != 0:
        output.append(buffer & 255)
    return bytes(output)


def arccos(data=None, out=None, name=None, **kwargs):
    """Returns element-wise inverse cosine of the input array.

    The input should be in range `[-1, 1]`.
    The output is in the closed interval :math:`[0, \\pi]`

    .. math::
       arccos([-1, -.707, 0, .707, 1]) = [\\pi, 3\\pi/4, \\pi/2, \\pi/4, 0]

    The storage type of ``arccos`` output is always dense

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L206

    Parameters
    ----------
    data : NDArray
        The input array.

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def glPolygonStipple(mask: 'bpy.context.object'):
    """Set the polygon stippling pattern

    :param mask: Specifies a pointer to a 32x32 stipple pattern that will be unpacked from memory in the same way that glDrawPixels unpacks pixels.
    :type mask: 'bpy.context.object'
    """
    pass


def make_an_event(new_state):
    """Turns a new/target state into an event name."""
    return ('on_%s' % new_state).lower()


def DeleteGroup(r, group, dry_run=False):
    """
    Deletes a node group.

    @type group: str
    @param group: the node group to delete
    @type dry_run: bool
    @param dry_run: whether to peform a dry run

    @rtype: int
    @return: job id
    """
    query = {'dry-run': dry_run}
    return r.request('delete', '/2/groups/%s' % group, query=query)


def convert_preview_crop_gravity(coordinates, x_max, y_max):
    """
    convert corrdinates from crop3:
    offset_x, offset_y, width, height, gravitation
    original image size:
    x_max, y_max
    return coordinates for drawing crop: x0, y0, x1, y1
    """
    offset_x = coordinates[0]
    offset_y = coordinates[1]
    width = coordinates[2]
    height = coordinates[3]
    gravitation = coordinates[4]
    if gravitation == 'NW':
        x0 = offset_x
        y0 = offset_y
        x1 = x0 + width
        y1 = y0 + height
    elif gravitation == 'N':
        x0 = x_max / 2 - width / 2
        y0 = offset_y
        x1 = x_max / 2 + width / 2
        y1 = y0 + height
    elif gravitation == 'NE':
        x0 = x_max - width - offset_x
        y0 = offset_y
        x1 = x_max - offset_x
        y1 = y0 + height
    elif gravitation == 'W':
        x0 = offset_x
        y0 = y_max / 2 - height / 2
        x1 = x0 + width
        y1 = y_max / 2 + height / 2
    elif gravitation == 'C':
        x0 = x_max / 2 - width / 2
        y0 = y_max / 2 - height / 2
        x1 = x_max / 2 + width / 2
        y1 = y_max / 2 + height / 2
    elif gravitation == 'E':
        x0 = x_max - width - offset_x
        y0 = y_max / 2 - height / 2
        x1 = x_max - offset_x
        y1 = y_max / 2 + height / 2
    elif gravitation == 'SW':
        x0 = offset_x
        y0 = y_max - height - offset_y
        x1 = x0 + width
        y1 = y_max - offset_y
    elif gravitation == 'S':
        x0 = x_max / 2 - width / 2
        y0 = y_max - height - offset_y
        x1 = x_max / 2 + width / 2
        y1 = y_max - offset_y
    elif gravitation == 'SE':
        x0 = x_max - width - offset_x
        y0 = y_max - height - offset_y
        x1 = x_max - offset_x
        y1 = y_max - offset_y
    else:
        x0 = 5
        y0 = 5
        x1 = x_max - 5
        y1 = y_max - 5
    return x0, y0, x1, y1


@classmethod
def register_tags_tuples_style(cls, tags_tuples_style=None):
    """Registers a dictionary of PTK-style styles for tags_tuples.
        """
    cls.TAGS_TUPLE_STYLE = tags_tuples_style or {}


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


def ints2string(x, threshold=None):
    """Convert ndarray of ints to string."""
    if threshold is None or len(x) <= threshold:
        return str(x.tolist())
    return str(x[:threshold].tolist())[:-1] + ', ...]'


def subdict(d, *keys, key_filter=lambda o: o, value_filter=lambda o: o):
    """Return Subdictionary"""
    keys = set(d.keys()) - set(keys)
    out = {}
    for k in filter(key_filter, keys):
        value = d[k]
        if value_filter(value):
            out[k] = value
    return out


def flag_is_set(flag, flags):
    """Checks if the flag is set

    Returns boolean"""
    if flags & flag > 0:
        return True
    return False


def multi_pop(d, *args):
    """ pops multiple keys off a dict like object """
    retval = {}
    for key in args:
        if key in d:
            retval[key] = d.pop(key)
    return retval


def set_default_weight_to_length(vertices):
    """
    Add weight column to the dataframe *vertices* with element equal to the
    length of the associated geometry ; in-place.

    Parameters
    ----------
    vertices: DataFrame
        Dataframe of the vertices.
    """
    for idx, vertex in vertices.iterrows():
        vertices.loc[idx, 'weight'] = vertex['geometry'].length


def cat(seq, dim):
    """Concat the sequence of tensors in the given dimension.

    Parameters
    ----------
    seq : list of Tensor
        The tensor sequence.
    dim : int
        The concat dim.

    Returns
    -------
    Tensor
        A framework-specific tensor.
    """
    pass


@staticmethod
def ioConvertName(name):
    """Convert a variable name to ``camelCase`` for exporting."""
    return 'his' + name[0].upper() + name[1:]


@classmethod
def _query_delete_where(cls, query) ->str:
    """Generates the UPDATE stub"""
    builder = [f'DELETE FROM {cls._name}']
    builder.append('WHERE')
    builder.append(query)
    return ' '.join(builder)


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['action']
    if type == 'ADD_HTTP_REQUEST_HEADER':
        return 'AddHttpRequestHeaderRule'
    if type == 'REDIRECT':
        return 'RedirectRule'
    if type == 'REMOVE_HTTP_REQUEST_HEADER':
        return 'RemoveHttpRequestHeaderRule'
    if type == 'EXTEND_HTTP_REQUEST_HEADER_VALUE':
        return 'ExtendHttpRequestHeaderValueRule'
    if type == 'REMOVE_HTTP_RESPONSE_HEADER':
        return 'RemoveHttpResponseHeaderRule'
    if type == 'CONTROL_ACCESS_USING_HTTP_METHODS':
        return 'ControlAccessUsingHttpMethodsRule'
    if type == 'ALLOW':
        return 'AllowRule'
    if type == 'ADD_HTTP_RESPONSE_HEADER':
        return 'AddHttpResponseHeaderRule'
    if type == 'EXTEND_HTTP_RESPONSE_HEADER_VALUE':
        return 'ExtendHttpResponseHeaderValueRule'
    else:
        return 'Rule'


def diz_from_dms(binary, filename):
    """
    Amiga diskmasher format. Depends on the external binary 'xdms'.
    """
    import subprocess
    args = 'd', filename
    proc = subprocess.Popen((binary,) + args, stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    output, _ = proc.communicate()
    if proc.returncode == 0:
        return output.decode('cp437_art')
    else:
        return u'No description'


def remove_line(line2D):
    """
    Removes line from matplotlib plot.
    # http://stackoverflow.com/questions/4981815/how-to-remove-lines-in-a-matplotlib-plot
    """
    l = line2D.pop(0)
    l.remove()
    del l


def dasherize(word):
    """Replace underscores with dashes in the string.

    Example::

        >>> dasherize("puni_puni")
        'puni-puni'

    """
    return word.replace('_', '-')


@staticmethod
def _unmarshal_parts(pkg_reader, package, part_factory):
    """
        Return a dictionary of |Part| instances unmarshalled from
        *pkg_reader*, keyed by partname. Side-effect is that each part in
        *pkg_reader* is constructed using *part_factory*.
        """
    parts = {}
    for partname, content_type, reltype, blob in pkg_reader.iter_sparts():
        parts[partname] = part_factory(partname, content_type, reltype,
            blob, package)
    return parts


def _try_to_decode(some_bytes):
    """Don't know why some turtl notes are in latin1.
    """
    try:
        return some_bytes.decode('utf8')
    except UnicodeDecodeError:
        return some_bytes.decode('latin1')


@staticmethod
def calculate_trendsrating(datas):
    """
        Calculates the analysts rating ala Levermann
        :param datas: analysts data
        :return: the rating score
        """
    nominator = 0
    denominator = 0
    for data in datas:
        nominator += data['Recommendation'] * data['NumberOfAnalysts']
        denominator += data['NumberOfAnalysts']
    return nominator / denominator


def get_leading_whitespace(s):
    """
    Gets the leading whitespace of a string. Mainly used to
    determine how many space were there originally before adding a
    docstring. So that a docstring is placed in the same
    pattern
    Parameters
    ----------
    str s: String text
    """
    accumulator = []
    for c in s:
        if c in ' \t\x0b\x0c\r\n':
            accumulator.append(c)
        else:
            break
    return ''.join(accumulator)


def _add_errorbar(ax, x, y, yerr, filled, markersize=None, color=None):
    """Add an errorbar to Axes `ax`, allowing an array of markers."""
    ax.errorbar(x[filled], y[filled], yerr[filled], ls='None', marker='o',
        markersize=markersize, color=color)
    notfilled = ~filled
    ax.errorbar(x[notfilled], y[notfilled], yerr[notfilled], ls='None', mfc
        ='None', marker='o', markersize=markersize, color=color)


def get_lighter_color(color):
    """Generates a lighter color.

    Keyword arguments:
    color -- color you want to change, touple with 3 elements (Doesn't matter
             if it is RGB or BGR)
    Return:
    Return a lighter version of the provided color

    """
    add = 255 - max(color)
    add = min(add, 30)
    return color[0] + add, color[1] + add, color[2] + add


def undo():
    """Undo previous action

    """
    pass


def criar_dominio_generico(modelo, codigo, valor):
    """
    Cria um registro em um determinado dominio
    """
    dominio = modelo()
    dominio.codigo = codigo
    dominio.valor = valor
    dominio.save()
    return dominio


@classmethod
def get(cls, top, parent=None):
    """
        This will get all of the switch bd on the
        specified node.  If no node is specified, then
        it will get all of the bds on all
        of the switches.

        :param parent:
       :param top: the topSystem level json object
       :returns: list of Switch bridge domain
        """
    cls.check_parent(parent)
    result = []
    bd_data = top.get_class('l2BD')
    for l2bd in bd_data:
        bdomain = cls()
        bdomain._top = top
        bdomain._populate_from_attributes(l2bd['l2BD']['attributes'])
        bdomain._get_cxt_name(top)
        bdomain._get_multicast_flood_address(top)
        result.append(bdomain)
        if parent:
            bdomain._parent = parent
            bdomain._parent.add_child(bdomain)
    return result


def update_config_vars(config_dict, app):
    """
    Use the Heroku API to update config vars

    :param config_dict: dictionary of config vars
    :param app: name of the Heroku app
    :return: None
    """
    updated_config = app.update_config(config_dict)
    return updated_config.to_dict()


@classmethod
def sharing_change_folder_join_policy_details(cls, val):
    """
        Create an instance of this class set to the
        ``sharing_change_folder_join_policy_details`` tag with value ``val``.

        :param SharingChangeFolderJoinPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('sharing_change_folder_join_policy_details', val)


def stencil_fit_image_aspect(use_repeat: bool=True, use_scale: bool=True,
    mask: bool=False):
    """When using an image texture, adjust the stencil size to fit the image aspect ratio

    :param use_repeat: Use Repeat, Use repeat mapping values
    :type use_repeat: bool
    :param use_scale: Use Scale, Use texture scale values
    :type use_scale: bool
    :param mask: Modify Mask Stencil, Modify either the primary or mask stencil
    :type mask: bool
    """
    pass


def relu(data=None, name=None, attr=None, out=None, **kwargs):
    """Computes rectified linear activation.

    .. math::
       max(features, 0)

    The storage type of ``relu`` output depends upon the input storage type:

       - relu(default) = default
       - relu(row_sparse) = row_sparse
       - relu(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L85

    Parameters
    ----------
    data : Symbol
        The input array.

    name : string, optional.
        Name of the resulting symbol.

    Returns
    -------
    Symbol
        The result symbol.
    """
    return 0,


def print_scientific_8(value: float) ->str:
    """
    Prints a value in 8-character scientific notation.
    This is a sub-method and shouldnt typically be called

    Notes
    -----
    print_float_8 : a better float printing method

    """
    if value == 0.0:
        return '%8s' % '0.'
    python_value = '%8.11e' % value
    svalue, sexponent = python_value.strip().split('e')
    exponent = int(sexponent)
    sign = '-' if abs(value) < 1.0 else '+'
    exp2 = str(exponent).strip('-+')
    value2 = float(svalue)
    leftover = 5 - len(exp2)
    if value < 0:
        fmt = '%%1.%sf' % (leftover - 1)
    else:
        fmt = '%%1.%sf' % leftover
    svalue3 = fmt % value2
    svalue4 = svalue3.strip('0')
    field = '%8s' % (svalue4 + sign + exp2)
    return field


def onEnabled(theme, settings, dependenciesSettings):
    """Called when the theme is enabled through the control panel, either
        because the global "enabled" flag was switched, or because the theme
        was changed.
        """


def sign(data=None, out=None, name=None, **kwargs):
    """Returns element-wise sign of the input.

    Example::

       sign([-2, 0, 3]) = [-1, 0, 1]

    The storage type of ``sign`` output depends upon the input storage type:

       - sign(default) = default
       - sign(row_sparse) = row_sparse
       - sign(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L759

    Parameters
    ----------
    data : NDArray
        The input array.

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def uses_mysql(connection):
    """Return whether the connection represents a MySQL DB."""
    return 'mysql' in connection.settings_dict['ENGINE']


@classmethod
def can_represent(cls, location):
    """
        This is used to allow the plugin to determine if it thinks it is
        able to scrape the given data source identifier or not.

        :param location: Location Identifier. This could be a url, or a filepath
            or a uuid etc.
        :type location: string

        :return: bool
        """
    return False


def obj_has_attr(obj, name):
    """Return True if the object has the attribute.

    Parameters
    ----------
    obj: object
        Object to check
    name: str
        Attribute name to check
    """
    return hasattr(obj, name)


def primitive_square_add(size: float=100.0, location: float=(0.0, 0.0)):
    """Add new square-shaped spline

    :param size: Size, Size of new circle
    :type size: float
    :param location: Location, Location of new circle
    :type location: float
    """
    pass


def is_autograph_signing_format(format_):
    """Return bool of whether a signing format is for autograph.

    Args:
        format_ (str): the format to check

    """
    return format_ and format_.startswith('autograph_')


@staticmethod
def get_list_response():
    """
        Get a get_banks :class:`paynlsdk.api.transaction.getbanks.Response` instance

        Please note this method is a mapping from the paynlsdk.client.transaction.Transaction.get_banks() method,
        that returns the internal List object of banks.
        :return: Response object
        :rtype: paynlsdk.api.transaction.getbanks.Response
        """
    from paynlsdk.client.transaction import Transaction
    return Transaction.get_banks_response()


def federate(*stores):
    """
    Create a session spec for connecting to a federated store.

    :param stores: List of session specs to federate.
    :type stores: tuple[string]
    :return: A session spec string.
    :rtype: string
    """
    return ' + '.join(stores)


@staticmethod
def _word_wrap(text, width):
    """Returns lengths of lines that can be printed without wrapping."""
    lengths = []
    while len(text) > width:
        try:
            end = text[:width + 1].rindex(' ')
        except ValueError:
            break
        if end == -1:
            return [len(text)]
        lengths.append(end)
        text = text[end + 1:]
    if text:
        lengths.append(len(text))
    return lengths


def calculate_inline_block_replaced_normal_flow_height(node, context):
    """Implements S10.6.10"""
    raise NotImplementedError('Section 10.6.10')


def xmlid(entity):
    """Return a value usable as ID/IDREF for the given entity."""
    return entity.cw_adapt_to('IXmlId').id()


def split_doc_num(doc_num, effective_date):
    """ If we have a split notice, we construct a document number
    based on the original document number and the effective date. """
    effective_date = ''.join(effective_date.split('-'))
    return '{0}_{1}'.format(doc_num, effective_date)


def overlap(bbox1, bbox2):
    """
    Given two bboxes, return whether the two bboxes overlap
    """
    x1, y1, w1, h1 = bbox1
    x2, y2, w2, h2 = bbox2
    return x1 < x2 + w2 and y1 < y2 + h2 and x2 < x1 + w1 and y2 < y1 + h1


def jsPath(path):
    """Returns a relative path without \\, -, and . so that
    the string will play nicely with javascript."""
    shortPath = path.replace('C:\\Users\\scheinerbock\\Desktop\\' +
        'ideogram\\scrapeSource\\test\\', '')
    noDash = shortPath.replace('-', '_dash_')
    jsPath = noDash.replace('\\', '_slash_').replace('.', '_dot_')
    return jsPath


def _store_canonical(current_path: str, r_id: str) ->str:
    """
            Store a canonical copy of a resource in this adapter.

            If we're using an adapter as a canonical adapter, we need
            to be able to store from a current path, taking in a generated UUID,
            rather than looking info up from the database.

            :param current_path - current path to object
            :param r_id - UUID of resource you're storing
            :param checksum - checksum of resource
            :param filename - filename of resource you're storing

        """
    pass


def short_to_long(arg: str) ->str:
    """Convert the short form of an argument to its long form."""
    if arg == '-h':
        return '--help'
    elif arg == '-v':
        return '--version'
    elif arg == '-q':
        return '--quiet'
    else:
        return arg


@staticmethod
def iso88591(value):
    """Doing automatic conversion to iso-8859-1 strings.

        Converts from utf-8 to iso-8859-1 string. That means, all input value
        of Headers class must be UTF-8 stings.
        """
    try:
        if isinstance(value, str):
            return value.encode('utf-8').decode('iso-8859-1')
    except UnicodeError:
        raise AssertionError(
            'Header name/value must be iso-8859-1 encoded (got {0})'.format
            (value))
    raise AssertionError('Header name/value must be of type str (got {0})'.
        format(value))


def xywh_from_bbox(minx, miny, maxx, maxy):
    """Convert a bounding box from a numeric list to a numeric dict representation."""
    return {'x': minx, 'y': miny, 'w': maxx - minx, 'h': maxy - miny}


def same_type(values, types):
    """Check if values are belongs to same type or type tuple.

    :param collections.Iterable values: values to check type similarity
    :param tuple|type types: type or tuple of types
    """
    return all(map(lambda it: isinstance(it, types), values))


def select_less():
    """Deselect boundary selected keys of each particle

    """
    pass


def crop(x, x_min=None, x_max=None, y_min=None, y_max=None):
    """perform crop on batch of images"""
    return x[:, :, y_min:y_max, x_min:x_max]


def _mean(W_or_V):
    """ The reconstruction from VAE is returned by:
  (mean, total_stddev, explained_stddev)
  This method will make sure only mean value is return
  """
    W_or_V = W_or_V[0] if isinstance(W_or_V, (tuple, list)
        ) or W_or_V.ndim == 3 else W_or_V
    assert W_or_V.ndim == 2
    return W_or_V


def mel2hz(mel):
    """Convert a value in Mels to Hertz

    :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
    :returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
    """
    return 700 * (10 ** (mel / 2595.0) - 1)


def teams():
    """Return a real Premier League team with upcoming strenght scores for upcoming fixtures"""
    pass


def __get_search_dataset(_query_uri):
    """This function identifies the appropriate search dataset."""
    _dataset = ''
    if 'search/contents' in _query_uri:
        _dataset = 'search_contents'
    elif 'search/people' in _query_uri:
        _dataset = 'search_people'
    elif 'search/places' in _query_uri:
        _dataset = 'search_places'
    elif 'search/tags' in _query_uri:
        _dataset = 'search_tags'
    return _dataset


def set_attr(obj, n, attr, val, default=None):
    """
    Set the specified attribute of an ElementTree ``Element`` object to the value from the
    specified target.

    :param obj: An object which contains an ``ATTR_MAP`` property.
    :param n: An ElementTree ``Element`` object.
    :param attr: The name of the attribute to set.
    :param val: The value of the attribute to set.
    :param default: The default value of ``val``. If ``val==default``, the attribute will not be set.

    """
    if default != None and val == default:
        return
    if obj.ATTR_MAP.has_key(attr):
        f = obj.ATTR_MAP[attr]
        s = f.to_str(val)
        if s != None:
            n.attrib[attr] = s
        return
    if val != None:
        s = str(val)
        n.attrib[attr] = s


def rating_format(rating):
    """Return an integer equal to the string represented sum.

    Cast a string expressing a sum of integers delimited by a plus sign,
    e.g. 81+3, into an integer equal to a sum of the two numbers and
    return the integer.

    Parameters
    ----------
    rating : str
        String representing a sum of two integers with a plus sign
        inbetween.

    Returns
    -------
    rating : int
        Integer value of the sum of the numbers. Integer is equal to zero
        if the type of the input is not string.

    Notes
    -----
    This function is used in the FIFA19 data set to convert the player's
    special rating format in the game to an integer to get the proper
    understanding of the data when performing Machine Learning.

    Examples
    --------
    >>> r = rating_format("81+3")
    >>> print(r)
    84
    """
    if type(rating) is not str:
        return 0
    elif '+' in rating:
        plus = rating.index('+')
        base = int(rating[:plus])
        add = int(rating[plus + 1:])
        return base + add
    else:
        return int(rating)


def math(u, h):
    """Return (x0,y0,x1,y1) for the given height."""
    return u[1].start, h - u[0].stop - 1, u[1].stop, h - u[0].start - 1


def Commas(value):
    """Formats an integer with thousands-separating commas.

  Args:
    value: An integer.

  Returns:
    A string.
  """
    if value < 0:
        sign = '-'
        value = -value
    else:
        sign = ''
    result = []
    while value >= 1000:
        result.append('%03d' % (value % 1000))
        value /= 1000
    result.append('%d' % value)
    return sign + ','.join(reversed(result))


def _params_for_pegasus(parameters):
    """Escapes $ and escapes in parameters string for pegasus.

    Pegaus kickstart tries to do variable substitution if it sees a ``$``, and
    it will strip away back slashes. This can be problematic when trying to use
    LaTeX in parameter labels. This function adds escapes to all ``$`` and
    backslashes in a parameters argument, so the argument can be safely passed
    through pegasus-kickstart.

    Parameters
    ----------
    parameters : list or str
        The parameters argument to modify. If a list, the output will be
        converted to a space-separated string.
    """
    if isinstance(parameters, list):
        parameters = ' '.join(parameters)
    return parameters.replace('\\', '\\\\').replace('$', '\\$')


def minify_css(input_files, output_file):
    """
    Minifies the input CSS files to the output file.

    Output file may be same as input to minify in place.

    In debug mode this function just concatenates the files
    without minifying.
    """
    from .modules import minify, utils
    if not isinstance(input_files, (list, tuple)):
        raise RuntimeError('CSS minifier takes a list of input files.')
    return {'dependencies_fn': utils.no_dependencies, 'compiler_fn': minify
        .minify_css, 'input': input_files, 'output': output_file, 'kwargs': {}}


def _get_parser():
    """Get parser object for hasy_tools.py."""
    import argparse
    from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
    parser = ArgumentParser(description=__doc__, formatter_class=
        ArgumentDefaultsHelpFormatter)
    parser.add_argument('--dataset', dest='dataset', help=
        'specify which data to use')
    parser.add_argument('--verify', dest='verify', action='store_true',
        default=False, help='verify PNG files')
    parser.add_argument('--overview', dest='overview', action='store_true',
        default=False, help='Get overview of data')
    parser.add_argument('--analyze_color', dest='analyze_color', action=
        'store_true', default=False, help='Analyze the color distribution')
    parser.add_argument('--class_distribution', dest='class_distribution',
        action='store_true', default=False, help=
        'Analyze the class distribution')
    parser.add_argument('--distances', dest='distances', action=
        'store_true', default=False, help=
        'Analyze the euclidean distance distribution')
    parser.add_argument('--pca', dest='pca', action='store_true', default=
        False, help=
        'Show how many principal components explain 90%% / 95%% / 99%% of the variance'
        )
    parser.add_argument('--variance', dest='variance', action='store_true',
        default=False, help='Analyze the variance of features')
    parser.add_argument('--correlation', dest='correlation', action=
        'store_true', default=False, help='Analyze the correlation of features'
        )
    parser.add_argument('--create-classification-task', dest='create_folds',
        action='store_true', default=False, help=argparse.SUPPRESS)
    parser.add_argument('--create-verification-task', dest=
        'create_verification_task', action='store_true', default=False,
        help=argparse.SUPPRESS)
    parser.add_argument('--count-users', dest='count_users', action=
        'store_true', default=False, help=
        'Count how many different users have created the dataset')
    parser.add_argument('--analyze-cm', dest='cm', default=False, help=
        'Analyze a confusion matrix in JSON format.')
    return parser


def split_sized_data(data, ulong_unpack=ulong_unpack, null_field=4294967295,
    len=len, errmsg=
    'insufficient data in field {0}, required {1} bytes, {2} remaining'.format
    ):
    """
	Given serialized record data, return a tuple of tuples of type Oids and
	attributes.
	"""
    v = memoryview(data)
    f = 1
    while v:
        l = ulong_unpack(v)
        if l == null_field:
            v = v[4:]
            yield None
            continue
        l += 4
        d = v[4:l].tobytes()
        if len(d) < l - 4:
            raise ValueError(errmsg(f, l - 4, len(d)))
        v = v[l:]
        f += 1
        yield d


def world_remove():
    """Remove Rigid Body simulation world from the current scene

    """
    pass


@classmethod
def serialize(cls, conversation):
    """
        Serialize a conversation instance for storage.
        """
    return {'namespace': conversation.namespace, 'units': sorted(
        conversation.units), 'scope': conversation.scope}


def deepest_scope(v1, v2):
    """
    Returns the variable that is at the deepest scope. If they are equal in scope, then return v1.
    """
    s1 = v1.scope()
    s2 = v2.scope()
    if not s2.starts_with(s1):
        return v1
    if s1.starts_with(s2):
        return v1
    return v2


def combine(clusters):
    """Make new collocation analyses from data in clusters"""
    colls = []
    collocates = clusters[0].collocates
    for c in clusters[1:]:
        collocates = collocates.join(c.collocates, rsuffix='-' + str(c.
            period[0]))
    return collocates


def executeSQL(cursor, query, params=None):
    """ Execute a sqlite3 query """
    if params is None:
        return cursor.execute(query)
    return cursor.execute(query, params)


def cli_billing_get_invoice(client, name=None):
    """Retrieve invoice of specific name of the subscription"""
    if name:
        return client.get(name)
    return client.get_latest()


def bC_MgOH_CO3_HMW84(T, P):
    """c-a: magnesium-hydroxide carbonate [HMW84]."""
    b0 = 0.0
    b1 = 0.0
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


@classmethod
def register_resources(klass, registry, resource_class):
    """ meta model subscriber on resource registration.

        We watch for PHD event that provides affected entities and register
        the health-event filter to the resources.
        """
    services = {'acm-certificate', 'directconnect', 'dms-instance',
        'directory', 'ec2', 'dynamodb-table', 'cache-cluster', 'efs',
        'app-elb', 'elb', 'emr', 'rds', 'storage-gateway'}
    if resource_class.type in services:
        resource_class.filter_registry.register('health-event', klass)


def asciify(data):
    """
    Limit the byte data string to only ascii characters and convert it to a string.
    Non-representable characters are dropped.
    :param data: byte data string to convert to ascii
    :return: string
    """
    return ''.join(map(chr, filter(lambda x: x < 128, data)))


def get_scene_id(current_scene_db):
    """gets the scene ID from the scene db"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    get_scene_id = 'SELECT ID FROM "SceneMetadata"'
    cur.execute(get_scene_id)
    id = str(cur.fetchone()[0])
    conn.close()
    return id


def getPeer():
    """
        Returns L{IPv4Address} or L{IPv6Address}.
        """


def _left_rotate(n, b):
    """Left rotate a 32-bit integer n by b bits."""
    return (n << b | n >> 32 - b) & 4294967295


def is_tty(stream):
    """Returns True if the given stream is a tty, else False

    :param stream: object to be checked for being a tty
    :returns: True if the given object is a tty, otherwise False
    :rtype: bool
    """
    return hasattr(stream, 'isatty') and stream.isatty()