def compressnumbers(s):
    """Take a string that's got a lot of numbers and try to make something
        that represents that number. Tries to make
        unique strings from things like usb-0000:00:14.0-2

    """
    n = ''
    currentnum = ''
    for i in s:
        if i in '0123456789':
            if currentnum or not i == '0':
                currentnum += i
        else:
            n += currentnum
            currentnum = ''
    return n + currentnum


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


@classmethod
def _clear_cache(cls):
    """
        Clears the list of variables for reuse by :obj:`make`.
        """
    cls.all_continuous_vars.clear()


def context_set_float(data_path: str='', value: float=0.0, relative: bool=False
    ):
    """Set a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assignment value
    :type value: float
    :param relative: Relative, Apply relative to the current value (delta)
    :type relative: bool
    """
    pass


def _alias_properties_from_kwargs(site, archi, mobile=None):
    """To be used with **properties, checks given keys.

    Returns values.
    """
    return site, archi, mobile


def fill(use_beauty: bool=True):
    """Fill a selected edge loop with faces

    :param use_beauty: Beauty, Use best triangulation division
    :type use_beauty: bool
    """
    pass


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

        :param DataPlacementRestrictionChangePolicyType val:
        :rtype: EventType
        """
    return cls('data_placement_restriction_change_policy', val)


@staticmethod
def has_public_ip(addresses):
    """Return True is addresses contains an IP starting iwth 10.x."""
    return 'provider1' in addresses and addresses['provider1'][0]['addr'
        ].startswith('10.')


def skip_leading_ws_with_indent(s, i, tab_width):
    """Skips leading whitespace and returns (i, indent),

    - i points after the whitespace
    - indent is the width of the whitespace, assuming tab_width wide tabs."""
    count = 0
    n = len(s)
    while i < n:
        ch = s[i]
        if ch == ' ':
            count += 1
            i += 1
        elif ch == '\t':
            count += abs(tab_width) - count % abs(tab_width)
            i += 1
        else:
            break
    return i, count


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 t_USE_HOST_DECL_NAMES(t):
    """use-host-decl-names"""
    return t


@classmethod
def sql(cls):
    """
        Produces the SQL of the current query.
        """
    return cls.__query__.sql()


def post_install(context):
    """Post install script"""
    if context.readDataFile('collectiveredirectpage_default.txt') is None:
        return


def padded_num(num=-1, max_num=1):
    """
    The function that convert int to zero padded string

    :param int num: Number to be converted to string
    :param int max_num: Numbers to determine digits
    :return:
    """
    digit = len(str(max_num))
    if num >= 0:
        return str(num).zfill(digit)
    else:
        return '?' * digit


def read_chunk(filename, chunk_size, start):
    """
    Read a chunk of the trajectory file.

    Parameters
    ----------
    filename: string
        filename of the file to load
    chunk_size: int
        size of the chunk to load
    start: int
        frame to start the loading from

    Returns
    -------
    A tuple with the data for the read chunk (depending on what
    filetype.read returns)
    """
    with open(filename) as f:
        pos = f.tell()
        seek_pos = start
        rel_pos = seek_pos - pos
        f.seek(rel_pos, 1)
        result = f.read(chunk_size)
    if isinstance(result, tuple):
        return result
    else:
        return result,


def Boiling(G, q, Hvap):
    """Calculates Boiling number or `Bg` using heat flux, two-phase mass flux,
    and heat of vaporization of the fluid flowing. Used in two-phase heat
    transfer calculations.

    .. math::
        \\text{Bg} = \\frac{q}{G_{tp} \\Delta H_{vap}}

    Parameters
    ----------
    G : float
        Two-phase mass flux in a channel (combined liquid and vapor) [kg/m^2/s]
    q : float
        Heat flux [W/m^2]
    Hvap : float
        Heat of vaporization of the fluid [J/kg]

    Returns
    -------
    Bg : float
        Boiling number [-]

    Notes
    -----
    Most often uses the symbol `Bo` instead of `Bg`, but this conflicts with
    Bond number.

    .. math::
        \\text{Bg} = \\frac{\\text{mass liquid evaporated / area heat transfer
        surface}}{\\text{mass flow rate fluid / flow cross sectional area}}

    First defined in [4]_, though not named.

    Examples
    --------
    >>> Boiling(300, 3000, 800000)
    1.25e-05

    References
    ----------
    .. [1] Winterton, Richard H.S. BOILING NUMBER. Thermopedia. Hemisphere,
       2011. 10.1615/AtoZ.b.boiling_number
    .. [2] Collier, John G., and John R. Thome. Convective Boiling and
       Condensation. 3rd edition. Clarendon Press, 1996.
    .. [3] Stephan, Karl. Heat Transfer in Condensation and Boiling. Translated
       by C. V. Green.. 1992 edition. Berlin; New York: Springer, 2013.
    .. [4] W. F. Davidson, P. H. Hardie, C. G. R. Humphreys, A. A. Markson,
       A. R. Mumford and T. Ravese "Studies of heat transmission through boiler
       tubing at pressures from 500 to 3300 pounds" Trans. ASME, Vol. 65, 9,
       February 1943, pp. 553-591.
    """
    return q / (G * Hvap)


def __rand__(other):
    """Given BTrees.IFBTree data structure, return weighted intersection"""


def only_keys(d, *keys):
    """Returns a new dictionary containing only the given keys.

    Parameters
    ----------
    d : dict
        The original dictionary.
    keys: list of keys
        The keys to keep.  If a key is not found in the dictionary, it is
        ignored.
    """
    result = dict()
    for key in keys:
        if key in d:
            result[key] = d[key]
    return result


@classmethod
def loadPopplerDocument(cls, document, renderer=None, pageSlice=None):
    """Convenience class method yielding instances of this class.

        The Page instances are created from the document, in page number order.
        The specified Renderer is used, or else the global poppler renderer.
        If pageSlice is given, it should be a slice object and only those pages
        are then loaded.

        """
    it = range(document.numPages())
    if pageSlice is not None:
        it = it[pageSlice]
    for num in it:
        yield cls(document, num, renderer)


def complement_indices(A, B):
    """Returns a complement(A-B) indices in A

       Returns the indices of A's the complementary set

       Example:
       A = ['a', 'b', 'c']
       B = ['b','c']
       result = complement_indices(A,B)
       print(result)
       # prints [0]

    """
    indices = []
    for idx, i in enumerate(A, start=0):
        if i not in B:
            indices.append(idx)
    return indices


def get_function_kwargs(f):
    """
    Get dictionary of a function's keyword arguments and their default values.

    Args:
        :f:
            | function name

    Returns:
        :dict:
            | Dict with the function's keyword arguments and their default values
            | Is empty if there are no defaults (i.e. f.__defaults__ or f.__kwdefaults__ are None).
    """
    kwdefs = f.__kwdefaults__
    if kwdefs is None:
        kwdefs = {}
    names = f.__code__.co_varnames[:f.__code__.co_argcount]
    if f.__defaults__ is not None:
        d = dict(zip(names[::-1][:len(f.__defaults__)][::-1], f.__defaults__))
    else:
        d = {}
    d.update(kwdefs)
    return d


def _fd(f):
    """Get a filedescriptor from something which could be a file or an fd."""
    return f.fileno() if hasattr(f, 'fileno') else f


@staticmethod
def process_response(response):
    """
        Do nothing for now.
        """
    return response


def oecd(adult, children):
    """
        This is a scale used to calculate numbers of adult equivalents.
        The coefficents have been used in reference of Poverty Manual by World Bank.
    """
    return 1 + 0.7 * (adult - 1) + 0.5 * children


@classmethod
def named_scopes(cls):
    """Return all named Scopes."""
    return [cls.content, cls.settings, cls.user_state, cls.preferences, cls
        .user_info, cls.user_state_summary]


@staticmethod
def verify_arguments(data):
    """
        Verify arguments. Here is the verified logic:

            | verified | namespace | attribute | value |
            |----------|-----------|-----------|-------|
            |   True   |     Y     |     Y     |   Y   |
            |   True   |     Y     |     Y     |   -   |
            |   True   |     Y     |     -     |   -   |
            |   True   |     -     |     -     |   -   |
            |   False  |     -     |     Y     |   -   |
            |   False  |     -     |     -     |   Y   |
            |   False  |     -     |     Y     |   Y   |
            |   False  |     Y     |     -     |   Y   |

        :param data: (dict) Parsed arguments, e.g:
            {
                'namespace': 'user',
                'attribute': 'Name,
                'value': 'Eva'
            }
        :return: (bool) Arguments verified result
        """
    if data['value']:
        if not data['namespace'] or not data['attribute']:
            return False
    elif not data['namespace'] and data['attribute']:
        return False
    return True


def wrap_geom(geom):
    """ Wraps a geometry dict in an GeoJSON Feature
    """
    return {'type': 'Feature', 'properties': {}, 'geometry': geom}


def operator_operands(tokenlist):
    """ Generator to extract operators and operands in pairs """
    iterator = iter(tokenlist)
    while True:
        try:
            yield next(iterator), next(iterator)
        except StopIteration:
            break


def to_pyrocko_events(catalog):
    """
    Convert ObsPy catalog object to list of Pyrocko event objects.

    :param catalog:
        :py:class:`obspy.Catalog <obspy.core.event.Catalog>` object
    :returns:
        list of :py:class:`pyrocko.model.Event` objects or ``None`` if catalog
        is ``None``
    """
    obspy_catalog = catalog
    if obspy_catalog is None:
        return None
    from pyrocko import model
    events = []
    for obspy_event in obspy_catalog:
        for origin in obspy_event.origins:
            events.append(model.Event(name='%s-%s' % (obspy_event.
                resource_id, origin.resource_id), time=origin.time.
                timestamp, lat=origin.latitude, lon=origin.longitude, depth
                =origin.depth, region=origin.region))
    return events


def iterate(func, start):
    """Return ``start``, ``func(start)``, ``func(func(start))``, ...

        >>> from itertools import islice
        >>> list(islice(iterate(lambda x: 2*x, 1), 10))
        [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

    """
    while True:
        yield start
        start = func(start)


def extract_deb(archive, compression, cmd, verbosity, interactive, outdir):
    """Extract a DEB archive."""
    cmdlist = [cmd]
    if verbosity > 1:
        cmdlist.append('--vextract')
    else:
        cmdlist.append('--extract')
    cmdlist.extend(['--', archive, outdir])
    return cmdlist


def field2prop(field):
    """
    Convert a field to the property that is used to access that field

    :param field:
        A string or Symbol that represents the field
    :returns:
        Name of the property to access on the unit.
    """
    return str(field).replace('-', '_')


def EnterOrderNumber(*args, **kwargs):
    """ Stub Anduin function."""
    print('EnterOrderNumber', args, kwargs)


def _explore_capture(explore, g, node):
    """
    Adds the capture flags on the edges around the node. Of another capture
    is already flagged, append to the list.
    """
    explore.add(node.statement)
    g.add_node(node.statement)
    for p in g.predecessors(node):
        data = g.get_edge_data(p, node, default={'start_captures': []})
        data['start_captures'] = [*data.get('start_captures', []), node]
        g.add_edge(p, node.statement, **data)
    for s in g.successors(node):
        data = g.get_edge_data(node, s, default={'stop_captures': []})
        data['stop_captures'] = [node, *data.get('stop_captures', [])]
        g.add_edge(node.statement, s, **data)
    g.remove_node(node)


def __getitem__(name):
    """Get the action with the given name

        Actions are computed from form fields (IFormField).  If the
        form field used to create an action has a prefix, then that
        should be reflected in the name passed.
        """


def validate_string(value, label):
    """Validates that the given value is a string."""
    if not isinstance(value, str):
        raise ValueError('Invalid type for {0}: {1}.'.format(label, value))
    return value


def close():
    """
        Release external resources held by this object.

        This object may not be usable after this.
        """


@classmethod
def hmac_sha1(cls, key):
    """Creates a new HMAC SHA1 algorithm instance.

        Args:
            key: Signer key as a byte sequence.

        Returns:
            UserImportHash: A new ``UserImportHash``.
        """
    return cls._hmac('HMAC_SHA1', key)


def df_stdev(row, column_label_list=None):
    """
	Calculate the standard deviation of each row for the specified columns of a data frame

	Do not call this function directly; use it with df.apply() instead.

	data_frame["Stdev"] = data_frame.apply(df_stdev, args=(
				["Bob", "Alice"],), axis=1)

	:param row: row of the data frame
	:type row: pandas.core.series.Series
	:param column_label_list: list of column labels to calculate standard deviation for
	:type column_label_list: list

	:return: Standard deviation
	:rtype: float
	"""
    from numpy import nanstd
    if column_label_list is None:
        column_label_list = list(row.index)
    return nanstd(row[column_label_list])


def rolling_std(data, lookback_mean=1, lookback_std=10, k=1):
    """method to get anomalies as dates (DatetimeIndex) (dtype=datetime64[ns])
    - rolling mean mu_hat(n)
    - rolling std sigma_hat(n)
    - data points xn
    - anomalies definition: xn - mu_hat(n-1) > k*std_hat(n-1)

    - maximum ten anomalies (10 'biggest' anomalies)

    :argument data: dataframe with one column (interest) and pandas dates as index
    :argument k: float

    :returns anomalies as DatetimeIndex sorted(dtype=datetime64[ns])
    """
    mean = data.rolling(lookback_mean).mean().shift(1)
    std = data.rolling(lookback_std).std().shift(1)
    tmp = data - mean - k * std
    return tmp[tmp.iloc[:, (0)] > 0].sort_values(by=tmp.columns[0],
        ascending=False)[0:10].index.sort_values()


def d_(member, readable=True, writable=True, final=True):
    """ Mark an Atom member as bindable from Enaml syntax.

    Parameters
    ----------
    member : Member
        The atom member to mark as bindable from Enaml syntax.

    readable : bool, optional
        Whether the member is readable from Enaml syntax. The member
        must be readable to use the '>>', ':=', and '::' operators.
        The default is True.

    writable : bool, optional
        Whether the member is writable from Enaml syntax. The member
        must be writable to use the '=', '<<', and ':=' operators.
        The default is True.

    final : bool, optional
        Whether or not the member can be redefined from Enaml syntax
        using the 'attr' keyword. The default is True and indicates
        that the member cannot be overridden.

    """
    metadata = member.metadata
    if metadata is None:
        metadata = member.metadata = {}
    metadata['d_member'] = True
    metadata['d_readable'] = readable
    metadata['d_writable'] = writable
    metadata['d_final'] = final
    return member


@staticmethod
def _format_like(value) ->str:
    """
        Formatting value in the event of LIKE operation
        :param value: str
        :return: str
        """
    return "'{}'".format(value)


def _is_descriptor(obj):
    """Returns True if obj is a descriptor, False otherwise."""
    return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj,
        '__delete__')


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a Puppet forge item."""
    item_id = item['owner']['username'] + '-' + item['name']
    return item_id


def bashTemplate(template):
    """ return the bash commands required by template for batch simulation"""
    if template == 'mpi_direct':
        return '#!/bin/bash \n%s\ncd %s\n%s\n        '
    elif template == 'hpc_slurm':
        return """#!/bin/bash
#SBATCH --job-name=%s
#SBATCH -A %s
#SBATCH -t %s
#SBATCH --nodes=%d
#SBATCH --ntasks-per-node=%d
#SBATCH -o %s.run
#SBATCH -e %s.err
#SBATCH --mail-user=%s
#SBATCH --mail-type=end
%s
%s
source ~/.bashrc
cd %s
%s
wait
        """
    elif template == 'hpc_torque':
        return """#!/bin/bash
#PBS -N %s
#PBS -l walltime=%s
#PBS -q %s
#PBS -l %s
#PBS -o %s.run
#PBS -e %s.err
%s
cd $PBS_O_WORKDIR
echo $PBS_O_WORKDIR
%s
        """


@classmethod
def __is_required__(cls, name: str) ->bool:
    """Tell if the prop defined by `name` is a required one.

        Parameters
        ----------
        name : str
            The name of the prop we want to know if it is required.

        Returns
        -------
        bool
            ``True`` if the prop is required, ``False`` otherwise.

        """
    return name in cls.__required_props__


def MHCDEigenFrequencies(dg, r, Uhv=4000.0, rho=1.2041, yDirNum=4, xDirNum=4):
    """Eigenfrequency calculatioon of a micro hollow cathode discharge.

    Args:
        dg      :   Distance of electrodes (discharge gap).
        r       :   Radius of the discharge hole.
        Uhv     :   Voltage between electrodes.
        rho     :   Gas density.
        yDirNum :   Col Number of eigenfrequencies.
        xDirNum :   Row number of eigenfrequencies.

    Returns:
        Returns the eigenfrequencies of the discharge.

    """
    from scipy.special import jn, jn_zeros
    import numpy as np
    k = 3
    e0 = 8.854187817e-12
    vm = np.sqrt(e0 / rho) * Uhv / dg
    bessel_roots = np.zeros((xDirNum, yDirNum))
    for x in range(0, xDirNum):
        b = jn_zeros(x, yDirNum)
        for y in range(0, yDirNum):
            bessel_roots[y][x] = b[y]
    f = bessel_roots * vm * k / (2 * np.pi * r)
    return f


@staticmethod
def _get_headers(key, return_type):
    """
        Get HTTP request headers
         - Provisioning portal expects "X-Token" header,
         - VPSA expects "X-Access-Key".
         - We set them both.

        :param key: Access key
        :param return_type: Return type. 'raw', 'json' or 'xml'
        :return: headers dictionary
        :rtype: dict
        """
    headers = {'X-Access-Key': key, 'X-Token': key, 'x-auth-token': key}
    if return_type != 'raw':
        headers['Content-Type'] = 'application/json'
    return headers


def dt_monthname_long(dt):
    """Return long month name for datetime.
    """
    return dt.strftime('%B')


def content():
    """
        the content of the display yet
        """


def downgrade():
    """Downgrade database."""
    pass


def DISTINCT(src_column):
    """
    Builtin distinct values for groupby. Returns a list of distinct values.

    >>> sf.groupby("user",
    ...       {'rating_distinct':tc.aggregate.DISTINCT('rating')})
    """
    return '__builtin__distinct__', [src_column]


def slicerange(slice, limit):
    """Takes a slice object and returns a range iterator

    :param slice: slice object
    :param limit: maximum value allowed
    :returns: iterator
    """
    return range(*slice.indices(limit))


def create_plane_track():
    """Create new plane track out of selected point tracks

    """
    pass


@staticmethod
def applies_to(node):
    """
        Does this change affect the given XML node?
        n.b. prior Changes will already be applied to the node.
        """
    raise NotImplementedError


def get_summary(commit):
    """Determine the summary line for use in a filename.

    :param commit: Commit
    :return: Summary string
    """
    return commit.message.splitlines()[0].replace(' ', '-')


@classmethod
def from_code(cls, status, **kwargs):
    """ Instantiate one of subclasses by code

            :rtype: type
        """
    for C in cls.__subclasses__():
        if C.status == status:
            return C(**kwargs)
    return cls(**kwargs)


def describe_maintenance_window_tasks(WindowId=None, Filters=None,
    MaxResults=None, NextToken=None):
    """
    Lists the tasks in a Maintenance Window.
    See also: AWS API Documentation

    :example: response = client.describe_maintenance_window_tasks(
        WindowId='string',
        Filters=[
            {
                'Key': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxResults=123,
        NextToken='string'
    )

    :type WindowId: string
    :param WindowId: [REQUIRED]
            The ID of the Maintenance Window whose tasks should be retrieved.

    :type Filters: list
    :param Filters: Optional filters used to narrow down the scope of the returned tasks. The supported filter keys are WindowTaskId, TaskArn, Priority, and TaskType.
            (dict) --Filter used in the request.
            Key (string) --The name of the filter.
            Values (list) --The filter values.
            (string) --

    :type MaxResults: integer
    :param MaxResults: The maximum number of items to return for this call. The call also returns a token that you can specify in a subsequent call to get the next set of results.

    :type NextToken: string
    :param NextToken: The token for the next set of items to return. (You received this token from a previous call.)

    :rtype: dict
    :return: {
        'Tasks': [
            {
                'WindowId': 'string',
                'WindowTaskId': 'string',
                'TaskArn': 'string',
                'Type': 'RUN_COMMAND',
                'Targets': [
                    {
                        'Key': 'string',
                        'Values': [
                            'string',
                        ]
                    },
                ],
                'TaskParameters': {
                    'string': {
                        'Values': [
                            'string',
                        ]
                    }
                },
                'Priority': 123,
                'LoggingInfo': {
                    'S3BucketName': 'string',
                    'S3KeyPrefix': 'string',
                    'S3Region': 'string'
                },
                'ServiceRoleArn': 'string',
                'MaxConcurrency': 'string',
                'MaxErrors': 'string'
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def closeStdin():
    """
        Close stdin after all data has been written out.
        """


def calculate_discount(initial: int, current: int) ->int:
    """
    Calculates the % difference between initial and current price.

    Note: when initial is 0 (that is, old price was lower than the new one -
    very unlikely in Steam), we assume that increase is (new price * 100)%.

    :param initial: initial price
    :param current: current price
    :return integer: representing the discount
    """
    if initial is None or current is None:
        return 0
    if current == 0:
        return -100
    difference = current - initial
    initial = 1 if initial == 0 else initial
    percent = difference / initial * 100
    return int(round(percent, 0))


@classmethod
def init_from_nonzero_tuples(cls, d, dtype):
    """
        Create a polynomial from a list of tuples (in the format
        of poly.nonzero output).
        """
    q = cls.zero(dtype=dtype)
    for idx, val in d:
        q[idx] = val
    return q


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'node_modules',
        'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['split_imports'] = False
    prefs['sort_imports_alphabetically'] = False


def write_bytes(encoder, datum, schema=None):
    """Bytes are encoded as a long followed by that many bytes of data."""
    encoder.write_bytes(datum)


def set(key, value):
    """Call to enable special settings:

    ('DXImageTransform.Microsoft', True)
        enable support for parsing special MS only filter values

    Clears the tokenizer cache which holds the compiled productions!
    """
    if key == 'DXImageTransform.Microsoft' and value is True:
        from . import cssproductions
        from . import tokenize2
        tokenize2._TOKENIZER_CACHE.clear()
        cssproductions.PRODUCTIONS.insert(1, cssproductions._DXImageTransform)


def _station_code(station):
    """returns station code from a station dict"""
    return '-'.join([station['USAF'], station['WBAN']])


@classmethod
def _from_object(cls, receiver):
    """Construct a receiver from receiver object.

        @param cls: The target class.
        @param receiver: a receiver object that contains all fields.
        """
    kwargs = {'id': receiver.id, 'name': receiver.name, 'user': receiver.
        user, 'project': receiver.project, 'domain': receiver.domain,
        'created_at': receiver.created_at, 'updated_at': receiver.
        updated_at, 'actor': receiver.actor, 'params': receiver.params,
        'channel': receiver.channel}
    return cls(receiver.type, receiver.cluster_id, receiver.action, **kwargs)


def list_file_shares(GatewayARN=None, Limit=None, Marker=None):
    """
    Gets a list of the file shares for a specific file gateway, or the list of file shares that belong to the calling user account. This operation is only supported in the file gateway architecture.
    See also: AWS API Documentation

    :example: response = client.list_file_shares(
        GatewayARN='string',
        Limit=123,
        Marker='string'
    )

    :type GatewayARN: string
    :param GatewayARN: The Amazon resource Name (ARN) of the gateway whose file shares you want to list. If this field is not present, all file shares under your account are listed.

    :type Limit: integer
    :param Limit: The maximum number of file shares to return in the response. The value must be an integer with a value greater than zero. Optional.

    :type Marker: string
    :param Marker: Opaque pagination token returned from a previous ListFileShares operation. If present, Marker specifies where to continue the list from after a previous call to ListFileShares. Optional.

    :rtype: dict
    :return: {
        'Marker': 'string',
        'NextMarker': 'string',
        'FileShareInfoList': [
            {
                'FileShareARN': 'string',
                'FileShareId': 'string',
                'FileShareStatus': 'string',
                'GatewayARN': 'string'
            },
        ]
    }

    """
    pass


def correctTraceAndAlignment(dq_array, info, traceprofile, shift1,
    alignment_correction):
    """Correct the DQ array for the trace and alignment correction.
    The trace and alignment correction shifts every spectrum to a horizontal
    spectrum in (xfull, yfull) space.  The DQ arrays need to be shifted in the
    same way.

    Parameters
    ----------

    dq_array: array-like
        The input DQ array

    info: dictionary
        Keywords and values

    traceprofile: array-like
        Trace profile, a 1-d vector of delta YFULL values for each XCORR.  This
        was SUBTRACTED from the yfull values, so we need to ADD the NEGATIVE
        of this

    alignment_correction:
        The offset that was added to the YFULL values  to correct the alignment

    """
    nrows, ncols = dq_array.shape
    total_correction = None
    if alignment_correction is not None:
        total_correction = alignment_correction
        if traceprofile is not None:
            total_correction = -traceprofile + alignment_correction
    return


def getHistoryMetadata(obj):
    """Returns the versioning metadata history.
        """


def to_type(value, data_type):
    """Return ``value`` if instance of ``data_type`` else raise error.

    >>> to_type(1, int)
    1
    >>> eggs = to_type("eggs", unicode)
    >>> eggs == "eggs"
    True
    >>> type(eggs) == unicode
    True
    >>> to_type("1+j", complex)
    (1+1j)
    >>> to_type("eggs", float) # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    Traceback (most recent call last):
        ....
    ValueError: eggs cannot be cast to float.

    """
    if isinstance(value, data_type) or value is None:
        return value
    else:
        try:
            return data_type(value)
        except:
            raise ValueError('%s cannot be cast to %s.' % (value, data_type
                .__name__))


@classmethod
def _add_positional_arguments(cls, parser):
    """
        Add arg for model to parser

        Parameters
        ----------
        parser : 'argparser'
            Add arg to parser
        """
    parser.add_argument('model', help='Path to model')


def get_num_frames_in_event(event):
    """
    Gets the number of frames in an AGIPD 1M event retrieved from Karabo.

    This function retrieves the number of frames in each event for the detector
    identified by the 'karabo_detector_label' entry in the 'DataRetrievalLayer'
    configuration parameter group.

    NOTE: This function is designed to be injected as a member function into an
    :class:`~onda.utils.data_event.DataEvent` object.

    Arguments:

        event (:class:`~onda.utils.data_event.DataEvent`): an object storing the event
            data.

    Returns:

        int: the number of frames in the event.
    """
    return event.data[event.framework_info['detector_label']]['image.data'
        ].shape[0]


def accuracy_proba(predictions, y):
    """
    Returns accuracy metric using predictions probability.

    :param predictions: (np.array or pandas Series) Model predictions
    :param y: (np.array or pandas Series) actual results

    :return: metric that evaluates how close those predictions actually were
    :rtype: float
    """
    return 1 - (y - predictions).abs().mean()


def get_analog_status_small(name, field, units, object, readings):
    """
    Builds an analog reading without thresholds based on a single field

    Args:
        name: The name to apply to the reading
        field: The field with the reading
        units: The units of measure for the reading
        object: The object to parse
        readings: The list of readings to update
    """
    if field not in object:
        return
    reading = {'Name': name + ' ' + field, 'Reading': object[field],
        'Units': units, 'Health': None, 'LowerFatal': None, 'LowerCritical':
        None, 'LowerCaution': None, 'UpperCaution': None, 'UpperCritical':
        None, 'UpperFatal': None}
    readings.append(reading)


def file2histo(histo_filename, hist_obj):
    """

        Read the histogram in from a file with no header and two columns

        :type histo_filename: str
        :param histo_filename: path to the histogram text file with two columns, keep the energy dimensionless to avoid confusion.

        :type hist_obj: instance of the histo class
        :param hist_obj: contains all the info regarding the energy histogram of sites for a given material

        :raises: One has to initialize the histogram object before calling this function.
        pandas could throw up if the file is not formatted correctly. Refer examples section in the documentation.

        :rtype: histogram object with the energies and their densities updated

        """
    import pandas as pd
    import numpy as np
    histo_temp = pd.read_csv(histo_filename, header=None, delim_whitespace=True
        )
    hist_obj.E = np.array(histo_temp[0])
    hist_obj.RhoE = np.array(histo_temp[1])
    hist_obj.name = histo_filename
    hist_obj.nbins = len(hist_obj.E)
    return hist_obj


@classmethod
def from_binary_descriptor(cls, data):
    """
        Creates an endpoint object from a description of that endpoint.
        """
    return cls(data)


def select_role_certificates(rd, use, certs):
    """extend *certs* (a list) by certificates used by role descriptor *rd*.

  Note: *rd* may be ``None``.
  """
    if rd is None:
        return
    for kd in rd.KeyDescriptor:
        if use is None or kd.use is None or use == kd.use:
            ki = kd.KeyInfo
            for x509 in getattr(ki, 'X509Data', ()):
                cert = getattr(x509, 'X509Certificate', None)
                if cert is not None:
                    certs.append(cert[0])


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def _draw_circle(data, obj, draw_options):
    """Return the PGFPlots code for circles.
    """
    x, y = obj.center
    ff = data['float format']
    cont = ('\\draw[{}] (axis cs:' + ff + ',' + ff + ') circle (' + ff + ');\n'
        ).format(','.join(draw_options), x, y, obj.get_radius())
    return data, cont


def trimcase(string):
    """Convert string into trimmed string.

    Args:
        string: String to convert.

    Returns:
        string: Trimmed case string
    """
    return str(string).strip()


def connection_db_type(connection):
    """
	A totally broken attempt to determine what type of database a
	connection object is attached to.  Don't use this.

	The input is a DB API 2.0 compliant connection object, the return
	value is one of the strings "sqlite3" or "mysql".  Raises TypeError
	when the database type cannot be determined.
	"""
    if 'sqlite' in repr(connection):
        return 'sqlite'
    if 'mysql' in repr(connection):
        return 'mysql'
    raise TypeError(connection)


def _make_angle_gradient(X, Y, angle):
    """Generates index map for angle gradients."""
    import numpy as np
    Z = (180 * np.arctan2(Y, X) / np.pi + angle) % 360 / 360
    return Z


def canvas(with_attribution=True):
    """
    Placeholder function to show example docstring (NumPy format)

    Replace this function and doc string for your own project

    Parameters
    ----------
    with_attribution : bool, Optional, default: True
        Set whether or not to display who the quote is from

    Returns
    -------
    quote : str
        Compiled string including quote and optional attribution
    """
    quote = 'The code is but a canvas to our imagination.'
    if with_attribution:
        quote += '\n\t- Adapted from Henry David Thoreau'
    return quote


def clip(x, low, high):
    """Clip x so that it lies between the low and high marks."""
    return max(low, min(x, high))


@classmethod
def genprefix(cls, node, ns):
    """
        Generate a prefix.

        @param node: XML node on which the prefix will be used.
        @type node: L{sax.element.Element}
        @param ns: Namespace needing a unique prefix.
        @type ns: (prefix, URI)
        @return: I{ns} with a new prefix.
        @rtype: (prefix, URI)

        """
    for i in range(1, 1024):
        prefix = 'ns%d' % (i,)
        uri = node.resolvePrefix(prefix, default=None)
        if uri in (None, ns[1]):
            return prefix, ns[1]
    raise Exception('auto prefix, exhausted')


def index_rules_by_type(rules):
    """
    Indexes a list of rules by type name,
    while maintaining rule order for each rule type

    Sample Input:
    [
        <TimeRule: Time Rule>,
        <TimeRule: Time Rule>,
        <UserIsLoggedInRule: Logged in Rule>
    ]

    Sample Output:
    {
        'TimeRule': [ <TimeRule: Time Rule>, <TimeRule: Time Rule> ],
        'UserIsLoggedInRule': [ <UserIsLoggedInRule: Logged in Rule> ]
    }
    """
    indexed_rules = {}
    for rule in rules:
        type_name = type(rule).__name__
        if type_name in indexed_rules:
            indexed_rules[type_name].append(rule)
        else:
            indexed_rules[type_name] = [rule]
    return indexed_rules


@staticmethod
def unsafe_escape_like_string(parameter: str, escape_character: str='=') ->str:
    """
        This function purely escapes a string for use in an ILIKE or LIKE
        It does NOT make it safe to directly format a string.  YOU MUST
        STILL USE PSYCOPG2 PARAMETERIZATION.

        This makes it so that if you search for a string that includes a '%'
        character it still works.

        ..code::python

            my_search_string = 'something%or_another'
            escaped_search_string = escape_like_strings(my_search_string)
            query = "SELECT * FROM my_table WHERE name LIKE %s ESCAPE '='"
            execute_query(query, (f'%{escaped_search_string}%',))
        """
    return parameter.replace(escape_character, f'{escape_character * 2}'
        ).replace('%', f'{escape_character}%').replace('_',
        f'{escape_character}_')


def avgcolor(imageobj):
    """Get the average color of the PIL.Image object.

    imageobj: the image
    returns a RGB tuple.
    """
    r = 0
    g = 0
    b = 0
    totalcount = 0
    colors = 256
    arr = None
    while True:
        arr = imageobj.getcolors(colors)
        if arr is None:
            colors *= 2
        else:
            break
    for tup in arr:
        r += tup[0] * tup[1][0]
        g += tup[0] * tup[1][1]
        b += tup[0] * tup[1][2]
        totalcount += tup[0]
    r //= totalcount
    g //= totalcount
    b //= totalcount
    return r, g, b


def kaldi_lvl_to_logging_lvl(lvl):
    """Convert kaldi level to logging level"""
    if lvl <= 1:
        lvl = lvl * -10 + 20
    else:
        lvl = 11 - lvl
    return lvl


@classmethod
def _create_column_info(cls, name: str, data_type: str) ->dict:
    """
        Create column info object
        :param name: column name
        :param data_type: column data type
        :return: column info object
        """
    return {'name': name, 'type': f'{data_type}'}


@staticmethod
def __updateMany(cls_or_instance, query: dict, update: dict, upsert=False,
    array_filters=None, bypass_document_validation=False, collation=None,
    session=None, db=None):
    """Update specific fields for many documents.

        equal to db.collection.updateMany(query, {$set: {key: new_val})
        """
    __db = db if db else cls_or_instance.__db
    return __db[cls_or_instance.__collection__].update_many(query, {'$set':
        update}, upsert=upsert, array_filters=array_filters,
        bypass_document_validation=bypass_document_validation, collation=
        collation, session=session)


def _np_dtype(attribute_type):
    """
    Return a relevant numpy dtype entry.
    """
    if attribute_type in ('double', 'float', 'real'):
        return float
    elif attribute_type in ('int', 'integer'):
        return int
    else:
        return object


def setGlobalPrintPrivateEntries(enabled=False):
    """
    When enabled, Container __str__ shows keys like _ _index _etc, otherwise and by default, it hides those keys. __repr__ never shows private entries.

    :param enabled: bool
    """
    global globalPrintPrivateEntries
    globalPrintPrivateEntries = enabled


def normalize_range(e, n):
    """
    Return the range tuple normalized for an ``n``-element object.

    The semantics of a range  is slightly different than that of a slice.
    In particular, a range is similar to a list in meaning (and on Py2 it was
    eagerly expanded into a list). Thus we do not allow the range to generate
    indices that would be invalid for an ``n``-array. Furthermore, we restrict
    the range to produce only positive or only negative indices. For example,
    ``range(2, -2, -1)`` expands into ``[2, 1, 0, -1]``, and it is confusing
    to treat the last "-1" as the last element in the list.

    :param e: a range object representing a selector
    :param n: number of elements in a sequence to which ``e`` is applied
    :returns: tuple ``(start, count, step)`` derived from ``e``, or None
        if the range is invalid.
    """
    if e.step > 0:
        count = max(0, (e.stop - e.start - 1) // e.step + 1)
    else:
        count = max(0, (e.start - e.stop - 1) // -e.step + 1)
    if count == 0:
        return 0, 0, e.step
    start = e.start
    finish = e.start + (count - 1) * e.step
    if start >= 0:
        if start >= n or finish < 0 or finish >= n:
            return None
    else:
        start += n
        finish += n
        if start < 0 or start >= n or finish < 0 or finish >= n:
            return None
    assert count >= 0
    return start, count, e.step


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 '+'


@staticmethod
def na_remplacing(serie):
    """ remplace None with '_missing_' to make it a modality """
    ii_null = serie.isnull()
    if not ii_null.any():
        return serie
    result_serie = serie.copy()
    result_serie[ii_null] = '_missing_'
    return result_serie


def _send_data_tf(event):
    """Standard logging handler for sending a P-DATA-TF PDU."""
    pass


def _convert_gpslatitude_gpslongitude_to_degrees(value):
    """
    Helper function to convert the GPS coordinates stored in the EXIF GPSLatitude or GPSLongitude to degrees in float format
    Don't call directly, use get_latitude_longitude()
    """
    deg_num, deg_denom = value[0]
    d = float(deg_num) / float(deg_denom)
    min_num, min_denom = value[1]
    m = float(min_num) / float(min_denom) if min_denom != 0 else 0
    sec_num, sec_denom = value[2]
    s = float(sec_num) / float(sec_denom) if sec_denom != 0 else 0
    return d + m / 60.0 + s / 3600.0


def select_linked():
    """Select keyframes occurring in the same F-Curves as selected ones

    """
    pass


def add_extra_nonce_to_tx_extra(extra, extra_nonce):
    """
    Appends nonce extra to the extra buffer
    :param extra:
    :param extra_nonce:
    :return:
    """
    if len(extra_nonce) > 255:
        raise ValueError('Nonce could be 255 bytes max')
    extra += b'\x02' + len(extra_nonce).to_bytes(1, 'big') + extra_nonce
    return extra


def any_of(*args):
    """Return regex that matches any of the input regex patterns.

    The returned value is equivalent to writing::

        r'(<arg1>|<arg2>|...)'
    """
    return '({})'.format('|'.join(args))


def html(text):
    """
    Macro tag <<html>>...<</html>>
    Pass-trought for html code (or other stuff)
    """
    return text


@classmethod
def explicit_cutoff(cls, cutoff_byte):
    """
        Extracts the explicit cutoff value from the cutoff byte of a serialized HLL.

        :param byte cutoff_byte: the cutoff byte of the serialized HLL
        :returns: the explicit cutoff value
        :rtype: int
        """
    return cutoff_byte & cls.EXPLICIT_CUTOFF_MASK


def array_from(obj, func, *args):
    """
        from elist.elist import *
        array_from("abcd",None)
        #####
        def map_func(ele,x,y):
            return(int(ele)+x+y)

        array_from("1234",map_func,1000,100)

        def map_func(ele):
            return(int(ele)*2)

        array_from("1234",map_func)

        array_from("1234",None)
    """
    if func:
        l = list(obj)
        rslt = list(map(lambda ele: func(ele, *args), l))
        return rslt
    else:
        return list(obj)


def completions(cls, cc_prefix):
    """Return all country codes starting with `cc_prefix` and unique
           completion for `cc_prefix`, if any.
        """
    return cls.cc_trie.completions(cc_prefix)


def takes_args(function):
    """Returns True if the supplied functions takes extra non-keyword arguments"""
    return bool(function.__code__.co_flags & 4)


def readConnectionLost():
    """
        Notification of the read connection being closed.

        This indicates peer did half-close of write side. It is now
        the responsibility of the this protocol to call
        loseConnection().  In addition, the protocol MUST make sure a
        reference to it still exists (i.e. by doing a callLater with
        one of its methods, etc.)  as the reactor will only have a
        reference to it if it is writing.

        If the protocol does not do so, it might get garbage collected
        without the connectionLost method ever being called.
        """


@staticmethod
def coordinates(model):
    """Return dictionary with keys latitude and longitude."""
    return {'latitude': model.latitude, 'longitude': model.longitude}


def remove_ticks_labels(ax, remove_x=True, remove_y=True):
    """Remove ticks and labels from axes"""
    if remove_x:
        ax.set_xticklabels([])
        ax.set_xticks([])
    if remove_y:
        ax.set_yticklabels([])
        ax.set_yticks([])


def openCommittedBlobFile(oid, serial, blob=None):
    """Return a file for committed data for the given object id and serial

        If a blob is provided, then a BlobFile object is returned,
        otherwise, an ordinary file is returned.  In either case, the
        file is opened for binary reading.

        This method is used to allow storages that cache blob data to
        make sure that data are available at least long enough for the
        file to be opened.
        """


def atomic_number(atom):
    """Get the atomic number for an atom.

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

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


def type_to_str(type_object) ->str:
    """
    convert a type object to class path in str format
    :param type_object: type
    :return: class path
    """
    cls_name = str(type_object)
    assert cls_name.startswith("<class '"), 'illegal input'
    cls_name = cls_name[len("<class '"):]
    assert cls_name.endswith("'>"), 'illegal input'
    cls_name = cls_name[:-len("'>")]
    return cls_name


def is_terminal(n):
    """returns true if the node contains only one terminal or less"""
    return len(n.get_terminals()) <= 1


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 constraints_copy():
    """Copy constraints to other selected bones

    """
    pass


def special_mode(v):
    """decode Olympus SpecialMode tag in MakerNote"""
    mode1 = {(0): 'Normal', (1): 'Unknown', (2): 'Fast', (3): 'Panorama'}
    mode2 = {(0): 'Non-panoramic', (1): 'Left to right', (2):
        'Right to left', (3): 'Bottom to top', (4): 'Top to bottom'}
    if not v or (v[0] not in mode1 or v[2] not in mode2):
        return v
    return '%s - sequence %d - %s' % (mode1[v[0]], v[1], mode2[v[2]])


def assert_is_lon(val):
    """
    Checks it the given value is a feasible decimal longitude

    :param val: value to be checked
    :type val: int of float
    :returns:  `None`
    :raises: *ValueError* if value is out of longitude boundaries, *AssertionError* if type is wrong

    """
    assert type(val) is float or type(val) is int, 'Value must be a number'
    if val < -180.0 or val > 180.0:
        raise ValueError('Longitude value must be between -180 and 180')


@staticmethod
def defaultSymbol():
    """
        Returns the default symbol path for this node.

        :returns: symbol path (or resource).
        """
    return ':/symbols/vpcs_guest.svg'


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 format_form_errors(form):
    """Formats form errors in HTML
    if there is only one error - returns a plain string
    if more than one, returns an unordered list of errors
    in HTML format.
    If there are no errors, returns empty string
    """
    if form.errors:
        errors = form.errors.values()
        if len(errors) == 1:
            return errors[0]
        else:
            result = '
'
            for error in errors:
                result += '
%s
' % error
            result += '
'
            return result
    else:
        return ''


def itersplitat(string, positions):
    """
	Split ``string`` at the positions specified in ``positions``.

	For example::

		>>> from ll import misc
		>>> import datetime
		>>> datetime.datetime(*map(int, misc.itersplitat("20090609172345", (4, 6, 8, 10, 12))))
		datetime.datetime(2009, 6, 9, 17, 23, 45)

	This is a generator.
	"""
    curpos = 0
    for pos in positions:
        part = string[curpos:pos]
        if part:
            yield part
        curpos = pos
    part = string[curpos:]
    if part:
        yield part


def out_of_china(lng, lat):
    """
    判断是否在国内，不在国内不做偏移
    :param lng:
    :param lat:
    :return:
    """
    return not (lng > 73.66 and lng < 135.05 and lat > 3.86 and lat < 53.55)


@staticmethod
def generate_sms_endpoint(phone=None):
    """
            @type phone: string
            @param phone: the number of phone
        """
    endpoint = ('sms:directsms:anonymous' if phone is None else
        'sms:directsms:%s' % phone)
    return endpoint


def _get_qpoint_pos(pos):
    """Return the coordinates of a QPointF object."""
    return pos.x(), pos.y()


def fixer_round(value, n_digits):
    """
	Round all float numbers.

	Parameters
	----------
	n_digits : int
		Number of digits to keep.
	"""
    if type(value) is float:
        return round(value, n_digits)
    return value


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


@classmethod
def make_request(cls, memory_location, dfi=None):
    """
        Generates a request for RequestUpload

        :param memory_location: The address and the size of the memory block to be read.
        :type memory_location: :ref:`MemoryLocation <MemoryLocation>`

        :param dfi: Optional dataFormatIdentifier defining the compression and encryption scheme of the data.
                If not specified, the default value of 00 will be used, specifying no encryption and no compression
        :type dfi: :ref:`DataFormatIdentifier <DataFormatIdentifier>`

        :raises ValueError: If parameters are out of range, missing or wrong type
        """
    from udsoncan import Request, MemoryLocation
    dfi = cls.normalize_data_format_identifier(dfi)
    if not isinstance(memory_location, MemoryLocation):
        raise ValueError(
            'memory_location must be an instance of MemoryLocation')
    request = Request(service=cls)
    request.data = b''
    request.data += dfi.get_byte()
    request.data += memory_location.alfid.get_byte()
    request.data += memory_location.get_address_bytes()
    request.data += memory_location.get_memorysize_bytes()
    return request


def shimbel(w):
    """
    Find the Shimbel matrix for first order contiguity matrix.

    Parameters
    ----------
    w     : W
            spatial weights object

    Returns
    -------

    info  : list
            list of lists; one list for each observation which stores
            the shortest order between it and each of the the other observations.

    Examples
    --------
    >>> from libpysal.weights import lat2W, shimbel
    >>> w5 = lat2W()
    >>> w5_shimbel = shimbel(w5)
    >>> w5_shimbel[0][24]
    8
    >>> w5_shimbel[0][0:4]
    [-1, 1, 2, 3]
    """
    info = {}
    ids = w.id_order
    for i in ids:
        s = [0] * w.n
        s[ids.index(i)] = -1
        for j in w.neighbors[i]:
            s[ids.index(j)] = 1
        k = 1
        flag = s.count(0)
        while flag:
            p = -1
            knext = k + 1
            for j in range(s.count(k)):
                neighbor = s.index(k, p + 1)
                p = neighbor
                next_neighbors = w.neighbors[ids[p]]
                for neighbor in next_neighbors:
                    nid = ids.index(neighbor)
                    if s[nid] == 0:
                        s[nid] = knext
            k = knext
            flag = s.count(0)
        info[i] = s
    return info


@classmethod
def getIdentity(cls):
    """return class identity as stored in database (currently class name
        with …Control stripped out)."""
    return cls.__mapper_args__['polymorphic_identity'
        ] if 'polymorphic_identity' in cls.__mapper_args__ else None


def get_the_processes_name(executed_cursor, pid):
    """Return the process name."""
    process_name_query = """
                SELECT name, argv
                FROM executed_files
                WHERE process = %s
                """
    executed_cursor.execute(process_name_query % pid)
    return executed_cursor.fetchall()


def get_lomb_lambda(lomb_model):
    """Get the regularization parameter of a fitted Lomb-Scargle model."""
    return lomb_model['freq_fits'][0]['lambda']


def get_rendition_upload_to(instance, filename):
    """
    Obtain a valid upload path for an image rendition file.

    This needs to be a module-level function so that it can be referenced within migrations,
    but simply delegates to the `get_upload_to` method of the instance, so that AbstractRendition
    subclasses can override it.
    """
    return instance.get_upload_to(filename)


def name(approach):
    """Return approach name. Removes double spaces in display

    Doctest:

    .. doctest::

        >>> from snowballing.operations import reload
        >>> reload()
        >>> [[a, m]] = get_approaches()
        >>> name(a)
        'noWorkflow'
    """
    return approach.display.replace('  ', '')


@classmethod
def disable(cls):
    """Disables page domain notifications.
        """
    return cls.build_send_payload('disable', {}), None


def trim_obd_value(v):
    """
    Trims unneeded data from an OBD response
    :param str v:
    :return str:
    """
    if not v or len(v) < 4:
        return ''
    else:
        return v[4:]


def constraint_grouping(node, fallback=lambda *xs, **ks: None):
    """Grouping function for constraints.

    This function can be passed in a list to :attr:`groupings` of
    :class:`oemof.solph.network.EnergySystem`.

    Parameters
    ----------
    node : :class:`Node <oemof.network.Node`
        The node for which the figure out a constraint group.
    fallback : callable, optional
        A function of one argument. If `node` doesn't have a `constraint_group`
        attribute, this is used to group the node instead. Defaults to not
        group the node at all.
    """
    cg = getattr(node, 'constraint_group', fallback)
    return cg()


def list_concat(*lists):
    """
    joins multiple lists into a single list. Always returns a copy.

    """
    ret = list()
    for l in lists:
        ret.extend(l)
    return ret


def assert_almost_equal(a, b, delta=1e-08):
    """Asserts that abs(a - b) <= delta
    """
    assert abs(a - b) <= delta


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

        :param DomainInvitesSetInviteNewUserPrefToNoDetails val:
        :rtype: EventDetails
        """
    return cls('domain_invites_set_invite_new_user_pref_to_no_details', val)


@classmethod
def adapt_emulated_to_native(cls, impl, **kw):
    """Produce a MySQL native :class:`.mysql.ENUM` from plain
        :class:`.Enum`.

        """
    kw.setdefault('validate_strings', impl.validate_strings)
    kw.setdefault('values_callable', impl.values_callable)
    return cls(**kw)


def primitive_nurbs_surface_torus_add(radius: float=1.0, view_align: bool=
    False, enter_editmode: bool=False, location: float=(0.0, 0.0, 0.0),
    rotation: float=(0.0, 0.0, 0.0), layers: bool=(False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False)):
    """Construct a Nurbs surface Torus

    :param radius: Radius
    :type radius: float
    :param view_align: Align to View, Align the new object to the view
    :type view_align: bool
    :param enter_editmode: Enter Editmode, Enter editmode when adding this object
    :type enter_editmode: bool
    :param location: Location, Location for the newly added object
    :type location: float
    :param rotation: Rotation, Rotation for the newly added object
    :type rotation: float
    :param layers: Layer
    :type layers: bool
    """
    pass


def load_dataset(name):
    """
    Example datasets.

    Parameters
    ----------
    name : str
        Possible dataset names are ``"kinship"``, ``"dali"``, and ``"gwas"``.

    Returns
    -------
    data : ndarray, dataframe
        Selected dataset.
    """
    import io
    from bz2 import decompress
    from pandas import read_pickle
    from numpy import load
    from urllib.request import urlopen
    if name == 'kinship':
        c = urlopen('http://rest.s3for.me/limix/1000G_kinship.npy').read()
        f = io.BytesIO(c)
        return load(f)
    elif name == 'dali':
        c = urlopen('http://rest.s3for.me/limix/dali.jpg.bz2').read()
        o = decompress(c)
        return io.BytesIO(o)
    elif name == 'gwas':
        c = urlopen('http://rest.s3for.me/limix/mdd_small.pkl.bz2').read()
        o = decompress(c)
        return read_pickle(io.BytesIO(o), compression=None)
    raise ValueError('Unknown dataset {}.'.format(name))


def gcd(a, b):
    """Return greatest common divisor using Euclid's Algorithm."""
    while b:
        a, b = b, a % b
    return a


def is_scalar(value):
    """Checks if the supplied value can be converted to a scalar."""
    try:
        float(value)
    except (TypeError, ValueError):
        return False
    else:
        return True


def _transpose_named_matrix(mat):
    """Transpose mat inplace (no copy)."""
    mat['nrow'], mat['ncol'] = mat['ncol'], mat['nrow']
    mat['row_names'], mat['col_names'] = mat['col_names'], mat['row_names']
    mat['data'] = mat['data'].T


@classmethod
def poisson_gt(cls, tau_1, tau_2, symbolic=False):
    """Asymptotic development of ``P(X_1 > X_2)``, where ``X_i ~ Poison(tau_i * n)``.

        Parameters
        ----------
        tau_1,tau_2 : Number
            The parameter of the Poisson distribution of ``X_i`` is ``tau_i * n``, where `n` tends to infinity.
        symbolic : bool
            Whether the computations are symbolic or numeric.

        Returns
        -------
        Asymptotic
            The asymptotic development of ``P(X_1 > X_2)``, where ``X_i ~ Poison(tau_i * n)``.

        Examples
        --------
            >>> from math import log
            >>> print(Asymptotic.poisson_gt(tau_1=0, tau_2=0))
            exp(- inf)
            >>> print(Asymptotic.poisson_gt(tau_1=0, tau_2=1/10))
            exp(- inf)
            >>> print(Asymptotic.poisson_gt(tau_1=1/10, tau_2=0))
            exp(o(1))
            >>> Asymptotic.poisson_gt(tau_1=9/10, tau_2=1/10).look_equal(
            ...     Asymptotic(mu=0, nu=0, xi=0))
            True
            >>> Asymptotic.poisson_gt(tau_1=3/10, tau_2=3/10).look_equal(
            ...     Asymptotic(mu=0, nu=0, xi=-log(2)))
            True
            >>> asymptotic = Asymptotic.poisson_gt(tau_1=1/10, tau_2=9/10)
            >>> asymptotic_eq = Asymptotic.poisson_eq(tau_1=1/10, tau_2=9/10)
            >>> asymptotic.look_equal(
            ...     Asymptotic(mu=asymptotic_eq.mu, nu=asymptotic_eq.nu, xi=asymptotic_eq.xi - log(2)))
            True
        """
    return cls.poisson_x1_ge_x2_plus_k(tau_1, tau_2, 1, symbolic=symbolic)


def seconds_to_str(seconds):
    """Approximate text description of how many seconds

    Parameters
    ----------
    seconds: int
        number of seconds

    Returns
    -------
    str:
        Something like: 30 seconds, or 4 minutes

    """
    minutes = int(seconds / 60)
    if minutes:
        return f'{minutes} min, '
    else:
        return f'{seconds % 60:0.0f} seconds'


@classmethod
def _get_apic_classes(cls):
    """
        Get the APIC classes used by this acitoolkit class.

        :returns: list of strings containing APIC class names
        """
    resp = ['eqptFan']
    return resp


def get_model(sbml):
    """
    return the model of a SBML
    """
    model_element = None
    for e in sbml:
        if e.tag[0] == '{':
            uri, tag = e.tag[1:].split('}')
        else:
            tag = e.tag
        if tag == 'model':
            model_element = e
            break
    return model_element


@staticmethod
def realGamma(gamma):
    """Return the value of ``gamma`` property, scaled appropriately.
        for use as an exponent.
        """
    if gamma < 0:
        return (gamma + 1.01) * 0.99
    else:
        return 1 + 9 * gamma


def org(base_url: str, organization_id: str=None) ->str:
    """
    Build the URL to access organizations
    """
    if not organization_id:
        return '/'.join([base_url, 'organizations'])
    return '/'.join([base_url, 'organizations', organization_id])


def _create_djset(args, cls):
    """ Return a DjSecret object """
    name = args.get('--name')
    settings = args.get('--settings')
    if name:
        return cls(name=name)
    elif settings:
        return cls(name=settings)
    else:
        return cls()


def get_neighborhood_vertex(G, v, h):
    """
    Given a vertex and a height/depth to
    traverse, find the neighborhood as defined in the CONGA
    paper.
    """
    return G.neighborhood(v, order=h)


def merge_two_dicts(dict1, dict2):
    """
    Compatible function to merge two dictionaries.
    """
    merged = dict1.copy()
    merged.update(dict2)
    return merged


@staticmethod
def dbm_to_watts(power_dbm):
    """Converts [dBm] to [W].

        Args:
            power_dbm (int, float): Power in [dBm].

        Returns:
            float: Power in [W].
        """
    power_W = 10.0 ** (power_dbm / 10.0) / 1000.0
    return power_W


def inttomonth(inmonth):
    """
    Turn integer month into string month.
    Necessary for webfetch.
    """
    if inmonth > 12:
        inmonth = 12
    if inmonth < 1:
        inmonth = 1
    strmonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
        'Sep', 'Oct', 'Nov', 'Dec']
    return strmonth[inmonth - 1]


def get_output(response, more_out=False):
    """
    Returns final output to display

    :param response: WoppResponse object to get the info
    :param more_out: more or less information?
    :return: dict containing output information
    """
    out_dict = {'name': response.name, 'current_version': response.
        latest_version, 'summary': response.summary, 'homepage': response.
        homepage, 'package_url': response.package_url, 'author': response.
        author}
    if more_out:
        out_dict.update({'author_email': response.author_email, 'releases':
            ', '.join(response.releases) if response.releases else None,
            'project_urls': response.project_urls, 'requires_python':
            response.requires_python, 'license': response.license,
            'current_release_url': response.latest_release_url,
            'current_package_info': response.latest_pkg_urls,
            'dependencies': ', '.join(response.dependencies) if response.
            dependencies else None})
    else:
        out_dict.update({'latest_releases': ', '.join(response.
            latest_releases) if response.latest_releases else None})
    return out_dict


def scale_color(img, max_val=255.0):
    """Scales an image of color values (int) [0,255] to (float) [0,1]"""
    return img / max_val


def update_app_setting(setting, data):
    """
    Update app setting from the project configuration definition file.
    """
    kwargs = {}
    for key, value in data.items():
        if key == 'type':
            raise ValueError('Setting `type` attribute denied to update')
        kwargs[key] = value
    setting.update(**kwargs)
    return setting


def transpose3(matrix):
    """Return the inversion (transpose) of 3x3 rotation matrix ``matrix``."""
    return matrix[0], matrix[3], matrix[6], matrix[1], matrix[4], matrix[7
        ], matrix[2], matrix[5], matrix[8]


@classmethod
def fromFile(cls, filePath, *args, **kwargs):
    """
        Load a NARC archive from a filesystem file.
        """
    with open(filePath, 'rb') as f:
        return cls(f.read(), *args, **kwargs)


def filename_to_list(filename):
    """Return a list of package/module names from a filename.

    One example is worth a thousand descriptions:

        >>> filename_to_list('z3c.coverage.__init__.cover')
        ['z3c', 'coverage', '__init__']

    """
    return filename.split('.')[:-1]


def stat(*unused_args, **unused_kwargs):
    """Method os.stat() is forbidden"""
    raise RuntimeError(
        'Usage of os.stat() is forbidden. Use certbot.compat.filesystem functions instead (eg. has_min_permissions, has_same_ownership).'
        )


def create_system_id(os_string, architecture):
    """
    Create a system-ID by joining the OS-String and the architecture with a hyphen.

    Args:
        os_string (str):
            The Operating system string.
        architecture (str):
            The Architecture string.

    Returns:
        The System-ID string.

    """
    system_id_format = '{os_string} {architecture}'
    return system_id_format.format(os_string=os_string.replace('_', ' '),
        architecture=architecture)


def make_chimera_attribute_file(column, recipient='residues', match_mode=
    '1 - to - 1'):
    """
    Write a UFSC Chimera attribute file. It assumes that the pd.Series index
        matches to the residue number in the target protein structure.
    :param pd.Series column: column with attributes in data and recipient in the index
    :param str recipient: level of attribute assignment. Choice from atoms,
        residues and molecules.
    :param str match_mode:
    :return None:

    .. example:
        generate_chimera_attrFile(variants.applymap(counts).tcga)

    .. note: Documentation
        https://www.cgl.ucsf.edu/chimera/docs/ContributedSoftware/defineattrib/defineattrib.html

    """
    if recipient not in ['atoms', 'residues', 'molecules']:
        raise ValueError('The recipient is not supported.')
    if recipient != 'residues':
        raise NotImplementedError
    try:
        name = column.name
    except AttributeError:
        raise TypeError('Column parameter needs to be a pd.Series.')
    template = """# Generated with ProteoFAV
    attribute: {name}
    match mode: {match_mode}
    recipient: {recipient}
    """
    column = column.reset_index()
    formatter = ['\t:{}'.format, '\t{}'.format]
    lines = column.to_string(index=False, header=False, formatters=formatter)
    lines = lines.replace(' ', '')
    return template.format(name=name, match_mode=match_mode, recipient=
        recipient) + lines


def store_trees(prefix=None, start_year=2015, tree_dict={}):
    """Saves values of `BaseStorageTree` objects. The file is saved into the 'data' directory
    in the current working directory. If there is no 'data' directory, one is created.

    Parameters
    ----------
    prefix : str, optional
        prefix to be added to file_name
    start_year : int, optional
        start year of analysis
    **kwargs
        arbitrary keyword arguments of `BaseStorageTree` objects

    """
    if prefix is None:
        prefix = ''
    for name in tree_dict.keys():
        tree_dict[name].write_columns(prefix + 'trees', name, start_year)


def psi_Ca_K_HCO3_HMW84(T, P):
    """c-c'-a: calcium potassium bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def cmp(a, b):
    """
    Compare a and b. Returns -1 if b > a, 1 if a > b, or 0 if a == b
    """
    return (a > b) - (a < b)


def get_number_is_days():
    """If number_is_days is True, the number_to_show will control
        days back to show instead of number of items.
        """


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

        :param SharedLinkSettingsRemoveExpirationType val:
        :rtype: EventType
        """
    return cls('shared_link_settings_remove_expiration', val)


def second(seq):
    """ The second element in a sequence

    >>> second('ABC')
    'B'
    """
    seq = iter(seq)
    next(seq)
    return next(seq)


def marker_jump(next: bool=True):
    """Jump to previous/next marker

    :param next: Next Marker
    :type next: bool
    """
    pass


def exhaustible(iterable):
    """Returns True if *iterable* is an exhaustible iterator."""
    return iter(iterable) is iter(iterable)


@staticmethod
def p_word_next(symbols):
    """word_next : CHARACTER word_next
                     | empty
        """
    if len(symbols) == 2:
        symbols[0] = ''
    else:
        symbols[0] = symbols[1] + symbols[2]


def get_table_count(extcsv, table):
    """
    Return the number of occurance of tables in
    extcsv
    """
    count = 0
    for t in extcsv.sections.keys():
        if table in t:
            count += 1
    return count


def convert_string_to_list(string_val):
    """Helper function to convert string to list.
     Used to convert shape attribute string to list format.
    """
    result_list = []
    list_string = string_val.split(',')
    for val in list_string:
        val = str(val.strip())
        val = val.replace('(', '')
        val = val.replace(')', '')
        val = val.replace('L', '')
        val = val.replace('[', '')
        val = val.replace(']', '')
        if val not in ('', 'None'):
            result_list.append(int(val))
    return result_list


def count_truthy(items):
    """
    Count non None values viz, but includes 0
    ----
    examples:

    1) count_truthy([1, 2, None, 'a']) -> 3
    2) count_truthy([1, 2, 0, 'a']) -> 4
    ----
    :param items: list
    :return: int
    """
    counter = 0
    for item in items:
        if item is not None:
            counter += 1
    return counter


def pad_tuple(tup, length, pad_val=None):
    """Pad the given tuple to the given length.

    If the input is not a tuple, convert it to a tuple of length one.
    Return None if pad fails.
    """
    if not isinstance(tup, tuple):
        tup = tup,
    if len(tup) > length:
        return None
    elif len(tup) == length:
        return tup
    else:
        return tup + (pad_val,) * (length - len(tup))


def process_events(my_gene, event, ioe_writer, gtf_writer, edge_len, th):
    """
    Generates specified event occurrences in gene and writes the GTF/IOE output
    """
    gene_event = event(my_gene, th)
    for event_repr, etype in gene_event.export_events_ioe():
        ioe_writer.write(event_repr, etype)
    for gtf_line, etype in gene_event.export_events_gtf(edge_len):
        gtf_writer.write(gtf_line, etype)


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


@staticmethod
def tag_end(tag):
    """Build closed tag info.

        :param tag: tag name
        :rtype: str
        """
    return '</{}>'.format(tag)


@classmethod
def make_empty_like(cls, sparsemap, nside_coverage=None, nside_sparse=None,
    dtype=None, primary=None, sentinel=None, wide_mask_maxbits=None,
    metadata=None):
    """
        Make an empty map with the same parameters as an existing map.

        Parameters
        ----------
        sparsemap : `HealSparseMap`
           Sparse map to use as basis for new empty map.
        nside_coverage : `int`, optional
           Coverage nside, default to sparsemap.nside_coverage
        nside_sparse : `int`, optional
           Sparse map nside, default to sparsemap.nside_sparse
        dtype : `str` or `list` or `np.dtype`, optional
           Datatype, any format accepted by numpy.  Default is sparsemap.dtype
        primary : `str`, optional
           Primary key for recarray.  Default is sparsemap.primary
        sentinel : `int` or `float`, optional
           Sentinel value.  Default is sparsemap._sentinel
        wide_mask_maxbits : `int`, optional
           Create a "wide bit mask" map, with this many bits.
        metadata : `dict`-like, optional
           Map metadata that can be stored in FITS header format.

        Returns
        -------
        healSparseMap : `HealSparseMap`
           HealSparseMap filled with sentinel values.
        """
    if nside_coverage is None:
        nside_coverage = sparsemap.nside_coverage
    if nside_sparse is None:
        nside_sparse = sparsemap.nside_sparse
    if dtype is None:
        dtype = sparsemap.dtype
    if primary is None:
        primary = sparsemap.primary
    if sentinel is None:
        sentinel = sparsemap._sentinel
    if wide_mask_maxbits is None:
        if sparsemap._is_wide_mask:
            wide_mask_maxbits = sparsemap._wide_mask_maxbits
    if metadata is None:
        metadata = sparsemap._metadata
    return cls.make_empty(nside_coverage, nside_sparse, dtype, primary=
        primary, sentinel=sentinel, wide_mask_maxbits=wide_mask_maxbits,
        metadata=metadata)


def proc_shortname(this, value):
    """Get the shortname of the process,
    if tag starts with "notag", don't include it"""
    if not this.tag or this.tag == 'notag':
        return this.id
    if this.tag[:6] == 'notag@':
        return '{}@{}'.format(this.id, this.tag[6:])
    return this.name


@staticmethod
def _dbc_add_backpointer_NL(sa, tobj, backpointer):
    """Add a single backpointer to a target obj"""
    sa.toc.add_backpointer_ins_NL(tobj, backpointer)


@classmethod
def get_config_opts(cls):
    """Override base class config options as do not use datasource """
    return []


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

        :param MemberSpaceLimitsAddExceptionType val:
        :rtype: EventType
        """
    return cls('member_space_limits_add_exception', val)


def formula_2017_01_01(foyer_fiscal, period, parameters):
    """
        Note : à partir des revenus 2017, la case 2TT représente les intérêts des prêts participatifs nets des pertes à imputer,
        contrairement à avant où il s'agissait des intérêts avant déduction des pertes. Donc, à partir de 2017, on a ici,
        par contrainte de la structure des cases de la déclaration des revenus, le montant net au lieu du montant brut.
        """
    year = period.this_year
    f2dc = foyer_fiscal('f2dc', year)
    f2ch = foyer_fiscal('f2ch', year)
    f2ts = foyer_fiscal('f2ts', year)
    f2go = foyer_fiscal('f2go', year)
    f2tr = foyer_fiscal('f2tr', year)
    f2fu = foyer_fiscal('f2fu', year)
    f2tt = foyer_fiscal('f2tt', year)
    majoration_revenus_reputes_distribues = parameters(period
        ).impot_revenu.rvcm.majoration_revenus_reputes_distribues
    return (f2dc + f2ch + f2ts + f2go *
        majoration_revenus_reputes_distribues + f2tr + f2fu + f2tt) / 12


def get_parent_id(org_client, account_id):
    """
    Query deployed AWS organanization for 'account_id. Return the 'Id' of
    the parent OrganizationalUnit or 'None'.
    """
    parents = org_client.list_parents(ChildId=account_id)['Parents']
    try:
        len(parents) == 1
        return parents[0]['Id']
    except:
        raise RuntimeError(
            "API Error: account '%s' has more than one parent: " % (
            account_id, parents))


@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['configSourceType']
    if type == 'ZIP_UPLOAD':
        return 'UpdateZipUploadConfigSourceDetails'
    else:
        return 'UpdateConfigSourceDetails'


def check_conditions(line, category, method, thresh=0.3):
    """Check conditions of our or m3d txt file"""
    check = False
    assert category in ['pedestrian', 'cyclist', 'all']
    if method == 'gt':
        if category == 'all':
            categories_gt = ['Pedestrian', 'Person_sitting', 'Cyclist']
        else:
            categories_gt = [category.upper()[0] + category[1:]]
        if line.split()[0] in categories_gt:
            check = True
    elif method in ('m3d', '3dop'):
        conf = float(line[15])
        if line[0] == category and conf >= thresh:
            check = True
    elif method == 'monodepth':
        check = True
    else:
        zz = float(line[13])
        conf = float(line[15])
        if conf >= thresh and 0.5 < zz < 70:
            check = True
    return check


def preview_toggle():
    """Toggle preview display for selected nodes

    """
    pass


def buildOpenPGPFingerprintHostname(uid):
    """
    Build the hostname where the OpenPGP fingerprint should be stored in a text
    record if it has been published. Don't forget, it's always possible that
    the name will not exist.
    """
    parts = uid.split('@', 1)
    hostname = parts[0]
    hostname += '._pka.'
    hostname += parts[1]
    return hostname


def route_to_alt_domain(request, url):
    """Route URL to a different subdomain.

    Used to rewrite URLs to point to websocket serving domain.
    """
    alternative_domain = request.registry.settings.get(
        'pyramid_notebook.alternative_domain', '').strip()
    if alternative_domain:
        url = url.replace(request.host_url, alternative_domain)
    return url


def query(**kw):
    """Query Soup for Records.

        @param kw: Keyword arguments defining the query.
        @return: list of records.
        """


@staticmethod
def _load_relationships(instance):
    """
        Helper method used to overcome a problem where the relationships that rely on joins aren't
        being loaded automatically.
        """
    for rel in instance.__mapper__.relationships:
        getattr(instance, rel.key)


def glGetAttachedShaders(program: int, maxCount: int, count: int, shaders: int
    ):
    """Returns the handles of the shader objects attached to a program object.

    :param program: Specifies the program object to be queried.
    :type program: int
    :param maxCount: Specifies the size of the array for storing the returned object names.
    :type maxCount: int
    :param count: Returns the number of names actually returned in objects.
    :type count: int
    :param shaders: Specifies an array that is used to return the names of attached shader objects.
    :type shaders: int
    """
    pass


def __split_complex_exon(transcript, exon, texon, sentinel, boundary,
    invert=False):
    """
    Private method used to split an exon when it is only partially coding,
    :param exon: Exon to be analysed
    :param texon: Transcriptomic coordinates of the exon
    :param sentinel: tuple of boolean flags, it indicates whether there are transcripts on the left
    (first member) and/or on the right (second member) of the current instance.

    :param boundary: Transcriptomic coordinates of the ORF boundary.
    :return:
    """
    left, right = sentinel
    to_discard = None
    new_exon = list(exon)
    if texon[1] == boundary[0]:
        if left is False:
            transcript.logger.debug("Appending mixed UTR/CDS 5' exon %s", exon)
        elif transcript.strand == '+':
            to_discard = exon[0], exon[1] - 1
            new_exon = exon[1] - 1, exon[1]
            texon = texon[1] - 1, texon[1]
            transcript.logger.debug('Appending monobase CDS exon %s (Texon %s)'
                , new_exon, texon)
        else:
            to_discard = exon[0] + 1, exon[1]
            new_exon = exon[0], exon[0] + 1
            texon = texon[1] - 1, texon[1]
            transcript.logger.debug('Appending monobase CDS exon %s (Texon %s)'
                , new_exon, texon)
    elif texon[0] == boundary[1]:
        if right is False:
            transcript.logger.debug('Appending mixed UTR/CDS right exon %s',
                exon)
        elif transcript.strand == '+':
            to_discard = exon[0] + 1, exon[1]
            new_exon = exon[0], exon[0] + 1
            texon = texon[0], texon[0] + 1
            transcript.logger.debug('Appending monobase CDS exon %s (Texon %s)'
                , new_exon, texon)
        else:
            to_discard = exon[0], exon[1] - 1
            new_exon = exon[1] - 1, exon[1]
            texon = texon[0], texon[0] + 1
            transcript.logger.debug('Appending monobase CDS exon %s (Texon %s)'
                , new_exon, texon)
    elif texon[0] <= boundary[0] <= boundary[1] <= texon[1]:
        transcript.logger.debug('Exon %s, case 3.1', exon)
        if invert is True:
            if left is True:
                new_exon[1] = exon[0] + (texon[1] - boundary[0])
                transcript.logger.debug(
                    'Case 3.1: Negative strand, another transcript on the left, new exon: %d, %d'
                    , new_exon[0], new_exon[1])
            if right is True:
                new_exon[0] = exon[1] - (boundary[1] - texon[0])
                transcript.logger.debug(
                    'Case 3.1: Negative strand, another transcript on the right, new exon: %d, %d'
                    , new_exon[0], new_exon[1])
        else:
            if left is True:
                new_exon[0] = exon[1] - (texon[1] - boundary[0])
                transcript.logger.debug(
                    'Case 3.1: Positive strand, another transcript on the left, new exon: %d, %d'
                    , new_exon[0], new_exon[1])
            if right is True:
                new_exon[1] = exon[0] + (boundary[1] - texon[0])
                transcript.logger.debug(
                    'Case 3.1: Positive strand, another transcript on the right, new exon: %d, %d'
                    , new_exon[0], new_exon[1])
        transcript.logger.debug('[Monoexonic] Tstart shifted for %s, %d to %d',
            transcript.id, texon[0], boundary[0])
        transcript.logger.debug('[Monoexonic] GStart shifted for %s, %d to %d',
            transcript.id, exon[0], new_exon[1])
        transcript.logger.debug('[Monoexonic] Tend shifted for %s, %d to %d',
            transcript.id, texon[1], boundary[1])
        transcript.logger.debug('[Monoexonic] Gend shifted for %s, %d to %d',
            transcript.id, exon[1], new_exon[1])
        if left is True:
            texon[0] = boundary[0]
        if right is True:
            texon[1] = boundary[1]
    elif texon[0] <= boundary[0] <= texon[1] <= boundary[1]:
        if left is True:
            if transcript.strand == '-':
                new_exon[1] = exon[0] + (texon[1] - boundary[0])
            else:
                new_exon[0] = exon[1] - (texon[1] - boundary[0])
            transcript.logger.debug('Tstart shifted for %s, %d to %d',
                transcript.id, texon[0], boundary[0])
            transcript.logger.debug('GStart shifted for %s, %d to %d',
                transcript.id, exon[0], new_exon[1])
            texon[0] = boundary[0]
    elif texon[1] >= boundary[1] >= texon[0] >= boundary[0]:
        if right is True:
            if transcript.strand == '-':
                new_exon[0] = exon[1] - (boundary[1] - texon[0])
            else:
                new_exon[1] = exon[0] + (boundary[1] - texon[0])
            transcript.logger.debug('Tend shifted for %s, %d to %d',
                transcript.id, texon[1], boundary[1])
            transcript.logger.debug('Gend shifted for %s, %d to %d',
                transcript.id, exon[1], new_exon[1])
            texon[1] = boundary[1]
        else:
            transcript.logger.debug('New exon: %s', new_exon)
            transcript.logger.debug('New texon: %s', texon)
    new_exon = tuple([new_exon[0], new_exon[1]])
    return new_exon, texon, to_discard


def add_link_type_vlan(enode, portlbl, name, vlan_id, shell=None):
    """
    Add a new virtual link with the type set to VLAN.

    Creates a new vlan device {name} on device {port}.
    Will raise an exception if value is already assigned.

    :param enode: Engine node to communicate with.
    :type enode: topology.platforms.base.BaseNode
    :param str portlbl: Port label to configure. Port label will be mapped
     automatically.
    :param str name: specifies the name of the new virtual device.
    :param str vlan_id: specifies the VLAN identifier.
    :param str shell: Shell name to execute commands. If ``None``, use the
     Engine Node default shell.
    """
    assert name
    if name in enode.ports:
        raise ValueError('Port {name} already exists'.format(name=name))
    assert portlbl
    assert vlan_id
    port = enode.ports[portlbl]
    cmd = 'ip link add link {dev} name {name} type vlan id {vlan_id}'.format(
        dev=port, name=name, vlan_id=vlan_id)
    response = enode(cmd, shell=shell)
    assert not response, 'Cannot add virtual link {name}'.format(name=name)
    enode.ports[name] = name


def seeIP():
    """ Get current IP value

        Returns:
        ----------
        result: string
            current IP value
    """
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    cw_ip = s.getsockname()[0]
    s.close()
    result = {'ip': str(cw_ip)}
    return result


def poll_for_jobs(actionTypeId=None, maxBatchSize=None, queryParam=None):
    """
    Returns information about any jobs for AWS CodePipeline to act upon.
    See also: AWS API Documentation

    :example: response = client.poll_for_jobs(
        actionTypeId={
            'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
            'owner': 'AWS'|'ThirdParty'|'Custom',
            'provider': 'string',
            'version': 'string'
        },
        maxBatchSize=123,
        queryParam={
            'string': 'string'
        }
    )

    :type actionTypeId: dict
    :param actionTypeId: [REQUIRED]
            Represents information about an action type.
            category (string) -- [REQUIRED]A category defines what kind of action can be taken in the stage, and constrains the provider type for the action. Valid categories are limited to one of the values below.
            owner (string) -- [REQUIRED]The creator of the action being called.
            provider (string) -- [REQUIRED]The provider of the service being called by the action. Valid providers are determined by the action category. For example, an action in the Deploy category type might have a provider of AWS CodeDeploy, which would be specified as CodeDeploy.
            version (string) -- [REQUIRED]A string that identifies the action type.

    :type maxBatchSize: integer
    :param maxBatchSize: The maximum number of jobs to return in a poll for jobs call.

    :type queryParam: dict
    :param queryParam: A map of property names and values. For an action type with no queryable properties, this value must be null or an empty map. For an action type with a queryable property, you must supply that property as a key in the map. Only jobs whose action configuration matches the mapped value will be returned.
            (string) --
            (string) --

    :rtype: dict
    :return: {
        'jobs': [
            {
                'id': 'string',
                'data': {
                    'actionTypeId': {
                        'category': 'Source'|'Build'|'Deploy'|'Test'|'Invoke'|'Approval',
                        'owner': 'AWS'|'ThirdParty'|'Custom',
                        'provider': 'string',
                        'version': 'string'
                    },
                    'actionConfiguration': {
                        'configuration': {
                            'string': 'string'
                        }
                    },
                    'pipelineContext': {
                        'pipelineName': 'string',
                        'stage': {
                            'name': 'string'
                        },
                        'action': {
                            'name': 'string'
                        }
                    },
                    'inputArtifacts': [
                        {
                            'name': 'string',
                            'revision': 'string',
                            'location': {
                                'type': 'S3',
                                's3Location': {
                                    'bucketName': 'string',
                                    'objectKey': 'string'
                                }
                            }
                        },
                    ],
                    'outputArtifacts': [
                        {
                            'name': 'string',
                            'revision': 'string',
                            'location': {
                                'type': 'S3',
                                's3Location': {
                                    'bucketName': 'string',
                                    'objectKey': 'string'
                                }
                            }
                        },
                    ],
                    'artifactCredentials': {
                        'accessKeyId': 'string',
                        'secretAccessKey': 'string',
                        'sessionToken': 'string'
                    },
                    'continuationToken': 'string',
                    'encryptionKey': {
                        'id': 'string',
                        'type': 'KMS'
                    }
                },
                'nonce': 'string',
                'accountId': 'string'
            },
        ]
    }

    :returns:
    (string) --
    (string) --

    """
    pass


@staticmethod
def before_frontend_construction(kwargs):
    """Plugin hook to manipulate the Frontend object constructor arguments. If
        a value is returned here it will replace the keyword arguments
        dictionary passed to the constructor."""


def get_projects(session):
    """
    Gets all Projects visible to the authenticated user
    :param session: ovation.session.Session
    :return: list of Projects
    """
    return session.get(session.path(resource='projects'))


def isatty(fh):
    """Return true if the process has a controlling terminal."""
    try:
        return fh.isatty()
    except AttributeError:
        pass


def parse_int_list(string):
    """
    Parses a string of numbers and ranges into a list of integers. Ranges
    are separated by dashes and inclusive of both the start and end number.

    Example:
        parse_int_list("8 9 10,11-13") == [8,9,10,11,12,13]
    """
    integers = []
    for comma_part in string.split(','):
        for substring in comma_part.split(' '):
            if len(substring) == 0:
                continue
            if '-' in substring:
                left, right = substring.split('-')
                left_val = int(left.strip())
                right_val = int(right.strip())
                integers.extend(range(left_val, right_val + 1))
            else:
                integers.append(int(substring.strip()))
    return integers


def _get_immediate_cls_attr(cls, attrname, strict=False):
    """return an attribute of the class that is either present directly
    on the class, e.g. not on a superclass, or is from a superclass but
    this superclass is a mixin, that is, not a descendant of
    the declarative base.

    This is used to detect attributes that indicate something about
    a mapped class independently from any mapped classes that it may
    inherit from.

    """
    if not issubclass(cls, object):
        return None
    for base in cls.__mro__:
        _is_declarative_inherits = hasattr(base, '_decl_class_registry')
        if attrname in base.__dict__ and (base is cls or (base in cls.
            __bases__ if strict else True) and not _is_declarative_inherits):
            return getattr(base, attrname)
    else:
        return None


def parse_big_number(num):
    """Parse large numbers into human readable format (e.g., 1K, 1M, 1B).

    :param num: int or float of number to parse
    :return: str of parsed number
    """
    if num < 1000.0:
        num = f'{num}'
    elif num < 1000000.0:
        num = f'{num / 1000.0:.0f}K'
    elif num < 1000000000.0:
        num = f'{num / 1000000.0:.0f}M'
    else:
        num = f'{num / 1000000000.0:.0f}B'
    return num


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 is_valid_structure(ext):
    """ Checks if structure format is compatible with GROMACS """
    formats = ['tpr', 'gro', 'g96', 'pdb', 'brk', 'ent']
    return ext in formats


def row_number(index):
    """ get row number of the 0x10 byte row containing the given index """
    return index // 16


def send(message):
    """Send a message using AMQP."""


def normalize_auth_header(header):
    """
    Normalize a header name into WSGI-compatible format.

    >>> normalize_auth_header('X-NSoT-Email')
    'HTTP_X_NSOT_EMAIL'

    :param header:
        Header name
    """
    return 'HTTP_' + header.upper().replace('-', '_')


@classmethod
def info(cls, id):
    """ Display information about an ssh key. """
    return cls.call('hosting.ssh.info', cls.usable_id(id))


def rate_limit(config, args):
    """
  Current rate limit information.
  """
    yield config.github.rate_limit()


def gcdex_diophantine(a, b, c):
    """
    Extended Euclidean Algorithm, Diophantine version.

    Given a, b in K[x] and c in (a, b), the ideal generated by a and b,
    return (s, t) such that s*a + t*b == c and either s == 0 or s.degree()
    < b.degree().

    """
    s, g = a.half_gcdex(b)
    q = c.exquo(g)
    s = q * s
    if not s.is_zero and s.degree() >= b.degree():
        q, s = s.div(b)
    t = (c - s * a).exquo(b)
    return s, t


def mdl_eigen(s, N):
    """MDL order-selection using eigen values

    :param s: a list of `p` sorted eigen values
    :param N: the size of the input data. To be defined precisely.

    :return:
        * an array containing the AIC values

    .. math:: MDL(k) = (n-k)N \\ln \\frac{g(k)}{a(k)} + 0.5k(2n-k) log(N)

    .. seealso:: :func:`aic_eigen` for details

    :References:
        * [Marple]_ Chap 13,
        * [Wax]_
    """
    import numpy as np
    kmdl = []
    n = len(s)
    for k in range(0, n - 1):
        ak = 1.0 / (n - k) * np.sum(s[k + 1:])
        gk = np.prod(s[k + 1:] ** (1.0 / (n - k)))
        kmdl.append(-(n - k) * N * np.log(gk / ak) + 0.5 * k * (2.0 * n - k
            ) * np.log(N))
    return kmdl


def vert_select_ungrouped(extend: bool=False):
    """Select vertices without a group

    :param extend: Extend, Extend the selection
    :type extend: bool
    """
    pass