def __def_function__():
    """To get __globals__ for this scope."""
    pass


def freestyle_module_remove():
    """Remove the style module from the stack

    """
    pass


@classmethod
def from_existing(cls, klass):
    """Build a new `_CivisBackend` from an existing one."""
    return cls(setup_cmd=klass.setup_cmd, from_template_id=klass.
        from_template_id, max_submit_retries=klass.max_submit_retries,
        client=klass.client, remote_backend=klass.remote_backend, **klass.
        executor_kwargs)


def is_good_response(response):
    """Helper method to check if boto3 call was a success."""
    code = response['ResponseMetadata']['HTTPStatusCode']
    return 200 <= code < 300


def en(value):
    """Returns an RDF literal from the en language for the given value."""
    from pymantic.primitives import Literal
    return Literal(value, language='en')


def create_firewall(interface: str, interface_data: dict, firewall_type:
    str, naughty_count: int):
    """
            Firewall factory. Will create a firewall based on the type of firewall that is passed in.
            Currently, this function only supports linux based operating systems
        """
    if firewall_type == 'linux':
        from deepdos.iptables import IPtable, IPTCError
        try:
            return IPtable(interface, interface_data, naughty_count)
        except IPTCError:
            print('Need to be root in order to access firewall')
            return None
    raise ValueError(
        'linux is the only supported operating system for firewall mode. You entered: {firewall_type}'
        )


@staticmethod
def get_short_arguments():
    """
        Return dictionary mapping single-letter short arguments to field names.

        Short arguments can be specified by subclasses statically by defining
        :attr:`short_arguments` or dynamically by defining this method. When
        both are defined, the dictionaries are merged, with
        :meth:`get_short_arguments` overriding :attr:`short_arguments` for
        any conflicts.

        Dictionaries look like this::

            class MyForm(Form):
                short_arguments = dict(c='comment')

                @staticmethod
                def get_short_arguments():
                    # Just for demonstration. In real code this would go in
                    # the short_arguments attribute above.
                    return dict(n='name')

                comment = StringField()
                name = StringField()

        The end user can now specify values for ``comment`` and ``name`` using
        ``-c 'my comment'`` and ``-n 'My Name'``, respectively.
        """


def randomize_transform(random_seed: int=0, use_delta: bool=False, use_loc:
    bool=True, loc: float=(0.0, 0.0, 0.0), use_rot: bool=True, rot: float=(
    0.0, 0.0, 0.0), use_scale: bool=True, scale_even: bool=False, scale:
    float=(1.0, 1.0, 1.0)):
    """Randomize objects loc/rot/scale

    :param random_seed: Random Seed, Seed value for the random generator
    :type random_seed: int
    :param use_delta: Transform Delta, Randomize delta transform values instead of regular transform
    :type use_delta: bool
    :param use_loc: Randomize Location, Randomize the location values
    :type use_loc: bool
    :param loc: Location, Maximum distance the objects can spread over each axis
    :type loc: float
    :param use_rot: Randomize Rotation, Randomize the rotation values
    :type use_rot: bool
    :param rot: Rotation, Maximum rotation over each axis
    :type rot: float
    :param use_scale: Randomize Scale, Randomize the scale values
    :type use_scale: bool
    :param scale_even: Scale Even, Use the same scale value for all axis
    :type scale_even: bool
    :param scale: Scale, Maximum scale randomization over each axis
    :type scale: float
    """
    pass


def count():
    """Return the number of spiders in the queue.

        This method can return a deferred. """


def parent_in_tree(parent_label, tree_hash):
    """ Return True if the parent of node_label is in the tree """
    return parent_label in tree_hash


def default_clutch_k_factor_curve():
    """
    Returns a default k factor curve for a generic clutch.

    :return:
        k factor curve.
    :rtype: callable
    """
    from ..defaults import dfl
    par = dfl.functions.default_clutch_k_factor_curve
    a = par.STAND_STILL_TORQUE_RATIO, par.LOCKUP_SPEED_RATIO
    from . import define_k_factor_curve
    return define_k_factor_curve(*a)


def sample():
    """Use mouse to sample color in current frame

    """
    pass


def _win_path_to_bytes(path):
    """Encode Windows paths to bytes. Only used on Python 2.

    Motivation is to be consistent with other operating systems where paths
    are also returned as bytes. This avoids problems mixing bytes and Unicode
    elsewhere in the codebase. For more details and discussion see
    <https://github.com/pypa/pip/issues/3463>.

    If encoding using ASCII and MBCS fails, return the original Unicode path.
    """
    for encoding in ('ASCII', 'MBCS'):
        try:
            return path.encode(encoding)
        except (UnicodeEncodeError, LookupError):
            pass
    return path


def equal():
    """Returns a function that computes whether two temporal intervals are
    strictly equal.

    The output function expects two temporal intervals (dicts with keys 't1'
    and 't2' for the start and end times, respectively). It returns ``True`` if
    the two intervals have equal start times and equal end times.

    Returns:
        An output function that takes two temporal intervals and returns
        ``True`` if the two intervals have equal start times and equal end
        times.
    """
    return lambda intrvl1, intrvl2: intrvl1['t1'] == intrvl2['t1'] and intrvl1[
        't2'] == intrvl2['t2']


def nedc_velocities_domain(cycle_type, *args):
    """
    Returns if the cycle is NEDC.

    :param cycle_type:
        Cycle type (WLTP or NEDC).
    :type cycle_type: str

    :return:
        If the cycle is NEDC.
    :rtype: bool
    """
    return cycle_type == 'NEDC'


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

        :param FileRequestChangeDetails val:
        :rtype: EventDetails
        """
    return cls('file_request_change_details', val)


@staticmethod
def has_battery():
    """Return whether the device has a battery."""
    return False


def clean_kwargs(request, data):
    """
    Очищает данные запроса от зарезервированных ключей.
    """
    kwargs = {}
    for key in data.keys():
        if '[]' in key and (data is request.POST or data is request.GET):
            kwargs[key.replace('[]', '')] = data.getlist(key)
        elif key not in ('method', 'username', 'password', 'language'):
            kwargs[key] = data.get(key)
    return kwargs


def rwmeth2filetype(rw_meth):
    """Get the alternate properties that corresponding to the old
    read_meth/write_meth keywords.

    Args:
        rw_meth (str): Read/write method name.

    Returns:
        dict: Property values equivalent to provided read/write method.

    """
    out = {}
    if rw_meth == 'all':
        out['filetype'] = 'binary'
    elif rw_meth == 'line':
        out['filetype'] = 'ascii'
    elif rw_meth == 'table_array':
        out['filetype'] = 'table'
        out['as_array'] = True
    else:
        out['filetype'] = rw_meth
    return out


def calc_storage(area, infiltration, storage, flowrate, dt=86400):
    """
    Explicitly solves for the future storage in a layer for each subbasin by
    rearranging the equation:

    dS/dt = I - (Q/area)

    into the following equation:

    S_t1 = (I - Q/area) * dt + S_t

    Where S_t1 is Storage @ time=t+dt, S_t is Storage @ time=t,
    dt is the time step in seconds, Q is flowrate, I is infiltation, and area
    is the subbasin area.

    Args:
        area:
        infiltration: pandas.Series of infiltration at the current timestep
        storage: pandas.Series for storage at the current timestep
        flowrate: pandas.Series for flowrate at the current timestep
        dt: timestep in seconds

    Returns:
        future_storage: pandas.Series of the storage for the next timestep
    """
    future_storage = (infiltration - flowrate / area) * dt + storage
    return future_storage


def make_edge_id(source_node_index, first_char):
    """Returns a string made from given params.
    """
    return '{}::{}'.format(source_node_index, first_char)


def make_modbusmap_channel(i, chan, device_type_name):
    """Make a channel object for a row in the CSV."""
    json_obj = {'ah': '', 'bytary': None, 'al': '', 'vn': chan['subTitle'],
        'ct': 'number', 'le': '16', 'grp': str(chan[
        'guaranteedReportPeriod']), 'la': None, 'chn': chan['name'], 'un':
        '1', 'dn': device_type_name, 'vm': None, 'lrt': '0', 'da': '300',
        'a': chan['helpExplanation'], 'c': str(chan['change']), 'misc_u':
        str(chan['units']), 'f': '1', 'mrt': str(chan['minReportTime']),
        'm': 'none', 'm1ch': '2-{}'.format(i), 'mv': '0', 's': 'On', 'r':
        '{}-{}'.format(chan['min'], chan['max']), 't': 'int'}
    return json_obj


def duplicates_make_real(use_base_parent: bool=False, use_hierarchy: bool=False
    ):
    """Make dupli objects attached to this object real

    :param use_base_parent: Parent, Parent newly created objects to the original duplicator
    :type use_base_parent: bool
    :param use_hierarchy: Keep Hierarchy, Maintain parent child relationships
    :type use_hierarchy: bool
    """
    pass


def viz_td(body, port=None, align='CENTER'):
    """Create HTML td for graphviz"""
    port_text = '' if port is None else 'PORT="{}"'.format(port)
    return '<TD {port_text} ALIGN="{align}">{body}</TD>'.format(**locals())


def get_settings():
    """
        Serialize the internal settings for this view

        :returns: the settings for this view
        :rtype: a dictionary
        """


def fix_sec_nseg(secs, dL):
    """ Set nseg of sections based on dL param: section.nseg = 1 + 2 * int(section.L / (2*dL))
    :param secs: netpyne dictionary with all sections
    :param dL: dL from config file
    """
    for secName in secs:
        secs[secName]['geom']['nseg'] = 1 + 2 * int(secs[secName]['geom'][
            'L'] / (2 * dL))


def select_option(prompt, valid_response_set):
    """Select an option from a set of options.

    :param prompt: Message to display before displaying option.
    :type prompt: str
    :param valid_response_set: Set of valid options to choose.
    :type valid_response_set: set
    :returns: option
    :rtype: str, int
    """
    response_valid = False
    while response_valid == False:
        response = input(prompt)
        if response.isdigit():
            response = int(response)
        else:
            response = response.lower()
        if response in valid_response_set:
            response_valid = True
            if response == 'y':
                response = 'yes'
            elif response == 'n':
                response = 'no'
        else:
            print('Invalid response.')
    return response


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 from_bytes(cls, bs):
    """ Create a new `TagSet` from the bytes `bs`,
        a UTF-8 encoding of a `TagSet` line.
    """
    line = bs.decode(errors='replace')
    return cls.from_line(line)


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 norm_01(x):
    """
    功能：将舵机参数归一化到[0,1]
    输入:待归一化舞蹈动作矩阵。数据类型为numpy.array
    返回：归一化后的舞蹈动作矩阵
    """
    out = x / 180
    return out.clip(0, 1)


def uptime(sender, process, data):
    """The time in seconds Supervisor reports the process has been running

    - ``process:{name}:uptime``
    """
    sender.riemann.event(service='process:{name}:uptime'.format(**data),
        metric_f=data['stop' if process is None else 'now'] - data['start'])


def check_tc_data(*args):
    """Access stored Thermocouple data from the sensor limits and collected data to index and build an integer numpy array for sensor values that have exceeded the set bounds.

    Parameters
    ----------
    tc_limits : int numpy array
        Values for thermocouple limits.
    tc_data : float numpy array
        Collected sensor data used to.

    Returns
    -------
    tc_input_data : numpy array
        numpy array of sensed thermocouple values data.
    """
    limits = args[0].tc_limits
    tc = []
    for i in range(len(limits)):
        x = args[1][i] - limits[i]
        if x >= 0:
            tc.append(args[1][i])
        else:
            tc.append(0)
    return tc


def create_permission(namespace: str=None, action: str=None):
    """

    DynamoDB Integration:
    ---

    required_fields = [namespace, action]

    if not all(required_fields):
        raise KeyError("NAMESPACE & ACTION fields are required.")

    try:
        permission_table.put_item(Item={
            "namespace": namespace,
            "action": action
        })

        return permission_table.get_item(Key={'namespace':{'S': namespace},
                                              'action':{'S': action}})
    except Exception as e:
        print(e)

        raise KeyError
    """
    required_fields = [namespace, action]
    if not all(required_fields):
        raise KeyError('NAMESPACE & ACTION fields are required.')
    return {'id': 'new-object-id', 'namespace': namespace, 'action': action,
        'permission': f'{namespace}:{action}'}


def create_avishan_config_file(app_name: str=None):
    """
    MONITORED_APPS_NAMES = []
    NOT_MONITORED_STARTS [
        '/admin', '/static', '/media', '/favicon.ico'
    ]
    JWT_KEY = "" or none if not available
    """
    if app_name:
        f = open(app_name + '/avishan_config.py', 'w+')
    else:
        f = open('avishan_config.py', 'w+')
    f.writelines(('def check():\n', '    pass\n\n\n', 'class AvishanConfig:\n')
        )
    if not app_name:
        f.writelines(['    MONITORED_APPS_NAMES = []\n',
            """    NOT_MONITORED_STARTS = ['/admin', '/static', '/favicon.ico']
"""
            , "    JWT_KEY = 'CHANGE_THIS_KEY'\n",
            '    USE_JALALI_DATETIME = True\n'])
    else:
        f.write('    pass\n')
    f.close()


@staticmethod
def fromQml(path: str):
    """
        Reads a ClassificationScheme from a QML file.
        :param path: str, path to QML file
        :return: ClassificationScheme
        """
    raise NotImplementedError()


def spritecollideany(sprite, group, collided=None):
    """finds any sprites in a group that collide with the given sprite

    pygame.sprite.spritecollideany(sprite, group): return sprite

    Given a sprite and a group of sprites, this will return return any single
    sprite that collides with with the given sprite. If there are no
    collisions, then this returns None.

    If you don't need all the features of the spritecollide function, this
    function will be a bit quicker.

    Collided is a callback function used to calculate if two sprites are
    colliding. It should take two sprites as values and return a bool value
    indicating if they are colliding. If collided is not passed, then all
    sprites must have a "rect" value, which is a rectangle of the sprite area,
    which will be used to calculate the collision.

    """
    if collided:
        for s in group:
            if collided(sprite, s):
                return s
    else:
        spritecollide = sprite.rect.colliderect
        for s in group:
            if spritecollide(s.rect):
                return s
    return None


def write_poscar(ofile, c, fract):
    """ Write POSCAR file for VASP
    NOTE: the order of atoms changes because of the sorting!
    """
    print('Written with manage_crystal', file=ofile)
    print('1', file=ofile)
    for k in range(3):
        print('%11.8f %11.8f %11.8f' % (c.matrix[k][0], c.matrix[k][1], c.
            matrix[k][2]), file=ofile)
    for e in c.element:
        print('{} '.format(e), end='', file=ofile)
    print('', file=ofile)
    for e in c.element:
        print('{} '.format(c.element_count[e]), end='', file=ofile)
    print('', file=ofile)
    if fract:
        print('direct', file=ofile)
    else:
        print('cartesian', file=ofile)
    for e in c.element:
        for i, a in enumerate(c.atom_element):
            if e == a:
                if fract:
                    print('%9.5f %9.5f %9.5f' % (c.atom_fract[i][0], c.
                        atom_fract[i][1], c.atom_fract[i][2]), file=ofile)
                else:
                    print('%9.5f %9.5f %9.5f' % (c.atom_fract[i][0], c.
                        atom_fract[i][1], c.atom_fract[i][2]), file=ofile)
    return


def _mean(data):
    """Return the sample arithmetic mean of data."""
    n = len(data)
    if n < 1:
        raise ValueError('mean requires at least one data point')
    return sum(data) / n


def convert_level(level, table):
    """ Convert logging levels using lookup table """
    try:
        return table[level][0]
    except KeyError:
        keys = table.keys()
        keys.sort()
        for key in keys:
            if level < key:
                return table[key][0]
        return table[keys[-1]][0]


def device_mapping(cuda_device: int) ->str:
    """
    In order to `torch.load()` a GPU-trained model onto a CPU (or specific GPU),
    you have to supply a `map_location` function. Call this with
    the desired `cuda_device` to get the function that `torch.load()` needs.
    """
    if cuda_device < 0:
        return 'cpu'
    return f'cuda:{cuda_device}'


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


@classmethod
def type(cls, attr):
    """Return the data type for an attribute.

        :rtype: str

        """
    return getattr(cls, '_' + attr)


def arange(start, stop):
    """Create a 1D range int64 tensor.

    Parameters
    ----------
    start : int
        The range start.
    stop : int
        The range stop.

    Returns
    -------
    Tensor
        The result tensor.
    """
    pass


def authorRank(authors, lastname, forename, initials):
    """ get the position of a person in an author list, first do first name
        matching, then in a second loop try matching of initials.
    """
    i = 0
    retlist = []
    for a in authors:
        i += 1
        if 'LastName' in a and lastname:
            if 'ForeName' in a:
                if a['LastName'].lower() == lastname.lower() and (forename.
                    lower() in a['ForeName'].lower() or a['ForeName'].lower
                    () in forename.lower()):
                    retlist = [i, a['LastName'] + ' ' + a['ForeName']]
    if len(retlist) > 0:
        return retlist
    i = 0
    for a in authors:
        i += 1
        if 'LastName' in a:
            if 'Initials' in a:
                if a['LastName'].lower() == lastname.lower(
                    ) and initials.lower() in a['Initials'].lower():
                    retlist = [i, a['LastName'] + ' ' + a['Initials']]
    if len(retlist) > 0:
        return retlist
    else:
        return 0, ''


def clear_capacities(topology):
    """
    Remove all capacities from the topology.

    Parameters
    ----------
    topology : Topology
    """
    topology.graph.pop('capacity_unit', None)
    for u, v in topology.edges():
        topology.adj[u][v].pop('capacity', None)


@classmethod
def is_capable(cls, in_type, out_type):
    """
        @param::in_type: the type of input dataframe in string
        @param::out_type: the type of output dataframe in string
        return boolean value indicates whether or not the conversion is supported
        """
    raise NotImplementedError(
        '> Dataframe.JointerBase is_capable(): method is not implemented. ')


def new():
    """Add a new screen

    """
    pass


def hello() ->str:
    """
    Simple Hello World.

    >>> hello()
    'Hello World'
    """
    return 'Hello World'


def sequence(line):
    """Determines if line is a sequence line
    """
    answer = False
    if not len(line) == 1 and not line.startswith('#') and not line.startswith(
        '/') and not line.startswith('Using'):
        answer = True
    return answer


@staticmethod
def default():
    """ return default options, available options:
        - max_name_length: maximum length of name for additionalProperties
        - max_prop_count: maximum count of properties (count of fixed properties + additional properties)
        - max_str_length: maximum length of string type
        - max_byte_length: maximum length of byte type
        - max_array_length: maximum length of array
        - max_file_length: maximum length of file, in byte
        - minimal_property: only generate 'required' properties
        - minimal_parameter: only generate 'required' parameter
        - files: registered file object: refer to pyswagger.primitives.File for details
        - object_template: dict of default values assigned for properties when 'name' matched
        - parameter_template: dict of default values assigned for parameters when 'name matched
        - max_property: all properties are generated, ignore 'required'
        - max_parameter: all parameters are generated, ignore 'required'

        :return: options
        :rtype: dict
        """
    return dict(max_name_length=64, max_prop_count=32, max_str_length=100,
        max_byte_length=100, max_array_length=100, max_file_length=200,
        minimal_property=False, minimal_parameter=False, files=[],
        object_template={}, parameter_template={}, max_property=False,
        max_parameter=False)


def setup(catalog, name, context):
    """Set up index called name in given catalog.

        Use name for index name and attribute to index. Set up
        index for interface or class context.
        """


@staticmethod
def _value_for_target(value, target):
    """ If a value is valid for a particular target architecture then
        return the value, otherwise return None.
        """
    parts = value.split('#', maxsplit=1)
    if len(parts) != 2:
        return value
    scope, value = parts
    for name in scope.replace(' ', '').split('|'):
        if name.startswith('!'):
            negate = True
            name = name[1:]
        else:
            negate = False
        if '-' in name:
            matches = target.name == name
        else:
            matches = target.platform.name == name
        if negate:
            matches = not matches
        if matches:
            return value
    return None


def snake_to_darwin_case(text: str) ->str:
    """Convert snake_case to Darwin_Case."""
    return '_'.join(map(str.capitalize, text.split('_')))


def get_frac_dels(var):
    """
    Returns the fraction of reads containing spanning deletions,
    or None if it isn't present in the VCF.
    """
    return var.INFO.get('Dels')


def convert_to_orcid(record):
    """Dummy converter, assuming that the record is a dojson serialization of MARC.

    To create yours see https://github.com/ORCID/python-orcid
    and http://members.orcid.org/api.
    """
    return {'title': {'title': record[0]['title_statement']['title']},
        'type': 'JOURNAL_ARTICLE', 'external-ids': {'external-id': [{
        'external-id-value': record[0]['other_standard_identifier'][
        'standard_number_or_code'], 'external-id-type': 'doi',
        'external-id-relationship': 'SELF'}]}}


@classmethod
def clean_unusable_keys(cls, resource):
    """Delete keys of dictionary not used

        :param resource: dictionary got from alignak-backend
        :type resource: dict
        :return:
        """
    fields = ['_links', '_updated', '_created', '_etag', '_id', 'name',
        'ui', '_realm', '_sub_realm', '_users_read', '_users_update',
        '_users_delete', '_parent', '_tree_parents', '_all_children',
        '_level', 'customs', 'host', 'service', 'back_role_super_admin',
        'token', '_templates', '_template_fields', 'note', '_is_template',
        '_templates_with_services', '_templates_from_host_template',
        'merge_host_users', 'hosts_critical_threshold',
        'hosts_warning_threshold', 'services_critical_threshold',
        'services_warning_threshold', 'global_critical_threshold',
        'global_warning_threshold', '_children', 'hostgroups', 'hosts',
        'dependent_hostgroups', 'dependent_hosts', 'servicegroups',
        'services', 'dependent_servicegroups', 'dependent_services',
        'usergroups', 'users', 'location', 'duplicate_foreach', 'tags',
        '_overall_state_id', 'trigger', 'schema_version']
    for field in resource:
        if field.startswith('ls_'):
            fields.append(field)
    for field in fields:
        if field in resource:
            del resource[field]


@classmethod
def create_generic(cls):
    """
        Return a UnknownLanguage instance..
        :return: UnknownLanguage instance.
        """
    return cls('unknown')


def _collectAttributes(cls, new_attrs, look_for_class):
    """Finds all attributes in `new_attrs` that are instances of
    `look_for_class`. The ``.name`` attribute is set for any matching objects.
    Returns them as a list.

    """
    result = []
    for attr, value in new_attrs.items():
        if isinstance(value, look_for_class):
            value.name = attr
            delattr(cls, attr)
            result.append(value)
    return result


def _recv_n_delete_rq(event):
    """Logging handler when an N-DELETE-RQ is received.

    Parameters
    ----------
    event : events.Event
        The evt.EVT_DIMSE_RECV event that occurred.
    """
    pass


def num_to_letter(num):
    """Return the letter of the English alphabet at the given position."""
    if not isinstance(num, int):
        raise TypeError('Expected an integer')
    if num < 1 or num > 26:
        raise ValueError('Expected an integer between 1 and 26 (inclusive)')
    return chr(num - 1 + ord('A'))


@classmethod
def get_types_import_string(cls):
    """Returns a string like `from typing import List, Set, Union`"""
    type_str = ', '.join(cls.types)
    return f'from typing import {type_str}'


def startEnd(length, start, end):
    """Helper function to normalize the start and end of an array by counting from the end of the array (just like Python).

    :type length: non-negative integer
    :param length: length of the array in question
    :type start: integer
    :param start: starting index to interpret
    :type end: integer
    :param end: ending index to interpret
    :rtype: (non-negative integer, non-negative integer)
    :return: (normalized starting index, normalized ending index)
    """
    if start >= 0:
        normStart = start
    else:
        normStart = length + start
    if normStart < 0:
        normStart = 0
    if normStart > length:
        normStart = length
    if end >= 0:
        normEnd = end
    else:
        normEnd = length + end
    if normEnd < 0:
        normEnd = 0
    if normEnd > length:
        normEnd = length
    if normEnd < normStart:
        normEnd = normStart
    return normStart, normEnd


def get_erp(_, data):
    """http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n323

    Positional arguments:
    data -- bytearray data to read.

    Returns:
    String.
    """
    if data[0] == 0:
        return '<no flags>'
    if data[0] & 1:
        return 'NonERP_Present'
    if data[0] & 2:
        return 'Use_Protection'
    if data[0] & 4:
        return 'Barker_Preamble_Mode'
    return ''


def mate_in_region(aln, regtup):
    """ Check if mate is found within region

    Return True if mate is found within region or region is None

    Args:
        aln (:obj:`pysam.AlignedSegment`): An aligned segment
        regtup (:tuple: (chrom, start, end)): Region
    Returns:
        bool: True if mate is within region

    """
    if regtup is None:
        return True
    return aln.next_reference_id == regtup[0] and regtup[1
        ] < aln.next_reference_start < regtup[2]


def poly_export(poly):
    """Saves parts of a polytope as a dictionary for export to MATLAB.

    @param poly: L{Polytope} that will be exported.
    @return output: dictionary containing fields of poly
    """
    output = {}
    if poly is not None:
        output['A'] = poly.A
        output['b'] = poly.b
    return output


def _maybe_print(something_to_print, end=None, min_=1, max_=99, verbose=0):
    """Print if verbose is within min_ and max_."""
    if min_ <= verbose <= max_:
        import sys
        print(something_to_print, end=end)
        sys.stdout.flush()


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

        :param PaperExternalViewDefaultTeamType val:
        :rtype: EventType
        """
    return cls('paper_external_view_default_team', val)


def queryProxy(obj, proxytype, default=None):
    """Look for a proxy of the given type around the object

        If no such proxy can be found, return the default.
        """


def neg_imag(data):
    """
    Negate imaginary data
    """
    data.imag = -data.imag
    return data


def timediff(datetime1, datetime2, eod=2400.0):
    """Compares date tuples and returns difference in
    a time tuple
    """
    date1, time1 = datetime1
    date2, time2 = datetime2
    date3 = date2 - date1
    time3 = time2 - time1
    return date3 * eod + time3


def receive_data_from_gpu(simulation):
    """
    Receive the simulation data from the GPU.
    Calls the functions of the particle and field package
    that receive the data from the GPU.

    Parameters :
    ------------
    simulation : object
        A simulation object that contains the particle
        (ptcl) and field object (fld)
    """
    for species in simulation.ptcl:
        if species.use_cuda:
            species.receive_particles_from_gpu()
    simulation.fld.receive_fields_from_gpu()


def get_resource_filename(manager, resource_name):
    """Return a true filesystem path for `resource_name`

        `manager` must be an ``IResourceManager``"""


def getstack(repo, rev=None):
    """return a sorted smartrev of the stack containing either rev if it is
    not None or the current working directory parent.

    The stack will always contain all drafts changesets which are ancestors to
    the revision and are not merges.
    """
    if rev is None:
        rev = b'.'
    revspec = b'only(%s) and not public() and not ::merge()'
    revisions = repo.revs(revspec, rev)
    revisions.sort()
    return revisions


def canonical_object_url():
    """The URL to the current "canonical" object.

        That is, the current object unless this object is the default page
        in its folder, in which case the folder is returned.
        """


def getBatchStart():
    """Return the batch start index."""


def generate_chip_id(g, method='chip_id_simple'):
    """
    Generates a ``chip_id`` field on each node based a dedicated scheme

    """
    for node in g.nodes():
        if 'chip_id' in g.node[node]:
            continue
        g.node[node]['chip_id'] = globals()[method](g, node)


def _try_resize_dim_0_inplace(array, new_shape_0):
    """Try to resize 0-axis of array in-place or return a view otherwise."""
    if new_shape_0 >= array.shape[0]:
        return array
    try:
        array.resize((new_shape_0,) + array.shape[1:])
        return array
    except ValueError:
        return array[:new_shape_0]


def find_duplicates(iterable):
    """Find duplicate elements in an iterable.
    Parameters
    ----------
    iterable : iterable
        Iterable to be searched for duplicates (i.e., elements that are
        repeated).
    Returns
    -------
    set
        Repeated elements in `iterable`.
    """
    seen, repeated = set(), set()
    for e in iterable:
        if e in seen:
            repeated.add(e)
        else:
            seen.add(e)
    return repeated


def pytest_xdist_rsyncfinish(source, gateways):
    """ called after rsyncing a directory to remote gateways takes place. """


def shade_smooth():
    """Set shading to smooth

    """
    pass


def create_pipeline(Name=None, InputBucket=None, OutputBucket=None, Role=
    None, AwsKmsKeyArn=None, Notifications=None, ContentConfig=None,
    ThumbnailConfig=None):
    """
    The CreatePipeline operation creates a pipeline with settings that you specify.
    See also: AWS API Documentation

    :example: response = client.create_pipeline(
        Name='string',
        InputBucket='string',
        OutputBucket='string',
        Role='string',
        AwsKmsKeyArn='string',
        Notifications={
            'Progressing': 'string',
            'Completed': 'string',
            'Warning': 'string',
            'Error': 'string'
        },
        ContentConfig={
            'Bucket': 'string',
            'StorageClass': 'string',
            'Permissions': [
                {
                    'GranteeType': 'string',
                    'Grantee': 'string',
                    'Access': [
                        'string',
                    ]
                },
            ]
        },
        ThumbnailConfig={
            'Bucket': 'string',
            'StorageClass': 'string',
            'Permissions': [
                {
                    'GranteeType': 'string',
                    'Grantee': 'string',
                    'Access': [
                        'string',
                    ]
                },
            ]
        }
    )

    :type Name: string
    :param Name: [REQUIRED]
            The name of the pipeline. We recommend that the name be unique within the AWS account, but uniqueness is not enforced.
            Constraints: Maximum 40 characters.

    :type InputBucket: string
    :param InputBucket: [REQUIRED]
            The Amazon S3 bucket in which you saved the media files that you want to transcode.

    :type OutputBucket: string
    :param OutputBucket: The Amazon S3 bucket in which you want Elastic Transcoder to save the transcoded files. (Use this, or use ContentConfig:Bucket plus ThumbnailConfig:Bucket.)
            Specify this value when all of the following are true:
            You want to save transcoded files, thumbnails (if any), and playlists (if any) together in one bucket.
            You do not want to specify the users or groups who have access to the transcoded files, thumbnails, and playlists.
            You do not want to specify the permissions that Elastic Transcoder grants to the files.
            Warning
            When Elastic Transcoder saves files in OutputBucket , it grants full control over the files only to the AWS account that owns the role that is specified by Role .
            You want to associate the transcoded files and thumbnails with the Amazon S3 Standard storage class.
            If you want to save transcoded files and playlists in one bucket and thumbnails in another bucket, specify which users can access the transcoded files or the permissions the users have, or change the Amazon S3 storage class, omit OutputBucket and specify values for ContentConfig and ThumbnailConfig instead.

    :type Role: string
    :param Role: [REQUIRED]
            The IAM Amazon Resource Name (ARN) for the role that you want Elastic Transcoder to use to create the pipeline.

    :type AwsKmsKeyArn: string
    :param AwsKmsKeyArn: The AWS Key Management Service (AWS KMS) key that you want to use with this pipeline.
            If you use either S3 or S3-AWS-KMS as your Encryption:Mode , you don't need to provide a key with your job because a default key, known as an AWS-KMS key, is created for you automatically. You need to provide an AWS-KMS key only if you want to use a non-default AWS-KMS key, or if you are using an Encryption:Mode of AES-PKCS7 , AES-CTR , or AES-GCM .

    :type Notifications: dict
    :param Notifications: The Amazon Simple Notification Service (Amazon SNS) topic that you want to notify to report job status.
            Warning
            To receive notifications, you must also subscribe to the new topic in the Amazon SNS console.
            Progressing : The topic ARN for the Amazon Simple Notification Service (Amazon SNS) topic that you want to notify when Elastic Transcoder has started to process a job in this pipeline. This is the ARN that Amazon SNS returned when you created the topic. For more information, see Create a Topic in the Amazon Simple Notification Service Developer Guide.
            Completed : The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder has finished processing a job in this pipeline. This is the ARN that Amazon SNS returned when you created the topic.
            Warning : The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters a warning condition while processing a job in this pipeline. This is the ARN that Amazon SNS returned when you created the topic.
            Error : The topic ARN for the Amazon SNS topic that you want to notify when Elastic Transcoder encounters an error condition while processing a job in this pipeline. This is the ARN that Amazon SNS returned when you created the topic.
            Progressing (string) --The Amazon Simple Notification Service (Amazon SNS) topic that you want to notify when Elastic Transcoder has started to process the job.
            Completed (string) --The Amazon SNS topic that you want to notify when Elastic Transcoder has finished processing the job.
            Warning (string) --The Amazon SNS topic that you want to notify when Elastic Transcoder encounters a warning condition.
            Error (string) --The Amazon SNS topic that you want to notify when Elastic Transcoder encounters an error condition.

    :type ContentConfig: dict
    :param ContentConfig: The optional ContentConfig object specifies information about the Amazon S3 bucket in which you want Elastic Transcoder to save transcoded files and playlists: which bucket to use, which users you want to have access to the files, the type of access you want users to have, and the storage class that you want to assign to the files.
            If you specify values for ContentConfig , you must also specify values for ThumbnailConfig .
            If you specify values for ContentConfig and ThumbnailConfig , omit the OutputBucket object.
            Bucket : The Amazon S3 bucket in which you want Elastic Transcoder to save transcoded files and playlists.
            Permissions (Optional): The Permissions object specifies which users you want to have access to transcoded files and the type of access you want them to have. You can grant permissions to a maximum of 30 users and/or predefined Amazon S3 groups.
            Grantee Type : Specify the type of value that appears in the Grantee object:
            Canonical : The value in the Grantee object is either the canonical user ID for an AWS account or an origin access identity for an Amazon CloudFront distribution. For more information about canonical user IDs, see Access Control List (ACL) Overview in the Amazon Simple Storage Service Developer Guide. For more information about using CloudFront origin access identities to require that users use CloudFront URLs instead of Amazon S3 URLs, see Using an Origin Access Identity to Restrict Access to Your Amazon S3 Content.
            Warning
            A canonical user ID is not the same as an AWS account number.
            Email : The value in the Grantee object is the registered email address of an AWS account.
            Group : The value in the Grantee object is one of the following predefined Amazon S3 groups: AllUsers , AuthenticatedUsers , or LogDelivery .
            Grantee : The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group
            Access : The permission that you want to give to the AWS user that you specified in Grantee . Permissions are granted on the files that Elastic Transcoder adds to the bucket, including playlists and video files. Valid values include:
            READ : The grantee can read the objects and metadata for objects that Elastic Transcoder adds to the Amazon S3 bucket.
            READ_ACP : The grantee can read the object ACL for objects that Elastic Transcoder adds to the Amazon S3 bucket.
            WRITE_ACP : The grantee can write the ACL for the objects that Elastic Transcoder adds to the Amazon S3 bucket.
            FULL_CONTROL : The grantee has READ , READ_ACP , and WRITE_ACP permissions for the objects that Elastic Transcoder adds to the Amazon S3 bucket.
            StorageClass : The Amazon S3 storage class, Standard or ReducedRedundancy , that you want Elastic Transcoder to assign to the video files and playlists that it stores in your Amazon S3 bucket.
            Bucket (string) --The Amazon S3 bucket in which you want Elastic Transcoder to save the transcoded files. Specify this value when all of the following are true:
            You want to save transcoded files, thumbnails (if any), and playlists (if any) together in one bucket.
            You do not want to specify the users or groups who have access to the transcoded files, thumbnails, and playlists.
            You do not want to specify the permissions that Elastic Transcoder grants to the files.
            You want to associate the transcoded files and thumbnails with the Amazon S3 Standard storage class.
            If you want to save transcoded files and playlists in one bucket and thumbnails in another bucket, specify which users can access the transcoded files or the permissions the users have, or change the Amazon S3 storage class, omit OutputBucket and specify values for ContentConfig and ThumbnailConfig instead.
            StorageClass (string) --The Amazon S3 storage class, Standard or ReducedRedundancy , that you want Elastic Transcoder to assign to the video files and playlists that it stores in your Amazon S3 bucket.
            Permissions (list) --Optional. The Permissions object specifies which users and/or predefined Amazon S3 groups you want to have access to transcoded files and playlists, and the type of access you want them to have. You can grant permissions to a maximum of 30 users and/or predefined Amazon S3 groups.
            If you include Permissions , Elastic Transcoder grants only the permissions that you specify. It does not grant full permissions to the owner of the role specified by Role . If you want that user to have full control, you must explicitly grant full control to the user.
            If you omit Permissions , Elastic Transcoder grants full control over the transcoded files and playlists to the owner of the role specified by Role , and grants no other permissions to any other user or group.
            (dict) --The Permission structure.
            GranteeType (string) --The type of value that appears in the Grantee object:
            Canonical : Either the canonical user ID for an AWS account or an origin access identity for an Amazon CloudFront distribution.
            Warning
            A canonical user ID is not the same as an AWS account number.
            Email : The registered email address of an AWS account.
            Group : One of the following predefined Amazon S3 groups: AllUsers , AuthenticatedUsers , or LogDelivery .
            Grantee (string) --The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group.
            Access (list) --The permission that you want to give to the AWS user that is listed in Grantee. Valid values include:
            READ : The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            READ_ACP : The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            WRITE_ACP : The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            FULL_CONTROL : The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            (string) --

    :type ThumbnailConfig: dict
    :param ThumbnailConfig: The ThumbnailConfig object specifies several values, including the Amazon S3 bucket in which you want Elastic Transcoder to save thumbnail files, which users you want to have access to the files, the type of access you want users to have, and the storage class that you want to assign to the files.
            If you specify values for ContentConfig , you must also specify values for ThumbnailConfig even if you don't want to create thumbnails.
            If you specify values for ContentConfig and ThumbnailConfig , omit the OutputBucket object.
            Bucket : The Amazon S3 bucket in which you want Elastic Transcoder to save thumbnail files.
            Permissions (Optional): The Permissions object specifies which users and/or predefined Amazon S3 groups you want to have access to thumbnail files, and the type of access you want them to have. You can grant permissions to a maximum of 30 users and/or predefined Amazon S3 groups.
            GranteeType : Specify the type of value that appears in the Grantee object:
            Canonical : The value in the Grantee object is either the canonical user ID for an AWS account or an origin access identity for an Amazon CloudFront distribution.
            Warning
            A canonical user ID is not the same as an AWS account number.
            Email : The value in the Grantee object is the registered email address of an AWS account.
            Group : The value in the Grantee object is one of the following predefined Amazon S3 groups: AllUsers , AuthenticatedUsers , or LogDelivery .
            Grantee : The AWS user or group that you want to have access to thumbnail files. To identify the user or group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group.
            Access : The permission that you want to give to the AWS user that you specified in Grantee . Permissions are granted on the thumbnail files that Elastic Transcoder adds to the bucket. Valid values include:
            READ : The grantee can read the thumbnails and metadata for objects that Elastic Transcoder adds to the Amazon S3 bucket.
            READ_ACP : The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            WRITE_ACP : The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            FULL_CONTROL : The grantee has READ , READ_ACP , and WRITE_ACP permissions for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            StorageClass : The Amazon S3 storage class, Standard or ReducedRedundancy , that you want Elastic Transcoder to assign to the thumbnails that it stores in your Amazon S3 bucket.
            Bucket (string) --The Amazon S3 bucket in which you want Elastic Transcoder to save the transcoded files. Specify this value when all of the following are true:
            You want to save transcoded files, thumbnails (if any), and playlists (if any) together in one bucket.
            You do not want to specify the users or groups who have access to the transcoded files, thumbnails, and playlists.
            You do not want to specify the permissions that Elastic Transcoder grants to the files.
            You want to associate the transcoded files and thumbnails with the Amazon S3 Standard storage class.
            If you want to save transcoded files and playlists in one bucket and thumbnails in another bucket, specify which users can access the transcoded files or the permissions the users have, or change the Amazon S3 storage class, omit OutputBucket and specify values for ContentConfig and ThumbnailConfig instead.
            StorageClass (string) --The Amazon S3 storage class, Standard or ReducedRedundancy , that you want Elastic Transcoder to assign to the video files and playlists that it stores in your Amazon S3 bucket.
            Permissions (list) --Optional. The Permissions object specifies which users and/or predefined Amazon S3 groups you want to have access to transcoded files and playlists, and the type of access you want them to have. You can grant permissions to a maximum of 30 users and/or predefined Amazon S3 groups.
            If you include Permissions , Elastic Transcoder grants only the permissions that you specify. It does not grant full permissions to the owner of the role specified by Role . If you want that user to have full control, you must explicitly grant full control to the user.
            If you omit Permissions , Elastic Transcoder grants full control over the transcoded files and playlists to the owner of the role specified by Role , and grants no other permissions to any other user or group.
            (dict) --The Permission structure.
            GranteeType (string) --The type of value that appears in the Grantee object:
            Canonical : Either the canonical user ID for an AWS account or an origin access identity for an Amazon CloudFront distribution.
            Warning
            A canonical user ID is not the same as an AWS account number.
            Email : The registered email address of an AWS account.
            Group : One of the following predefined Amazon S3 groups: AllUsers , AuthenticatedUsers , or LogDelivery .
            Grantee (string) --The AWS user or group that you want to have access to transcoded files and playlists. To identify the user or group, you can specify the canonical user ID for an AWS account, an origin access identity for a CloudFront distribution, the registered email address of an AWS account, or a predefined Amazon S3 group.
            Access (list) --The permission that you want to give to the AWS user that is listed in Grantee. Valid values include:
            READ : The grantee can read the thumbnails and metadata for thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            READ_ACP : The grantee can read the object ACL for thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            WRITE_ACP : The grantee can write the ACL for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            FULL_CONTROL : The grantee has READ, READ_ACP, and WRITE_ACP permissions for the thumbnails that Elastic Transcoder adds to the Amazon S3 bucket.
            (string) --

    :rtype: dict
    :return: {
        'Pipeline': {
            'Id': 'string',
            'Arn': 'string',
            'Name': 'string',
            'Status': 'string',
            'InputBucket': 'string',
            'OutputBucket': 'string',
            'Role': 'string',
            'AwsKmsKeyArn': 'string',
            'Notifications': {
                'Progressing': 'string',
                'Completed': 'string',
                'Warning': 'string',
                'Error': 'string'
            },
            'ContentConfig': {
                'Bucket': 'string',
                'StorageClass': 'string',
                'Permissions': [
                    {
                        'GranteeType': 'string',
                        'Grantee': 'string',
                        'Access': [
                            'string',
                        ]
                    },
                ]
            },
            'ThumbnailConfig': {
                'Bucket': 'string',
                'StorageClass': 'string',
                'Permissions': [
                    {
                        'GranteeType': 'string',
                        'Grantee': 'string',
                        'Access': [
                            'string',
                        ]
                    },
                ]
            }
        },
        'Warnings': [
            {
                'Code': 'string',
                'Message': 'string'
            },
        ]
    }

    :returns:
    Active : The pipeline is processing jobs.
    Paused : The pipeline is not currently processing jobs.

    """
    pass


def fno_to_na(fno):
    """Convert an fno to an NA.

    Parameters
    ----------
    fno : `float`
        focal ratio

    Returns
    -------
    `float`
        NA.  The NA of the system.

    """
    return 1 / (2 * fno)


def marthas_columns(data, verbose=0):
    """
    This program is named  in honor of my one of students who came up with the idea for it.
    It's a neat way of looking at data compared to the boring describe() function in Pandas.
    """
    data = data[:]
    print('Data Set Shape: %d rows, %d cols\n' % data.shape)
    if data.shape[1] > 25:
        print('Too many columns to print')
    elif verbose == 1:
        print('Data Set columns info:')
        for col in data.columns:
            print('* %s: %d nulls, %d unique vals, most common: %s' % (col,
                data[col].isnull().sum(), data[col].nunique(), data[col].
                value_counts().head(2).to_dict()))
        print('\n------\n')


def l1_dissimilarity(a, b):
    """Compute dissimilarity between rows of  `a` and `b` as :math:`||a-b||_1`.

    """
    assert len(a.shape) == len(b.shape)
    return (a - b).norm(p=1, dim=-1)


def _p_deactivate():
    """Deactivate the object.

        Possibly change an object in the saved state to the
        ghost state.  It may not be possible to make some persistent
        objects ghosts, and, for optimization reasons, the implementation
        may choose to keep an object in the saved state.
        """


def _collapse_entries(entries):
    """
    Convert [['key', 'value1'], ['key', 'value2]] to [['key', ['value1', 'value2']]]
    Expect key values to be consecutive. Will maintain order as provided.
    """
    if entries is None or len(entries) < 1:
        return []
    else:
        cur_key = entries[0][0]
        cur_value = []
        new_entry = []
    for entry in entries:
        if entry[0] == cur_key:
            cur_value.append(entry[1])
        else:
            new_entry.append([cur_key, cur_value])
            cur_key = entry[0]
            cur_value = [entry[1]]
    new_entry.append([cur_key, cur_value])
    return new_entry


def xor_bytes(a, b):
    """
    XOR on two bytes objects

    Args:
        a (bytes): object 1
        b (bytes): object 2

    Returns:
        bytes: The XOR result
    """
    assert isinstance(a, bytes)
    assert isinstance(b, bytes)
    assert len(a) == len(b)
    res = bytearray()
    for i in range(len(a)):
        res.append(a[i] ^ b[i])
    return bytes(res)


def _field_name(name, prefix=None):
    """
    Util for quick prefixes

    >>> _field_name(1)
    '1'
    >>> _field_name("henk")
    'henk'
    >>> _field_name("henk", 1)
    '1henk'
    """
    if prefix is None:
        return str(name)
    return '%s%s' % (prefix, name)


@classmethod
def fromfile(cls, filename):
    """Class method. Loads a context from file
        Arguments:
            filename: name of the file to load
        """
    from .fromfile import fromfile
    return fromfile(filename)


@classmethod
def view_list(cls, lst):
    """
        Create a dict that is a view on the given list
        """
    if not isinstance(lst, list):
        raise TypeError(
            '%s.view_list(obj) takes only actual list objects, not %r' % (
            cls.__name__, lst))
    obj = cls()
    obj._items = lst
    return obj


def create_output_script(pubkey):
    """Create an output script for paying to a pubkey from coinbase."""
    script_len = '41'
    OP_CHECKSIG = 'ac'
    return (script_len + pubkey + OP_CHECKSIG).decode('hex')


@classmethod
def DeregisterCredentials(cls, credentials):
    """Deregisters a path specification credentials.

    Args:
      credentials (Credentials): credentials.

    Raises:
      KeyError: if credential object is not set for the corresponding
          type indicator.
    """
    if credentials.type_indicator not in cls._credentials:
        raise KeyError('Credential object not set for type indicator: {0:s}.'
            .format(credentials.type_indicator))
    del cls._credentials[credentials.type_indicator]


def map2(func, *xs):
    """Apply arguments to a function and return a C{tuple} of results.

       Unlike Python 2's built-in L{map}, Python 3+ L{map} returns a
       L{map} object, an iterator-like object which generates the
       results only once.  Converting the L{map} object to a tuple
       maintains Python 2 behavior.

       @arg func: Function to apply (C{callable}).
       @arg xs: Arguments to apply (C{list, tuple, ...}).

       @return: Function results (C{tuple}).
    """
    return tuple(map(func, *xs))


def pgrb2(closest, offset):
    """pgrb2 1 degree dataset naming convention."""
    return 'gfs.t%02dz.pgrb2.1p00.f%03d' % (closest, offset)


def sizeof_fmt(num):
    """
    Formats number of bytes into a human readable form.

    From:
    """
    for size in ['bytes', 'KB', 'MB', 'GB']:
        if -1024.0 < num < 1024.0:
            return '%3.1f %s' % (num, size)
        num /= 1024.0
    return '%3.1f %s' % (num, 'TB')


def loop_separate(loop: 'bmesh.types.BMLoop'):
    """Rip a vertex in a face away and add a new vertex.

    :param loop: The loop to separate.
    :type loop: 'bmesh.types.BMLoop'
    """
    pass


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'vc_capable':
        'A boolean indicating if the device is currently configured in a virtual chassis. In spite of the name, this fact does NOT indicate whether or not the device is CAPABLE of joining a VC.'
        , 'vc_mode':
        'A string indicating the current virtual chassis mode of the device.',
        'vc_fabric':
        'A boolean indicating if the device is currently in fabric mode.',
        'vc_master':
        'A string indicating the chassis/node which is currently the master of the VC.'
        }


@staticmethod
def get_generatorStep(generator):
    """
        return data step N

        :return: int,step
        """
    step = generator.n // generator.batch_size
    return step


def IsBlankLine(line):
    """Returns true if the given line is blank.

  We consider a line to be blank if the line is empty or consists of
  only white spaces.

  Args:
    line: A line of a string.

  Returns:
    True, if the given line is blank.
  """
    return not line or line.isspace()


def snap(frame: int=0):
    """Frame where selected strips will be snapped

    :param frame: Frame, Frame where selected strips will be snapped
    :type frame: int
    """
    pass


def bC_Ca_HSO4_HMW84(T, P):
    """c-a: calcium bisulfate [HMW84]."""
    b0 = 0.2145
    b1 = 2.53
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length."""
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


def format_kwarg_dictionaries(default_kwargs=None, user_kwargs=None,
    protected_keys=None):
    """Function to combine default and user specified kwargs dictionaries

    Parameters
    ----------
    default_kwargs : dict, optional
        Default kwargs (default is None).
    user_kwargs : dict, optional
        User specified kwargs (default is None).
    protected_keys : array_like, optional
        Sequence of keys to be removed from the returned dictionary
        (default is None).

    Returns
    -------
    formatted_kwargs : dict
        Formatted kwargs dictionary.
    """
    formatted_kwargs = {}
    for d in [default_kwargs, user_kwargs]:
        if not isinstance(d, (dict, type(None))):
            raise TypeError(
                'd must be of type dict or None, but got {} instead'.format
                (type(d)))
        if d is not None:
            formatted_kwargs.update(d)
    if protected_keys is not None:
        for key in protected_keys:
            formatted_kwargs.pop(key, None)
    return formatted_kwargs


def log_start(start):
    """Styling for a block start log statement"""
    print('%s...\n' % start)


def get_next_free(prefix, type_generating, to_check):
    """ Get free next state or symbol """
    idx = 0
    new_var = type_generating(prefix)
    while new_var in to_check:
        new_var = type_generating(prefix + str(idx))
        idx += 1
    return new_var


def draw_stars(surface, stars, color):
    """used to draw (and clear) the stars"""
    for vel, pos in stars:
        pos = int(pos[0]), int(pos[1])
        surface.set_at(pos, color)


def formula_2009_01_01(foyer_fiscal, period, parameters):
    """
        Attention : Pour les années avant 2013, cette formule n'est pas entièrement correcte car le taux de la CSG n'était pas unique (distinction revenus du patrimoine et revenus de placement)
        """
    assiette_csg_revenus_capital = foyer_fiscal('assiette_csg_revenus_capital',
        period)
    P = parameters(period).taxation_capital.prelevements_sociaux
    total = (P.prelevement_social.revenus_du_patrimoine + P.caps.
        revenus_du_patrimoine + P.prelevements_solidarite.
        revenus_du_patrimoine + P.caps.rsa)
    return -assiette_csg_revenus_capital * total


def choose(n, k):
    """
    A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
    """
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in range(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0


def starmap(function, iterable):
    """
    Make an iterator that computes the function using arguments obtained from
    the iterable. Used instead of :func:`itertools.imap` when an argument
    parameters are already grouped in tuples from a single iterable (the data
    has been "pre-zipped"). The difference between :func:`itertools.imap` and
    :func:`starmap` parallels the distinction between ``function(a, b)`` and
    ``function(*c)``.

    .. note:: Software and documentation for this function are taken from
              CPython, :ref:`license details <psf-license>`.
    """
    for args in iterable:
        yield function(*args)


def invariants_constraint(fsm, k):
    """
    Computes the constraint to be added to the model when one wants to
    enforce the invariants declared in the SMV text.

    .. note::
        This constraint has no counterpart in BmcModel. However, the same
        result can be achieved by computing the conjunction of
        BmcModel.invar[time] for all the times in the range [0; k].

    :param fsm: the fsm whose transition relation must be unrolled
    :param k: the maximum (horizon/bound) time of the problem
    :return: the invariants constraint enforced on the paths.
    """
    return fsm.encoding.and_interval(fsm.invariants, 0, k)


@classmethod
def add_arguments(cls):
    """
        sub parser document
        """
    return [(('--keep-document',), dict(help='use set optimize to 1')), ((
        '--original',), dict(help='use set optimize to 1'))]
    pass


def get_class_name_from_module_name(module_name):
    """ returns the class name corresponding to a module_name """
    return module_name[0].upper() + module_name[1:].rstrip('1234567890')


def exception(__self, __message, *args, **kwargs):
    """Convenience method for logging an ``'ERROR'`` with exception information."""
    options = (True,) + __self._options[1:]
    __self._log('ERROR', None, False, options, __message, args, kwargs)


def convert2boolean(arg):
    """convert2boolean is used for environmental variables that must be
       returned as boolean
    """
    if not isinstance(arg, bool):
        return arg.lower() in ('yes', 'true', 't', '1', 'y')
    return arg


def load_patterns(cur, pat_table_name):
    """
        load pre-defined constraints(currently only fixed attributes and variable attributes)
    """
    global_pattern_table = pat_table_name + '_global'
    load_query = 'SELECT * FROM {};'.format(global_pattern_table)
    cur.execute(load_query)
    res = cur.fetchall()
    print(res)
    patterns = []
    for pat in res:
        if pat[0].find('community_area') != -1 and pat[0].find('district'
            ) != -1:
            continue
        if pat[1].find('community_area') != -1 and pat[1].find('district'
            ) != -1:
            continue
        if pat[0].find('community_area') != -1 and pat[1].find('district'
            ) != -1:
            continue
        if pat[1].find('community_area') != -1 and pat[0].find('district'
            ) != -1:
            continue
        patterns.append(list(pat))
        patterns[-1][0] = patterns[-1][0][1:-1].replace(' ', '').split(',')
        patterns[-1][1] = patterns[-1][1][1:-1].replace(' ', '').split(',')
    return patterns


def chunks(items, size):
    """
    Takes a list and an integer as an input. Yield subsets of the list of the
    same size as the provided integer.
    """
    for index in range(0, len(items), size):
        yield items[index:index + size]


def dense_output(t_current, t_old, h_current, rcont):
    """
    Dense output function, basically extrapolatin
    """
    s = (t_current - t_old) / h_current
    s1 = 1.0 - s
    return rcont[0] + s * (rcont[1] + s1 * (rcont[2] + s * (rcont[3] + s1 *
        (rcont[4] + s * (rcont[5] + s1 * (rcont[6] + s * rcont[7]))))))


def manage_changePropertyTypes(old_ids, props, REQUEST=None):
    """Replace one set of properties with another

        Delete all properties that have ids in old_ids, then add a
        property for each item in props.  Each item has a new_id,
        new_value, and new_type.  The type of new_value should match
        new_type.
        """


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


@staticmethod
def parse_response_text(response):
    """
        Bulkergr API returns text in CVS format so we need to parse
        and convert it to a dictionary so we can easily access it
        :param response: enhanced requests instance response
        :return:
        """
    response.results = dict()
    response.results['ACK'] = response.text.split(';')[0]
    response.results['id'] = response.text.split(';')[1]
    response.results['charge'] = response.text.split(';')[2]
    if response.results['ACK'].startswith('ERROR'):
        response.results['error'] = True
    else:
        response.results['error'] = False
    return response


def is_default():
    """True if this content object is the default content object
        of the folder.
        """


def parameter_init(model, name, shape, init):
    """Create parameter given name, shape and initiator

    Parameters
    ----------
    name : str
        parameter name
    shape : tuple
        parameter shape
    init : mxnet.initializer
        an initializer

    Returns
    -------
    mxnet.gluon.parameter
        a parameter object
    """
    p = model.params.get(name, shape=shape, init=init)
    return p


@classmethod
def get_content(cls, abspath, start=None, end=None):
    """Retrieve the content of the requested resource which is located
        at the given absolute path.
        This class method may be overridden by subclasses.  Note that its
        signature is different from other overridable class methods
        (no ``settings`` argument); this is deliberate to ensure that
        ``abspath`` is able to stand on its own as a cache key.
        This method should either return a byte string or an iterator
        of byte strings.  The latter is preferred for large files
        as it helps reduce memory fragmentation.
        .. versionadded:: 3.1
        """
    with open(abspath, 'rb') as file:
        if start is not None:
            file.seek(start)
        if end is not None:
            remaining = end - (start or 0)
        else:
            remaining = None
        while True:
            chunk_size = 64 * 1024
            if remaining is not None and remaining < chunk_size:
                chunk_size = remaining
            chunk = file.read(chunk_size)
            if chunk:
                if remaining is not None:
                    remaining -= len(chunk)
                yield chunk
            else:
                if remaining is not None:
                    assert remaining == 0
                return


def focus_previous(event):
    """
    Focus the previous visible Window.
    (Often bound to the `BackTab` key.)
    """
    event.app.layout.focus_previous()


def obj_box_coord_scale_to_pixelunit(coord, shape=None):
    """Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format.
    It is the reverse process of ``obj_box_coord_rescale``.

    Parameters
    -----------
    coord : list of 4 float
        One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1].
    shape : tuple of 2 or None
        For [height, width].

    Returns
    -------
    list of 4 numbers
        New bounding box.

    Examples
    ---------
    >>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3))
      [40, 30, 100, 70]

    """
    if shape is None:
        shape = [100, 100]
    imh, imw = shape[0:2]
    x = int(coord[0] * imw)
    x2 = int(coord[2] * imw)
    y = int(coord[1] * imh)
    y2 = int(coord[3] * imh)
    return [x, y, x2, y2]


@classmethod
def from_pandas_dataframe(cls, dataframe, trained_cluster, **params):
    """
        Constructing the handler from a pandas dataframe.
        :param dataframe: the dataframe form which the handler is constructed.
        :param trained_cluster: sklearn cluster (trained / fitted).
        :param params: other params.
        :return: returns the classifier plot handler object.
        """
    dataset = dict()
    dataset['data'] = dataframe.drop('target', axis=1).values
    dataset['feature_names'] = dataframe.drop('target', axis=1).columns.values
    return cls(dataset, trained_cluster, **params)


def listen(docs, quiet):
    """For running with --listen option."""
    from veusz.veusz_listen import openWindow
    openWindow(docs, quiet=quiet)


@staticmethod
def _get_iso_image_name(node):
    """Returns the boot iso image name for a given node.

        :param node: the node for which image name is to be provided.
        """
    return 'boot-%s' % node.uuid


def dpad_topleft_heading(controller):
    """
    Callback function that is triggered, when the direction top left was pressed

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('DIRECTION:' + str(controller.number) + ':' + controller.name +
        ':DPAD Top Left heading')


def rev_seq(seq):
    """Reverse the sequence and use the complement bases.
    This is for annotation on "-" strand.

    example:
        rev_seq("atgc")
        >>> 'gcat'
        rev_seq("akgc")
        >>> "k" is not valid base in:
        >>> dict_keys(['A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't', 'n'])
    """
    complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N', 'a':
        't', 'c': 'g', 'g': 'c', 't': 'a', 'n': 'n'}
    return_seq = ''
    for base in seq:
        try:
            return_seq = complement[base] + return_seq
        except KeyError:
            print('"%s" is not valid base in:' % base)
            print(complement.keys())
            raise
    return return_seq


def _get_member_war_status_class(collection_day_battles, war_day_battles,
    war_date, join_date, current_war=False, war_day=False):
    """ returns CSS class(es) for a war log entry for a given member """
    if war_date < join_date:
        return 'not-in-clan'
    status = 'normal'
    if current_war:
        if collection_day_battles < 3:
            status = 'ok'
        elif war_day and war_day_battles > 0:
            status = 'good'
        if war_day == False or war_day_battles == 0:
            status += ' incomplete'
    elif collection_day_battles == 0:
        status = 'na'
    elif war_day_battles == 0:
        status = 'bad'
    elif collection_day_battles < 3:
        status = 'ok'
    else:
        status = 'good'
    return status


def extract_filename(name: str):
    """
        Convert '/path:Contract' to /path
    """
    if not ':' in name:
        return name
    return name[:name.rfind(':')]


def find_point_in_path(path, sub):
    """Find a point in a path.

    Parameters
    ----------
    path : tuple of array_like
        Tuple of arrays of int that represent indices into a matrix.
    sub : tuple in int
        Indices to search *path* for.

    Returns
    -------
    int or None
        Index into *path* if the indices are found. Otherwise, ``None``.

    Examples
    --------
    >>> path = ((0, 1, 4, 6, 5), (3, 1, 7, 8, 10))
    >>> find_point_in_path(path, (4, 7))
    2
    >>> find_point_in_path(path, (99, 2)) is None
    True
    """
    try:
        return list(zip(*path)).index(sub)
    except ValueError:
        return None


def before_persist_object_listener(mapper, connection, obj):
    """
    This listener method is used to ensure, that an objects 'on_persist' method
    is executed before the object is written to the database.
    """
    obj.on_persist()


def ensure_encoded(thing, encoding='utf-8'):
    """Ensures proper encoding for unicode characters.

    Currently used only for characters `✓` and `✗`.

    """
    if isinstance(thing, bytes) or not isinstance(thing, str):
        return thing
    else:
        return thing.encode(encoding)


def is_cscan_unusable(cscan):
    """
    Check to see if a CachedImageScan is unusable
    :param cscan: XnatUtils.CachedImageScan object
    :return: True if unusable, False otherwise
    """
    return cscan.info()['quality'] == 'unusable'


def is_null(value):
    """
    Check if the scalar value or tuple/list value is NULL.

    :param value: Value to check.
    :type value: a scalar or tuple or list

    :return: Returns ``True`` if and only if the value is NULL (scalar value is None
        or _any_ tuple/list elements are None).
    :rtype: bool
    """
    if type(value) in (tuple, list):
        for v in value:
            if v is None:
                return True
        return False
    else:
        return value is None


def generate_dist_folder_name(base_dist_name, arch_names=None):
    """Generate the distribution folder name to use, based on a
    combination of the input arguments.

    WARNING: This function is copied from python-for-android. It would
    be preferable to have a proper interface, either importing the p4a
    code or having a p4a dist dir query option.

    Parameters
    ----------
    base_dist_name : str
        The core distribution identifier string
    arch_names : list of str
        The architecture compile targets

    """
    if arch_names is None:
        arch_names = ['no_arch_specified']
    return '{}__{}'.format(base_dist_name, '_'.join(arch_names))


def raise_(ex=None):
    """
    Raises an exception, to be used inside lambdas, or raise exceptions as function calls
    :param ex: which exception to raise
    :return: raises an exception
    """
    ex = ex or Exception()
    raise ex


@classmethod
def get_name(cls):
    """ Returns the name of the logger.
		"""
    return 'binary'


def get_pow1000(num):
    """Determine exponent for which significand of a number is within the
    range [1, 1000).
    """
    from decimal import Decimal
    from math import floor
    dnum = Decimal(str(num))
    if dnum == 0:
        return 0
    elif dnum < 0:
        dnum = -dnum
    return int(floor(dnum.log10() / 3))


def isNumber(s):
    """
    Determines if a unicode string (that may include commas) is a number.

    :param s: Any unicode string.
    :return: True if s represents a number, False otherwise.
    """
    s = s.replace(',', '')
    try:
        float(s)
        return True
    except ValueError:
        pass
    try:
        import unicodedata
        unicodedata.numeric(s)
        return True
    except (TypeError, ValueError) as e:
        pass
    return False


def bwf_constraint_constructor(ai_parser):
    """ Add the argparse switches relative to the box_wood_frame
  """
    r_parser = ai_parser
    r_parser.add_argument('--box_width', '--bw', action='store', type=float,
        default=400.0, help='It sets the width of the box of the grid.')
    r_parser.add_argument('--box_depth', '--bd', action='store', type=float,
        default=400.0, help=
        'It sets the depth of the box of the grid. Per default, it is set to box_width value.'
        )
    r_parser.add_argument('--box_height', '--bh', action='store', type=
        float, default=400.0, help=
        'It sets the height of the box of the grid. Per default, it is set to box_width value.'
        )
    r_parser.add_argument('--fitting_height', '--fh', action='store', type=
        float, default=30.0, help=
        'It sets the height of the fitting that pile up vertically two modules.'
        )
    r_parser.add_argument('--h_plank_width', '--hpw', action='store', type=
        float, default=50.0, help=
        'It sets the width of the horizontal planks. Note that the total width of the horizontal plank is plank_width+fitting_height.'
        )
    r_parser.add_argument('--v_plank_width', '--vpw', action='store', type=
        float, default=30.0, help='It sets the width of the vertical planks.')
    r_parser.add_argument('--plank_height', '--ph', action='store', type=
        float, default=20.0, help=
        'It sets the height of the vertical and horizontal planks.')
    r_parser.add_argument('--d_plank_width', '--dpw', action='store', type=
        float, default=30.0, help=
        'It sets the width of the diagonal planks. Per default the value is set to v_plank_width.'
        )
    r_parser.add_argument('--d_plank_height', '--dph', action='store', type
        =float, default=10.0, help=
        'It sets the height of the diagonal planks. If the vaue is zero, the plank_height value will be used. Set a lower value than plank_height to give space for the slab.'
        )
    r_parser.add_argument('--crenel_depth', '--cd', action='store', type=
        float, default=5.0, help=
        'It sets the depth of the crenels of the coplanar planks.')
    r_parser.add_argument('--wall_diagonal_size', '--wdz', action='store',
        type=float, default=50.0, help=
        'It sets the size of the diagonal lining of the four vertical walls.')
    r_parser.add_argument('--tobo_diagonal_size', '--tbdz', action='store',
        type=float, default=100.0, help=
        'It sets the size of the diagonal lining of the top and bottom faces.')
    r_parser.add_argument('--diagonal_lining_top_height', '--dlth', action=
        'store', type=float, default=20.0, help=
        'It sets the distance between the plank border and the holes for the horizontal top planks.'
        )
    r_parser.add_argument('--diagonal_lining_bottom_height', '--dlbh',
        action='store', type=float, default=20.0, help=
        'It sets the distance between the plank border and the holes for the horizontal bottom planks.'
        )
    r_parser.add_argument('--module_width', '--mw', action='store', type=
        int, default=1, help=
        'It sets the width of the module in number of box_width.')
    r_parser.add_argument('--router_bit_radius', '--rr', action='store',
        type=float, default=2.0, help=
        'It sets the radius of the router_bit of the cnc.')
    r_parser.add_argument('--cutting_extra', '--ce', action='store', type=
        float, default=2.0, help=
        'It sets the cutting_extra used to see better the fitting in the assembly view.'
        )
    r_parser.add_argument('--slab_thickness', '--st', action='store', type=
        float, default=5.0, help=
        'If not zero (the default value), it generates the slabs with this thickness.'
        )
    return r_parser


@staticmethod
def _convert_query_params_to_string_for_bytes(query_params):
    """
        Required to set multiple build states i.e ?state[]=running&state[]=scheduled

        :param query_params: query parameters
        :return: bytes of query param
        """
    query_string = ''
    for key, value in query_params.items():
        if query_string != '':
            query_string += '&'
        if key == 'state':
            query_string += value
        else:
            query_string += key + '=' + str(value)
    return query_string


def millis_interval(start, end):
    """start and end are datetime instances"""
    diff = end - start
    millis = diff.days * 24 * 60 * 60 * 1000
    millis += diff.seconds * 1000
    millis += diff.microseconds / 1000
    return millis


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


@staticmethod
def _isSingleCharacter(keychr):
    """Check whether given keyboard character is a single character.

        Parameters: key character which will be checked.
        Returns: True when given key character is a single character.
        """
    if not keychr:
        return False
    if len(keychr) == 1:
        return True
    return keychr.count('<') == 1 and keychr.count('>') == 1 and keychr[0
        ] == '<' and keychr[-1] == '>'


def delete_ip_set(IPSetId=None, ChangeToken=None):
    """
    Permanently deletes an  IPSet . You can't delete an IPSet if it's still used in any Rules or if it still includes any IP addresses.
    If you just want to remove an IPSet from a Rule , use  UpdateRule .
    To permanently delete an IPSet from AWS WAF, perform the following steps:
    See also: AWS API Documentation

    Examples
    The following example deletes an IP match set  with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5.
    Expected Output:

    :example: response = client.delete_ip_set(
        IPSetId='string',
        ChangeToken='string'
    )

    :type IPSetId: string
    :param IPSetId: [REQUIRED]
            The IPSetId of the IPSet that you want to delete. IPSetId is returned by CreateIPSet and by ListIPSets .

    :type ChangeToken: string
    :param ChangeToken: [REQUIRED]
            The value returned by the most recent call to GetChangeToken .

    :rtype: dict
    :return: {
        'ChangeToken': 'string'
    }

    :returns:
    IPSetId (string) -- [REQUIRED]
    The IPSetId of the  IPSet that you want to delete. IPSetId is returned by  CreateIPSet and by  ListIPSets .

    ChangeToken (string) -- [REQUIRED]
    The value returned by the most recent call to  GetChangeToken .

    """
    pass


@classmethod
def untranslated_fields(cls):
    """
        The fields that should not be translated on this object.

        :rtype:
            `tuple`
        """
    return cls._untranslated_fields


def add_suffix(in_files, suffix):
    """
    Wrap nipype's fname_presuffix to conveniently just add a prefix

    >>> add_suffix([
    ...     '/path/to/sub-045_ses-test_T1w.nii.gz',
    ...     '/path/to/sub-045_ses-retest_T1w.nii.gz'], '_test')
    'sub-045_ses-test_T1w_test.nii.gz'

    """
    import os.path as op
    from nipype.utils.filemanip import fname_presuffix, filename_to_list
    return op.basename(fname_presuffix(filename_to_list(in_files)[0],
        suffix=suffix))


def lfsr_next_one_seed(seed_iter, min_value_shift):
    """High-quality seeding for LFSR generators.

    The LFSR generator components discard a certain number of their lower bits
    when generating each output. The significant bits of their state must not
    all be zero. We must ensure that when seeding the generator.

    In case generators are seeded from an incrementing input (such as a system
    timer), and between increments only the lower bits may change, we would
    also like the lower bits of the input to change the initial state, and not
    just be discarded. So we do basic manipulation of the seed input value to
    ensure that all bits of the seed input affect the initial state.
    """
    try:
        seed = seed_iter.next()
    except StopIteration:
        return 4294967295
    else:
        if seed is None:
            return 4294967295
        else:
            seed = int(seed) & 4294967295
            working_seed = (seed ^ seed << 16) & 4294967295
            min_value = 1 << min_value_shift
            if working_seed < min_value:
                working_seed = seed << 24 & 4294967295
                if working_seed < min_value:
                    working_seed ^= 4294967295
            return working_seed


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.vw.VowpalWabbitFeaturizer'


def _restore_coord_attrs(ds):
    """
    Put back coordinates attribute that
    to_netcdf and to_zarr didn't like.

    Parameters
    ----------
    ds: xarray.Dataset

    Returns
    -------
    ds: xarray.Dataset
    """
    for var in ds.variables:
        attrs = ds[var].attrs
        coordinates = attrs.pop('_coordinates', None)
        ds[var].attrs = attrs
        if coordinates is not None:
            ds[var].attrs['coordinates'] = coordinates
    return ds


def aggregated_tex(f, entropy_matrix):
    """
    Write in latex file entropy of 6 groups (need to be change to adapt number of groups)

    Parameters
    ----------
        f: file

        entropy_matrix: numpy array from proportion_group analysis

    Returns
    -------
        File (Optionnal)
    """
    f.write('\n% 4. Aggregated Diversity')
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupA', entropy_matrix[0])
        )
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupB', entropy_matrix[1])
        )
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupC', entropy_matrix[2])
        )
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupD', entropy_matrix[3])
        )
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupE', entropy_matrix[4])
        )
    f.write('\n\\newcommand{\\%s}{%.2f}' % ('EntropyGroupF', entropy_matrix[5])
        )
    return f


def foreground_origin():
    """Return the original object of FHIR model that is proxied!"""


def create_document(Content=None, Name=None, DocumentType=None):
    """
    Creates a Systems Manager document.
    After you create a document, you can use CreateAssociation to associate it with one or more running instances.
    See also: AWS API Documentation

    :example: response = client.create_document(
        Content='string',
        Name='string',
        DocumentType='Command'|'Policy'|'Automation'
    )

    :type Content: string
    :param Content: [REQUIRED]
            A valid JSON string.

    :type Name: string
    :param Name: [REQUIRED]
            A name for the Systems Manager document.

    :type DocumentType: string
    :param DocumentType: The type of document to create. Valid document types include: Policy, Automation, and Command.

    :rtype: dict
    :return: {
        'DocumentDescription': {
            'Sha1': 'string',
            'Hash': 'string',
            'HashType': 'Sha256'|'Sha1',
            'Name': 'string',
            'Owner': 'string',
            'CreatedDate': datetime(2015, 1, 1),
            'Status': 'Creating'|'Active'|'Updating'|'Deleting',
            'DocumentVersion': 'string',
            'Description': 'string',
            'Parameters': [
                {
                    'Name': 'string',
                    'Type': 'String'|'StringList',
                    'Description': 'string',
                    'DefaultValue': 'string'
                },
            ],
            'PlatformTypes': [
                'Windows'|'Linux',
            ],
            'DocumentType': 'Command'|'Policy'|'Automation',
            'SchemaVersion': 'string',
            'LatestVersion': 'string',
            'DefaultVersion': 'string'
        }
    }

    :returns:
    (string) --

    """
    pass


def connect():
    """
        Try to connect to remote address.
        """


def initialize():
    """Initialize script."""
    print('Welcome to auto_py_torrent!\n')


def register_log(filename, level='DEBUG'):
    """ Registers file to have logs written to.

    Args:
        filename: A string that is the filepath to log to, or sys.stderr/sys.stdout.
        level: Logging level. For example, "DEBUG".

    Returns:
        Logging handler.
    """
    import logging
    import logging.handlers
    import sys
    import multiprocessing
    if filename is sys.stderr or filename is sys.stdout:
        handler = logging.StreamHandler(stream=filename)
    else:
        handler = logging.handlers.WatchedFileHandler(filename)
    formatter = logging.Formatter(
        '%(asctime)s | %(filename)-20s %(lineno)-4s %(funcName)25s() | %(message)s'
        )
    handler.setFormatter(formatter)
    queue = multiprocessing.Queue(-1)
    queue_handler = logging.handlers.QueueHandler(queue)
    queue_listener = logging.handlers.QueueListener(queue, handler)
    queue_listener.start()
    root = logging.getLogger('interpret')
    root.setLevel(level)
    root.addHandler(queue_handler)
    return queue_handler


@staticmethod
def calculate_hex(hex_string):
    """Credit for conversion to itsnotlupus/vesync_wsproxy"""
    hex_conv = hex_string.split(':')
    converted_hex = (int(hex_conv[0], 16) + int(hex_conv[1], 16)) / 8192
    return converted_hex


def filter_irr(df, irr_col, low, high, ref_val=None):
    """
    Top level filter on irradiance values.

    Parameters
    ----------
    df : DataFrame
        Dataframe to be filtered.
    irr_col : str
        String that is the name of the column with the irradiance data.
    low : float or int
        Minimum value as fraction (0.8) or absolute 200 (W/m^2)
    high : float or int
        Max value as fraction (1.2) or absolute 800 (W/m^2)
    ref_val : float or int
        Must provide arg when min/max are fractions

    Returns
    -------
    DataFrame
    """
    if ref_val is not None:
        low *= ref_val
        high *= ref_val
    df_renamed = df.rename(columns={irr_col: 'poa'})
    flt_str = '@low <= ' + 'poa' + ' <= @high'
    indx = df_renamed.query(flt_str).index
    return df.loc[(indx), :]


def sdf(L, S, T):
    """
    Calculates Stream Depletion Factor given:
        L - Shortest distance from well to stream (m)
        S - Storage coefficient (-)
        T - Transmissivity (m2/d)
    Returns:
        y - stream depletion factor
    """
    y = L ** 2 * S / T
    print(
        'Stream Depletion Factor (SDF) for L:%.2f, S:%.2f, and T:%.2f = %.2f' %
        (L, S, T, y))
    return y


def flip(bbox, size, flip_x=False, flip_y=False):
    """Flip bounding boxes according to image flipping directions.

    Parameters
    ----------
    bbox : numpy.ndarray
        Numpy.ndarray with shape (N, 4+) where N is the number of bounding boxes.
        The second axis represents attributes of the bounding box.
        Specifically, these are :math:`(x_{min}, y_{min}, x_{max}, y_{max})`,
        we allow additional attributes other than coordinates, which stay intact
        during bounding box transformations.
    size : tuple
        Tuple of length 2: (width, height).
    flip_x : bool
        Whether flip horizontally.
    flip_y : bool
        Whether flip vertically.

    Returns
    -------
    numpy.ndarray
        Flipped bounding boxes with original shape.
    """
    if not len(size) == 2:
        raise ValueError('size requires length 2 tuple, given {}'.format(
            len(size)))
    width, height = size
    bbox = bbox.copy()
    if flip_y:
        ymax = height - bbox[:, (1)]
        ymin = height - bbox[:, (3)]
        bbox[:, (1)] = ymin
        bbox[:, (3)] = ymax
    if flip_x:
        xmax = width - bbox[:, (0)]
        xmin = width - bbox[:, (2)]
        bbox[:, (0)] = xmin
        bbox[:, (2)] = xmax
    return bbox


def list_deployment_instances(deploymentId=None, nextToken=None,
    instanceStatusFilter=None, instanceTypeFilter=None):
    """
    Lists the instance for a deployment associated with the applicable IAM user or AWS account.
    See also: AWS API Documentation

    :example: response = client.list_deployment_instances(
        deploymentId='string',
        nextToken='string',
        instanceStatusFilter=[
            'Pending'|'InProgress'|'Succeeded'|'Failed'|'Skipped'|'Unknown'|'Ready',
        ],
        instanceTypeFilter=[
            'Blue'|'Green',
        ]
    )

    :type deploymentId: string
    :param deploymentId: [REQUIRED]
            The unique ID of a deployment.

    :type nextToken: string
    :param nextToken: An identifier returned from the previous list deployment instances call. It can be used to return the next set of deployment instances in the list.

    :type instanceStatusFilter: list
    :param instanceStatusFilter: A subset of instances to list by status:
            Pending: Include those instance with pending deployments.
            InProgress: Include those instance where deployments are still in progress.
            Succeeded: Include those instances with successful deployments.
            Failed: Include those instance with failed deployments.
            Skipped: Include those instance with skipped deployments.
            Unknown: Include those instance with deployments in an unknown state.
            (string) --

    :type instanceTypeFilter: list
    :param instanceTypeFilter: The set of instances in a blue/green deployment, either those in the original environment ('BLUE') or those in the replacement environment ('GREEN'), for which you want to view instance information.
            (string) --

    :rtype: dict
    :return: {
        'instancesList': [
            'string',
        ],
        'nextToken': 'string'
    }

    :returns:
    (string) --

    """
    pass


def describe_cache_subnet_groups(CacheSubnetGroupName=None, MaxRecords=None,
    Marker=None):
    """
    Returns a list of cache subnet group descriptions. If a subnet group name is specified, the list contains only the description of that group.
    See also: AWS API Documentation

    :example: response = client.describe_cache_subnet_groups(
        CacheSubnetGroupName='string',
        MaxRecords=123,
        Marker='string'
    )

    :type CacheSubnetGroupName: string
    :param CacheSubnetGroupName: The name of the cache subnet group to return details for.

    :type MaxRecords: integer
    :param MaxRecords: The maximum number of records to include in the response. If more records exist than the specified MaxRecords value, a marker is included in the response so that the remaining results can be retrieved.
            Default: 100
            Constraints: minimum 20; maximum 100.

    :type Marker: string
    :param Marker: An optional marker returned from a prior request. Use this marker for pagination of results from this operation. If this parameter is specified, the response includes only records beyond the marker, up to the value specified by MaxRecords .

    :rtype: dict
    :return: {
        'Marker': 'string',
        'CacheSubnetGroups': [
            {
                'CacheSubnetGroupName': 'string',
                'CacheSubnetGroupDescription': 'string',
                'VpcId': 'string',
                'Subnets': [
                    {
                        'SubnetIdentifier': 'string',
                        'SubnetAvailabilityZone': {
                            'Name': 'string'
                        }
                    },
                ]
            },
        ]
    }

    :returns:
    CreateCacheSubnetGroup
    ModifyCacheSubnetGroup

    """
    pass


def is_conflict(contents):
    """
    Given ``contents``, return ``True`` if there are any conflicts in it.
    """
    return '<<<<<<<' in contents


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 valRisingSlopes(Frames):
    """Computes values of RISING slopes.Returns a list of
    all values of RISING slopes in the signal."""
    previous, slopes = Frames[0], []
    for i in range(len(Frames)):
        if Frames[i] > previous:
            slopes.append(Frames[i] - previous)
        previous = Frames[i]
    return slopes