def ppd_threshold_from_comfort_class(comf_class):
    """Get acceptable PPD comfort threshold given the EN-15251 comfort class.

    Args:
        comf_class: An integer representing the EN-15251 comfort class.
            Choose from: 1, 2, 3 (the higher the class, the greater the PPD threshold)

    Returns:
        ppd_thresh -- Acceptable PPD threshold.
    """
    if comf_class == 1:
        ppd_thresh = 6
    elif comf_class == 2:
        ppd_thresh = 10
    elif comf_class == 3:
        ppd_thresh = 15
    else:
        raise ValueError(
            'Comfort class {} is not an acceptable value. Choose from: 1, 2, 3'
            .format(comf_class))
    return ppd_thresh


def demo():
    """demo is used to demonstrate typical examples about this class."""
    greeting = """
import clubear as cb
#clubear.csv is generated by cb.manager.demo()
sf=cb.shuffle('clubear.csv')
sf.dc() #shuffle by dc method
"""
    print(greeting)
    print('')


@classmethod
def validate_action(cls, action):
    """Verifies the given action is a valid duplicate jar rule action.

        :returns: The action if it is valid.
        :raises: ``ValueError`` if the action is invalid.
        """
    if action not in cls._VALID_ACTIONS:
        raise ValueError(
            'The supplied action must be one of {valid}, given: {given}'.
            format(valid=cls._VALID_ACTIONS, given=action))
    return action


def LowerStr(inString):
    """Returns a lower case string from any string. Useful for argparse types"""
    return inString.lower()


def summult(list1, list2):
    """
Multiplies elements in list1 and list2, element by element, and
returns the sum of all resulting multiplications.  Must provide equal
length lists.

Usage:   lsummult(list1,list2)
"""
    if len(list1) != len(list2):
        raise ValueError('Lists not equal length in summult.')
    s = 0
    for item1, item2 in zip(list1, list2):
        s = s + item1 * item2
    return s


def setup_options(session, args):
    """Sets streamlink options."""
    if args.hls_live_edge:
        session.set_option('hls-live-edge', args.hls_live_edge)
    if args.hls_segment_attempts:
        session.set_option('hls-segment-attempts', args.hls_segment_attempts)
    if args.hls_playlist_reload_attempts:
        session.set_option('hls-playlist-reload-attempts', args.
            hls_playlist_reload_attempts)
    if args.hls_segment_threads:
        session.set_option('hls-segment-threads', args.hls_segment_threads)
    if args.hls_segment_timeout:
        session.set_option('hls-segment-timeout', args.hls_segment_timeout)
    if args.hls_segment_ignore_names:
        session.set_option('hls-segment-ignore-names', args.
            hls_segment_ignore_names)
    if args.hls_timeout:
        session.set_option('hls-timeout', args.hls_timeout)
    if args.hls_audio_select:
        session.set_option('hls-audio-select', args.hls_audio_select)
    if args.hls_start_offset:
        session.set_option('hls-start-offset', args.hls_start_offset)
    if args.hls_duration:
        session.set_option('hls-duration', args.hls_duration)
    if args.hls_live_restart:
        session.set_option('hls-live-restart', args.hls_live_restart)
    if args.hds_live_edge:
        session.set_option('hds-live-edge', args.hds_live_edge)
    if args.hds_segment_attempts:
        session.set_option('hds-segment-attempts', args.hds_segment_attempts)
    if args.hds_segment_threads:
        session.set_option('hds-segment-threads', args.hds_segment_threads)
    if args.hds_segment_timeout:
        session.set_option('hds-segment-timeout', args.hds_segment_timeout)
    if args.hds_timeout:
        session.set_option('hds-timeout', args.hds_timeout)
    if args.http_stream_timeout:
        session.set_option('http-stream-timeout', args.http_stream_timeout)
    if args.ringbuffer_size:
        session.set_option('ringbuffer-size', args.ringbuffer_size)
    if args.rtmp_proxy:
        session.set_option('rtmp-proxy', args.rtmp_proxy)
    if args.rtmp_rtmpdump:
        session.set_option('rtmp-rtmpdump', args.rtmp_rtmpdump)
    if args.rtmp_timeout:
        session.set_option('rtmp-timeout', args.rtmp_timeout)
    if args.stream_segment_attempts:
        session.set_option('stream-segment-attempts', args.
            stream_segment_attempts)
    if args.stream_segment_threads:
        session.set_option('stream-segment-threads', args.
            stream_segment_threads)
    if args.stream_segment_timeout:
        session.set_option('stream-segment-timeout', args.
            stream_segment_timeout)
    if args.stream_timeout:
        session.set_option('stream-timeout', args.stream_timeout)
    if args.ffmpeg_ffmpeg:
        session.set_option('ffmpeg-ffmpeg', args.ffmpeg_ffmpeg)
    if args.ffmpeg_verbose:
        session.set_option('ffmpeg-verbose', args.ffmpeg_verbose)
    if args.ffmpeg_verbose_path:
        session.set_option('ffmpeg-verbose-path', args.ffmpeg_verbose_path)
    if args.ffmpeg_video_transcode:
        session.set_option('ffmpeg-video-transcode', args.
            ffmpeg_video_transcode)
    if args.ffmpeg_audio_transcode:
        session.set_option('ffmpeg-audio-transcode', args.
            ffmpeg_audio_transcode)
    session.set_option('subprocess-errorlog', args.subprocess_errorlog)
    session.set_option('subprocess-errorlog-path', args.
        subprocess_errorlog_path)
    session.set_option('locale', args.locale)


@classmethod
def get_subclass(cls, obj):
    """ Get the subclass to use when instantiating a polymorphic object.
            The default implementation looks at ``cls.config_polymorphic``
            to get the name of an attribute.  Subclasses automatically
            register their value for that attribute on creation via their
            ``config_polymorphic_identity`` field.  This process is then
            repeated recursively until None is returned (indicating that the
            current class is the correct one)

            This method can be overridden to allow any method you would like
            to use to select subclasses. It should return either the subclass
            to use or None, if the original class should be used.
        """
    if cls.config_polymorphic is None:
        return
    value = obj.get(cls.config_polymorphic)
    value = cls._subclasses.get(value)
    if value == cls or value is None:
        return None
    sub_value = value.get_subclass(obj)
    if sub_value is None:
        return value
    return sub_value


def legacy_ids(study_ids):
    """Handle legacy study IDs, returning the new format

    Parameters:
        study_ids: List of study IDs (new or old)

    Returns:
        result: List of new study IDs

    """
    legacy_id_subs = {'UKB-a:': 'ukb-a-', 'UKB-b:': 'ukb-b-', 'UKB-c:':
        'ukb-c-', 'IEU-a:': 'ieu-a-', '\\D': 'ieu-a-'}
    result = []
    for id in study_ids:
        for legacy_id in legacy_id_subs.keys():
            if id.find(legacy_id) >= 0:
                id = id.replace(legacy_id, legacy_id_subs[legacy_id])
        result.append(id)
    return result


def document_contents_callback(key, doc):
    """
    prints document contents -- use for diagnosing a document stream
    """
    print(key)
    for k, v in doc.items():
        print(f'\t{k}\t{v}')


def _translate_header_datapoints(ingredient, dictionary, duplicated):
    """Translating Datapoints.

    1. rename the columns in dataframe
    2. check duplication in the origin data.keys()
    3. rename the key in data.keys()
    """
    data = ingredient.get_data()
    new_data = dict()
    for k in list(data.keys()):
        df_new = data[k].rename(columns=dictionary)
        if k not in dictionary.keys():
            new_data[k] = df_new
            continue
        new_name = dictionary[k]
        if new_name in data.keys():
            if duplicated == 'error':
                raise ValueError(
                    'can not rename indicator {} to {} because {} already exists!'
                    .format(k, new_name, new_name))
            else:
                new_data[new_name] = df_new
        else:
            new_data[new_name] = df_new
    return new_data


def _normalizePath(path):
    """Normalize a path by resolving '.' and '..' path elements."""
    if path == u'/':
        return path
    new_segments = []
    prefix = u''
    if path.startswith('/'):
        prefix = u'/'
        path = path[1:]
    for segment in path.split(u'/'):
        if segment == u'.':
            continue
        if segment == u'..':
            new_segments.pop()
            continue
        if not segment:
            raise ValueError('path must not contain empty segments: %s' % path)
        new_segments.append(segment)
    return prefix + u'/'.join(new_segments)


@classmethod
def _reset_alias(cls):
    """Reset the alias so that it is recomputed the next time an instance
        is created."""
    cls._alias = None


def save_models(models, base_dir):
    """
    save_models: should be a dictionary with tags as keys, models as value
    """
    for model_key, model in models.iteritems():
        model.save('%s/analysis/models/%s.word2vec' % (base_dir, model_key))


def nodes(G, t=None):
    """Return a list of the nodes in the graph at a given snapshot.

            Parameters
            ----------

            G : Graph opject
                DyNetx graph object

            t : snapshot id (default=None)
                If None the the method returns all the nodes of the flattened graph.

            Returns
            -------
            nlist : list
                A list of nodes.  If data=True a list of two-tuples containing
                (node, node data dictionary).

            Examples
            --------
            >>> G = dn.DynGraph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
            >>> G.add_path([0,1,2], 0)
            >>> dn.nodes(G, t=0)
            [0, 1, 2]
            >>> G.add_edge(1, 4, t=1)
            >>> dn.nodes(G, t=0)
            [0, 1, 2]
            """
    return G.nodes(t)


def dump_stats(myStats):
    """
    Show stats when pings are done
    """
    print('\n----%s PYTHON PING Statistics----' % myStats.thisIP)
    if myStats.pktsSent > 0:
        myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd
            ) / myStats.pktsSent
    print(
        '%d packets transmitted, %d packets received, %0.1f%% packet loss' %
        (myStats.pktsSent, myStats.pktsRcvd, 100.0 * myStats.fracLoss))
    if myStats.pktsRcvd > 0:
        print('round-trip (ms)  min/avg/max = %d/%0.1f/%d' % (myStats.
            minTime, myStats.totTime / myStats.pktsRcvd, myStats.maxTime))
    print('')
    return


def check_lat(lat):
    """
    Checks whether the input latitude is within range and correct type

    Parameters
    ----------
    lat : float or int
        latitude (-90 to 90) in degrees

    Returns
    -------
    None. Raises an exception in case
    """
    if isinstance(lat, (int, float)):
        if abs(lat) > 90:
            raise ValueError('latitude should be -90 <= latitude <= 90')
    else:
        raise TypeError('latitude should be "float" or "int"')
    return None


def pCommon():
    """Return a string representing the object's value in the
        format: Mar. 1, 1997 1:45 pm"""


def generate_tag(domain, id, prefix='tag'):
    """Generate tag for given domain and id.

    :param domain: domain string
    :param id: local id
    :param prefix
    """
    return '{}:{}:{}'.format(prefix, domain, id)


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


def getVersionsWithAutomaticTransitions():
    """Get all versions that have outgoing transitions that are automatic.
        """


def writefile_log(output_logfile_name='lauepattern.log', linestowrite=[['']]):
    """
    TODO: maybe useless ?
    """
    filou = open(output_logfile_name, 'w')
    aecrire = linestowrite
    for line in aecrire:
        lineData = '\t'.join(line)
        filou.write(lineData)
        filou.write('\n')
    filou.close()


def selected_toggle():
    """Toggle the Outliner selection of items

    """
    pass


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


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

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


def controls(email):
    """Determine whether this user controls the given email address.

        :param email: The text email address to register.
        :type email: str
        :return: True if the user controls the given email address.
        :rtype: bool
        """


def list_tags_for_resources(ResourceType=None, ResourceIds=None):
    """
    Lists tags for up to 10 health checks or hosted zones.
    For information about using tags for cost allocation, see Using Cost Allocation Tags in the AWS Billing and Cost Management User Guide .
    See also: AWS API Documentation

    :example: response = client.list_tags_for_resources(
        ResourceType='healthcheck'|'hostedzone',
        ResourceIds=[
            'string',
        ]
    )

    :type ResourceType: string
    :param ResourceType: [REQUIRED]
            The type of the resources.
            The resource type for health checks is healthcheck .
            The resource type for hosted zones is hostedzone .

    :type ResourceIds: list
    :param ResourceIds: [REQUIRED]
            A complex type that contains the ResourceId element for each resource for which you want to get a list of tags.
            (string) --

    :rtype: dict
    :return: {
        'ResourceTagSets': [
            {
                'ResourceType': 'healthcheck'|'hostedzone',
                'ResourceId': 'string',
                'Tags': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ]
            },
        ]
    }

    :returns:
    The resource type for health checks is healthcheck .
    The resource type for hosted zones is hostedzone .

    """
    pass


def timestamp_from_datetime(datetime):
    """
        Convert from datetime format to timestamp format
        Input: Time in datetime format
        Output: Time in timestamp format
    """
    return datetime.strftime('%Y-%m-%dT%H:%M:%S.%fZ')


def _dummyProgressCallback(progress):
    """ A callback to indicate progress that does nothing. """
    pass


def _tr_quote(content):
    """Translate lines escaped with a comma: ,"""
    name, _, args = content.partition(' ')
    return '%s("%s")' % (name, '", "'.join(args.split()))


def provider_parser(subparser):
    """Configure provider parser for internetbs"""
    subparser.add_argument('--auth-key', help=
        'specify API key for authentication')
    subparser.add_argument('--auth-password', help=
        'specify password for authentication')


@classmethod
def for_tag(cls, value, validate=True):
    """
        Convert the colour name into a CSS class that can be added to a Tag
        component.

        Args:
            value: the colour.
            validate: check whether the colour is one of the pre-defined
                values. Defaults to True.

        Raises:
            ValueError: if validate is True and the colour is invalid.

        Returns:
            str: the CSS class used to set the tag colour.

        """
    if validate and not cls.is_valid(value):
        raise ValueError('Unexpected colour', value)
    return 'govuk-tag--%s' % value


@classmethod
def export_set(cls, dataset, **kwargs):
    """
        Returns reStructuredText table representation of dataset.

        Returns a simple table if the text in the first column is never
        wrapped, otherwise returns a grid table.

        >>> from tablip import Dataset
        >>> bits = ((0, 0), (1, 0), (0, 1), (1, 1))
        >>> data = Dataset()
        >>> data.headers = ['A', 'B', 'A and B']
        >>> for a, b in bits:
        ...     data.append([bool(a), bool(b), bool(a * b)])
        >>> table = data.rst
        >>> table.split('\\n') == [
        ...     '=====  =====  =====',
        ...     '  A      B    A and',
        ...     '                B  ',
        ...     '=====  =====  =====',
        ...     'False  False  False',
        ...     'True   False  False',
        ...     'False  True   False',
        ...     'True   True   True ',
        ...     '=====  =====  =====',
        ... ]
        True

        """
    if not dataset.dict:
        return ''
    force_grid = kwargs.get('force_grid', False)
    max_table_width = kwargs.get('max_table_width', cls.MAX_TABLE_WIDTH)
    column_widths = cls._get_column_widths(dataset, max_table_width)
    use_simple_table = cls._use_simple_table(dataset.headers[0] if dataset.
        headers else None, dataset.get_col(0), column_widths[0])
    if use_simple_table and not force_grid:
        return cls.export_set_as_simple_table(dataset, column_widths)
    else:
        return cls.export_set_as_grid_table(dataset, column_widths)


def convert_to_float(value_string, parser_info_out=None, suc_return=True):
    """
    Tries to make a float out of a string. If it can't it logs a warning
    and returns True or False if convertion worked or not.

    :param value_string: a string
    :returns value: the new float or value_string: the string given
    :returns: True or False
    """
    if parser_info_out is None:
        parser_info_out = {'parser_warnings': []}
    try:
        value = float(value_string)
    except TypeError:
        parser_info_out['parser_warnings'].append(
            'Could not convert: "{}" to float, TypeError'.format(value_string))
        if suc_return:
            return value_string, False
        else:
            return value_string
    except ValueError:
        parser_info_out['parser_warnings'].append(
            'Could not convert: "{}" to float, ValueError'.format(value_string)
            )
        if suc_return:
            return value_string, False
        else:
            return value_string
    if suc_return:
        return value, True
    else:
        return value


def qpdata_to_fslimage(qpd, grid=None):
    """
    Convert QpData to fsl.data.image.Image
    """
    from fsl.data.image import Image
    if grid is None:
        return Image(qpd.raw(), name=qpd.name, xform=qpd.grid.affine)
    else:
        return Image(qpd.resample(grid), name=qpd.name, xform=grid.affine)


@classmethod
def get_alias(cls, index_name=None):
    """Get the index alias as list."""
    conn = cls.get_connection()
    if not index_name:
        index_name = cls.get_index_name()
    alias_list = conn.indices.get_alias(index_name)
    return list(alias_list[cls.get_index_name()]['aliases'].keys())


def enum(**enums):
    """
        Allows for constant like variables.
    """
    return type('Enum', (), enums)


def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


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

        :param DeviceApprovalsAddExceptionType val:
        :rtype: EventType
        """
    return cls('device_approvals_add_exception', val)


def W_from_rep(data: 'AnnData', rep: str) ->'csr_matrix':
    """
    Return affinity matrix W based on representation rep.
    """
    rep_key = 'W_' + rep
    if rep_key not in data.uns:
        raise ValueError(
            'Affinity matrix does not exist. Please run neighbors first!')
    return data.uns[rep_key]


def make_errline(line, bad_fields=[]):
    """Return an 'error line' indicating problem fields in a string

    Given a tab-delimited line and a list of integer indices
    indicating which fields in the line have problems, this function
    returns a tab-delimited string where the original fields are
    replaced by either spaces or '^' characters.

    When printed beneath the original line, the '^'s indicate which
    fields are 'bad' according to the supplied indices, e.g.

    Input line: 'good    good    bad    bad    good'
    Error line: '                ^^^    ^^^        '

    Arguments:
      line: string where tabs delimit fields
      bad_fields: list of integer indices corresponding to 'bad'
        values in 'line'

    Returns:
      Tab-delimited 'error line' to be printed beneath the original
      line, to indicate which fields are 'bad'.
    """
    errline = []
    items = line.rstrip().split('\t')
    for i in range(len(items)):
        if i in bad_fields:
            errline.append('^' * len(items[i]))
        else:
            errline.append(' ' * len(items[i]))
    return '\t'.join(errline)


def wrap(text, width=80):
    """Wraps text to given width and returns list of lines."""
    lines = []
    for paragraph in text.split('\n'):
        line = []
        len_line = 0
        for word in paragraph.split(' '):
            word.strip()
            len_word = len(word)
            if len_line + len_word <= width:
                line.append(word)
                len_line += len_word + 1
            else:
                lines.append(' '.join(line))
                line = [word]
                len_line = len_word + 1
        lines.append(' '.join(line))
    return lines


@classmethod
def list(cls, session, paginated=False, resource_ids=[], no_deleted=True,
    latest=False):
    """This method is a generator which yields operation objects.

        This resource object list generator handles pagination and takes query
        params for response filtering.

        :param session: The session to use for making this request.
        :type session: :class:`~ecl.session.Session`
        :param bool paginated: ``True`` if a GET to this resource returns
            a paginated series of responses, or ``False``
            if a GET returns only one page of data.
            **When paginated is False only one
            page of data will be returned regardless
            of the API's support of pagination.**
        :param list resource_ids: These arguments are passed as
            resource_id query_string.
        :param bool no_deleted:
            ``True`` You can get operations for only existing resources.
            ``False`` You can get operations for all resources even removed.
        :param bool latest:
            ``True`` You can get only the latest operations for each resource.
            ``False`` You can get all of operations for each resource.
        :return: A generator of :class:`Operation` objects.
        :raises: :exc:`~ecl.exceptions.MethodNotSupported` if
                 :data:`Resource.allow_list` is not set to ``True``.
        """
    more_data = True
    uri = cls.base_path + '?no_deleted=%s&latest=%s' % (str(no_deleted).
        lower(), str(latest).lower())
    list_for_resource_ids = []
    if resource_ids:
        for resource_id in resource_ids:
            list_for_resource_ids.append('resource_id=%s' % resource_id)
    resource_id_query = '&'.join(list_for_resource_ids)
    if len(list_for_resource_ids) > 0:
        uri += '&%s' % resource_id_query
    while more_data:
        resp = session.get(uri, endpoint_filter=cls.service, headers={
            'Accept': 'application/json'})
        resp = resp.json()
        if cls.resources_key:
            resp = resp[cls.resources_key]
        if not resp:
            more_data = False
        yielded = 0
        new_marker = None
        for data in resp:
            data.pop('self', None)
            value = cls.existing(**data)
            new_marker = value.id
            yielded += 1
            yield value
        if not paginated:
            return


@staticmethod
def _get_value(x):
    """This is used when gradients are computed with autograd and the
        objective function is an ArrayBox. Same function as in legume.utils,
        but re-defined here so that this class could also be used independently
        """
    if str(type(x)) == "<class 'autograd.numpy.numpy_boxes.ArrayBox'>":
        return x._value
    else:
        return x


def guess_dtype(data):
    """ Attempt to guess an appropriate dtype for the object, returning None
    if nothing is appropriate (or if it should be left up the the array
    constructor to figure out)
    """
    """
    # todo
    with phil:
        if isinstance(data, h5r.RegionReference):
            return h5t.special_dtype(ref=h5r.RegionReference)
        if isinstance(data, h5r.Reference):
            return h5t.special_dtype(ref=h5r.Reference)
        if type(data) == bytes:
            return h5t.special_dtype(vlen=bytes)
        if type(data) == six.text_type:
           return h5t.special_dtype(vlen=six.text_type)
    """
    return None


def reverse_dict(indict: dict) ->dict:
    """Return a dict containing values of input dict as keys,
    and a set of associated keys as values.

    >>> reverse_dict({1: 2, 3: 2})
    {2: {1, 3}}
    >>> reverse_dict({1: 2, 3: 4})
    {2: {1}, 4: {3}}

    """
    ret = {}
    for key, val in indict.items():
        ret.setdefault(val, set()).add(key)
    return ret


def create_snapshot_from_volume_recovery_point(VolumeARN=None,
    SnapshotDescription=None):
    """
    Initiates a snapshot of a gateway from a volume recovery point. This operation is only supported in the cached volume gateway architecture.
    A volume recovery point is a point in time at which all data of the volume is consistent and from which you can create a snapshot. To get a list of volume recovery point for cached volume gateway, use  ListVolumeRecoveryPoints .
    In the CreateSnapshotFromVolumeRecoveryPoint request, you identify the volume by providing its Amazon Resource Name (ARN). You must also provide a description for the snapshot. When the gateway takes a snapshot of the specified volume, the snapshot and its description appear in the AWS Storage Gateway console. In response, the gateway returns you a snapshot ID. You can use this snapshot ID to check the snapshot progress or later use it when you want to create a volume from a snapshot.
    See also: AWS API Documentation

    Examples
    Initiates a snapshot of a gateway from a volume recovery point.
    Expected Output:

    :example: response = client.create_snapshot_from_volume_recovery_point(
        VolumeARN='string',
        SnapshotDescription='string'
    )

    :type VolumeARN: string
    :param VolumeARN: [REQUIRED]

    :type SnapshotDescription: string
    :param SnapshotDescription: [REQUIRED]

    :rtype: dict
    :return: {
        'SnapshotId': 'string',
        'VolumeARN': 'string',
        'VolumeRecoveryPointTime': 'string'
    }

    :returns:
    (dict) --
    SnapshotId (string) --
    VolumeARN (string) --
    VolumeRecoveryPointTime (string) --

    """
    pass


def variance(x):
    """
    Return the standard variance

    If ``x`` is an uncertain real number, return the
    standard variance.

    If ``x`` is an uncertain complex number, return
    a 4-element sequence containing elements of the
    variance-covariance matrix.

    Otherwise, return 0.

    **Examples**::

        >>> ur = ureal(2.5,0.5,3,label='x')
        >>> variance(ur)
        0.25
        >>> ur.v
        0.25

        >>> uc = ucomplex(1+2j,(.5,.5),3,label='x')
        >>> variance(uc)
        VarianceCovariance(rr=0.25, ri=0.0, ir=0.0, ii=0.25)

    """
    try:
        return x.v
    except AttributeError:
        return 0.0


def p_character_anything(p):
    """character : K_ANYTHING"""
    p[0] = [('anything', ())]


def formula_2012_01_01(foyer_fiscal, period):
    """
        Plafonnement supprimé pour l'année 2012
        """
    isf_ifi_avant_plaf = foyer_fiscal('isf_ifi_avant_plaf', period)
    return isf_ifi_avant_plaf


def align_left(text, length, left_edge='|', right_edge='|', text_length=
    None, left_padding=2):
    """Left align text."""
    if text_length is None:
        text_length = len(text)
    computed_length = text_length + left_padding + len(left_edge) + len(
        right_edge)
    if length - computed_length >= 0:
        padding = left_padding
    else:
        padding = 0
    output = []
    length_so_far = 0
    output.append(left_edge)
    length_so_far += len(left_edge)
    output.append(' ' * padding)
    length_so_far += padding
    output.append(text)
    length_so_far += text_length
    output.append(' ' * (length - length_so_far - len(right_edge)))
    output.append(right_edge)
    return ''.join(output)


def p_echo_expr_list(p):
    """echo_expr_list : echo_expr_list COMMA expr
                      | expr"""
    if len(p) == 4:
        p[0] = p[1] + [p[3]]
    else:
        p[0] = [p[1]]


def delete_initial_category(apps, schema_editor):
    """ Category will be deleted anyway """
    pass


def getTimeout():
    """ Get the timeout value
        """


@classmethod
def help_conll_format(cls):
    """With the help of this method, detail of senna
         arguments are displayed
        """
    return cls.get_conll_format.__doc__.split('\n\n')[1]


def strip_column_and_row_names(raw_dataframe, col_index=None, row_index=None):
    """
    一般第三行为 column name, 第一列为 row name，清洗 行列名。
    :param raw_dataframe: excel 原始数据
    :param col_index: column_name 所在 row index
    :param row_index: row_name 所在 col index
    :return:
    """
    raw_dataframe = raw_dataframe.dropna(axis=1, how='all')
    if col_index is None:
        col_index = 2
    if row_index is None:
        row_index = 0
    raw_dataframe.iloc[col_index] = raw_dataframe.iloc[col_index].apply(lambda
        x: x.replace(' ', '').replace('%', '').replace('(', '').replace(')',
        '') if isinstance(x, str) else x)
    raw_dataframe.iloc[:, (row_index)] = raw_dataframe.iloc[:, (row_index)
        ].apply(lambda x: x.replace(':', '').replace('：', '').replace('-',
        '').replace('——', '') if isinstance(x, str) else x)
    return raw_dataframe


def data_add():
    """Add new Grease Pencil datablock

    """
    pass


def is_valid_ssdp_packet(data: bytes) ->bool:
    """Check if data is a valid and decodable packet."""
    return bool(data) and b'\n' in data and (data.startswith(
        b'NOTIFY * HTTP/1.1') or data.startswith(b'M-SEARCH * HTTP/1.1') or
        data.startswith(b'HTTP/1.1 200 OK'))


@classmethod
def get_document_statuses(cls):
    """
        Method for fetching info about statuses of documents.

        :example:
            ``Common.get_document_statuses()``
        :return:
            dictionary with info about statuses of documents
        :rtype:
            dict
        """
    req = cls.send(method='getDocumentStatuses')
    return req


def decompress_zlib(in_str):
    """
    Uncompresses a zlib string and returns it.

    :Parameters:
        in_str : string
            zlib compressed string

    :returns: uncompressed string
    """
    import zlib
    content = zlib.decompress(in_str)
    return content


def center(number, rjust=4):
    """Center a number string about the decimal."""
    number = str(number)
    split = number.split('.')
    return ''.join((split[0].rjust(4), '.', split[1])) if len(split
        ) > 1 else split[0]


def format_iso8601(obj):
    """Format a datetime object for iso8601"""
    iso8601 = obj.isoformat()
    if obj.tzinfo:
        return iso8601
    return iso8601 + 'Z'


def pretty_bytes(bstr):
    """Return interpretation of bytes suitable for printing/logging."""
    return '[{len}] {repr}'.format(len=len(bstr), repr=repr(bstr))


def indent(s, depth):
    """
    Indent a string of text with *depth* additional spaces on each line.
    """
    spaces = ' ' * depth
    interline_separator = '\n' + spaces
    return spaces + interline_separator.join(s.split('\n'))


def _keys_equal(x, y):
    """
    Returns 'True' if the two keys are equal by the laws of HTTP headers.
    """
    return x.lower() == y.lower()


@staticmethod
def get_range_from_function(function):
    """
        Examines the ranges in PolarizationWCS.axis.function and returns a
        range from 1 to Naxis+1 if the function is defined, else returns
        None. The upper bound of the range is incremented by 1 (refer to
        comments for get_range above)
        """
    if function is not None:
        if function.naxis >= 1:
            return range(1, function.naxis + 1)
        else:
            raise ValueError('Invalid naxis value: {}'.format(function.naxis))
    return None


def check_properties(properties, allowed_properties, resource):
    """Checks the list of properties in the properties variable against the
    property list provided by the allowed_properties variable. If any property
    does not match the properties in allowed_properties, a ValueError is
    raised to prevent unexpected behavior when creating resources.

    properties: The config (as dict) provided by the configuration file
    allowed_properties: A list of strings representing the available params
        for a resource.
    resource: A string naming the resource in question for the error
        message.
    """
    for key in properties.keys():
        if key not in allowed_properties:
            raise ValueError('%s is not a valid property of %s' % (key,
                resource))


def head(list):
    """Returns the first element of the given list or string. In some libraries
this function is named first"""
    for x in list:
        return x


@conf
def common_flags_dmd(conf):
    """
	Set the flags required by *dmd* or *dmd2*
	"""
    v = conf.env
    v.D_SRC_F = ['-c']
    v.D_TGT_F = '-of%s'
    v.D_LINKER = v.D
    v.DLNK_SRC_F = ''
    v.DLNK_TGT_F = '-of%s'
    v.DINC_ST = '-I%s'
    v.DSHLIB_MARKER = v.DSTLIB_MARKER = ''
    v.DSTLIB_ST = v.DSHLIB_ST = '-L-l%s'
    v.DSTLIBPATH_ST = v.DLIBPATH_ST = '-L-L%s'
    v.LINKFLAGS_dprogram = ['-quiet']
    v.DFLAGS_dshlib = ['-fPIC']
    v.LINKFLAGS_dshlib = ['-L-shared']
    v.DHEADER_ext = '.di'
    v.DFLAGS_d_with_header = ['-H', '-Hf']
    v.D_HDR_F = '%s'


@classmethod
def get_identifier(cls, instance):
    """
        Hook to return a description for the current model.

        If there is a choice field 'extra_styles' in the plugins form: try to get plugins identifier via the current
        selected extra style name.
        """
    return instance.label


@classmethod
def parse(cls, reader):
    """returns an ApeTagItem parsed from the given BitstreamReader"""
    item_value_length, read_only, encoding = reader.parse(cls.FORMAT)
    key = []
    c = reader.read_bytes(1)
    while c != b'\x00':
        key.append(c)
        c = reader.read_bytes(1)
    value = reader.read_bytes(item_value_length)
    return cls(encoding, read_only, b''.join(key), value)


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

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

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


@classmethod
def cast(cls, value_type, value, visitor=None, **kwargs):
    """Cast is for visitors where you are visiting some random data
        structure (perhaps returned by a previous ``VisitorPattern.visit()``
        operation), and you want to convert back to the value type.

        This function also takes positional arguments:

            ``value_type=``\\ *RecordType*
                The type to cast to.

            ``value=``\\ *object*

            ``visitor=``\\ *Visitor.Options*
                Specifies the visitor options, which customizes the descent
                and reduction.
        """
    if visitor is None:
        visitor = cls.Visitor(cls.grok, cls.reverse, cls.collect, cls.
            produce, **kwargs)
    return cls.map(visitor, value, value_type)


@staticmethod
def remove_namespace_from_tag_name(tag_name):
    """
        Helper function, removes namespace annotation from tag name.

        :param tag_name: string with tag name.
        """
    return tag_name.split(':')[-1]


def vector_inverse_fft_image_filter(*args, **kwargs):
    """Procedural interface for VectorInverseFFTImageFilter"""
    import itk
    instance = itk.VectorInverseFFTImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


def lcm(a, b):
    """Return the lower common denominator of ``a`` and ``b``"""
    n = 1
    while 1:
        if a * n % b == 0:
            return a * n
        n += 1


def reverseByteOrder(data):
    """Reverses the byte order of an int (16-bit) or long (32-bit) value."""
    byteCount = len(hex(data)[2:].replace('L', '')[::2])
    val = 0
    for i in range(byteCount):
        val = val << 8 | data & 255
        data >>= 8
    return val


def get_dailysummary_iex(*args, **kwargs):
    """
    Returns a summary of daily market volume statistics. Without parameters,
    this will return the most recent trading session by default.

    Parameters
    ----------
    start : string, int, date, datetime, Timestamp
        The beginning of the date range.
    end : string, int, date, datetime, Timestamp
        The end of the date range.

    Reference: https://www.iextrading.com/developer/docs/#historical-daily

    :return: DataFrame
    """
    from pandas_datareader.iex.stats import DailySummaryReader
    return DailySummaryReader(*args, **kwargs).read()


def is_storage_local(storage):
    """
    Check to see if a file storage is local.
    """
    try:
        storage.path('test')
    except NotImplementedError:
        return False
    return True


@classmethod
def accepts_default_mpiprocs_per_machine(cls):
    """
        Return True if this JobResource accepts a 'default_mpiprocs_per_machine'
        key, False otherwise.

        Should be implemented in each subclass.
        """
    raise NotImplementedError


@classmethod
def get_containers(cls, **filters):
    """Return a list of containers

        By default return list of all containers, including non-running
        containers.

        Filtering can be done using filters keys defined in
        podman-ps(1).

        Multiple filters for a given key is handled by giving a list of string
        as value.

        >>> host.podman.get_containers()
        [<podman nginx>, <podman redis>, <podman app>]
        # Get all running containers
        >>> host.podman.get_containers(status="running")
        [<podman app>]
        # Get containers named "nginx"
        >>> host.podman.get_containers(name="nginx")
        [<podman nginx>]
        # Get containers named "nginx" or "redis"
        >>> host.podman.get_containers(name=["nginx", "redis"])
        [<podman nginx>, <podman redis>]
        """
    cmd = "podman ps --all --format '{{.Names}}'"
    args = []
    for key, value in filters.items():
        if isinstance(value, (list, tuple)):
            values = value
        else:
            values = [value]
        for v in values:
            cmd += ' --filter %s=%s'
            args += [key, v]
    result = []
    for podman_id in cls(None).check_output(cmd, *args).splitlines():
        result.append(cls(podman_id))
    return result


def missing_edges(x, y):
    """
	Counts edges that are present in the original structure (x) but
	are missing in the learned structure (y). (lower is better)
	"""
    missing = 0
    for rv in x.nodes():
        if not y.has_node(rv):
            missing += x.degree(rv)
        else:
            for child in x.children(rv):
                if child not in y.children(rv):
                    missing += 1
    return missing


def wrap_line(line, limit=None, chars=80):
    """Wraps the specified line of text on whitespace to make sure that none of the
    lines' lengths exceeds 'chars' characters.
    """
    result = []
    builder = []
    length = 0
    if limit is not None:
        sline = line[0:limit]
    else:
        sline = line
    for word in sline.split():
        if length <= chars:
            builder.append(word)
            length += len(word) + 1
        else:
            result.append(' '.join(builder))
            builder = [word]
            length = 0
    result.append(' '.join(builder))
    return result


def no_translate_debug_logs(logical_line, filename):
    """Check for 'LOG.debug(_('

    As per our translation policy,
    https://wiki.openstack.org/wiki/LoggingStandards#Log_Translation
    we shouldn't translate debug level logs.

    * This check assumes that 'LOG' is a logger.
    * Use filename so we can start enforcing this in specific folders instead
      of needing to do so all at once.

    N319
    """
    if logical_line.startswith('LOG.debug(_('):
        yield 0, "N319 Don't translate debug level logs"


@staticmethod
def can_handle_route(routing_key):
    """ Check if the consumer can handle the given routing key.

            .. note:: the default implementation will handle all routes.

            :param str routing_key: the routing key
        """
    return True


def unpack2(var, pattern, buff):
    """
    Create struct.unpack call for when pattern refers to variable
    :param var: variable the stores the result of unpack call, ``str``
    :param pattern: name of variable that unpack will read from, ``str``
    :param buff: buffer that the unpack reads from, ``StringIO``
    """
    return '%s = struct.unpack(%s, %s)' % (var, pattern, buff)


def get_local_tile_map(tileobj, crawltiles=2, mapsize=5):
    """
    Builds a 2D list of tiles, representing an x/y grid of tiles sorrounding
    the players current position.

    :param text_game_maker.tile.tile.Tile tileobj: starting tile
    :param int crawltiles: maximum tiles to travel from starting tile
    :param int mapsize: map height and width in tiles
    :return: 2D list representing x/y grind of tiles around player
    """
    tilemap = []
    for _ in range(mapsize):
        tilemap.append([None] * mapsize)
    pos = 0, 0
    tilestack = [(tileobj, None, None)]
    seen = []
    movetable = {'north': lambda : (pos[0], pos[1] - 1), 'south': lambda :
        (pos[0], pos[1] + 1), 'east': lambda : (pos[0] + 1, pos[1]), 'west':
        lambda : (pos[0] - 1, pos[1])}
    while tilestack:
        tile, newpos, movedir = tilestack.pop(0)
        if newpos:
            pos = newpos
        if tile in seen:
            continue
        seen.append(tile)
        if movedir:
            x, y = movetable[movedir]()
            pos = x, y
        if -crawltiles <= pos[0] <= crawltiles and -crawltiles <= pos[1
            ] <= crawltiles:
            tilemap[pos[1] + crawltiles][pos[0] + crawltiles] = tile
        for direction in movetable:
            adj = getattr(tile, direction)
            if not adj:
                continue
            tilestack.append((adj, pos, direction))
    return tilemap


def get_build_name(id):
    """ Get build name using id. """
    return 'build-{id}'.format(id=id)


def extract_fastx_comment(header):
    """
    Split FASTA/Q header into name and comment

    :param header: FASTA/Q header line
    :return: name, comment
    :rtype: tuple
    """
    cols = header.replace('\t', ' ').split(' ')
    name = cols[0]
    comment = None
    if len(cols) > 1:
        comment = ' '.join(cols[1:])
    return name, comment


@staticmethod
def _get_binding(bindings, operation_name):
    """
        Get the binding from 'bindings' assosciated with 'operation_name'
        """
    for binding in bindings['Operations']:
        if binding['Name'] == operation_name:
            return binding


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

        :param list of [str] val:
        :rtype: UsersSelectorArg
        """
    return cls('emails', val)


def psi_H_K_Cl_HMW84(T, P):
    """c-c'-a: hydrogen potassium chloride [HMW84]."""
    psi = -0.011
    valid = T == 298.15
    return psi, valid


def get_breadcrumbs(path, base='', topname='.', subarchivepath=None):
    """Generate (label, subpath, sep, is_last) tuples.
    """
    base = base.rstrip('/') + '/'
    subpathfull = path.strip('/')
    if subarchivepath is None:
        archivepath = None
    elif subarchivepath == '':
        archivepath = subpathfull
    else:
        archivepath = subpathfull[0:-(len(subarchivepath) + 1)]
    if subpathfull:
        yield topname, base, '/', False
        subpaths = []
        parts = subpathfull.split('/')
        parts_len = len(parts)
        for idx, part in enumerate(parts):
            subpaths.append(part)
            subpath = '/'.join(subpaths)
            if subpath == archivepath:
                yield part[:-1
                    ], base + subpath + '/', '!/', idx == parts_len - 1
            else:
                yield part, base + subpath + '/', '/', idx == parts_len - 1
    else:
        yield topname, base, '/', True


def sqrt_window_size_threshold_func(window_count):
    """The threshold function for LCU-SWS
    :param window_count: How many windows have appeared so far
    :return: the square root of the windows seen so far as a threshold
    """
    return window_count ** 0.5


def unsubscribe(service, nodeIdentifier, subscriber):
    """
        Unsubscribe from a node with a given JID.

        @param service: The publish-subscribe service entity.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: Identifier of the node to unsubscribe from.
        @type nodeIdentifier: C{unicode}
        @param subscriber: JID to unsubscribe from the node.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


def patch_setuptools_in_rtd():
    """Install newer setuptools and octomachinery in RTD."""
    import os
    import sys
    import subprocess
    if not os.getenv('READTHEDOCS') or os.getenv('READTHEDOCS_EXEC'):
        return
    pyenv_python_executable = subprocess.check_output(('pyenv', 'which',
        'python3.7'), text=True).strip()
    setuptools_update_cmd = (pyenv_python_executable, '-m', 'pip',
        'install', '--force-reinstall', '--cache-dir',
        '/home/docs/checkouts/readthedocs.org/user_builds/octomachinery/.cache/pip'
        , 'setuptools >= 40.9.0')
    pip_update_cmd = (sys.executable, '-m', 'pip', 'install',
        '--force-reinstall', '--cache-dir',
        '/home/docs/checkouts/readthedocs.org/user_builds/octomachinery/.cache/pip'
        , 'pip >= 19.0.3')
    octomachinery_install_cmd = (sys.executable, '-m', 'pip', 'install',
        '--force-reinstall', '--cache-dir',
        '/home/docs/checkouts/readthedocs.org/user_builds/octomachinery/.cache/pip'
        , '..[docs]')
    print('>>>>> Bumping setuptools...', file=sys.stderr)
    subprocess.check_call(setuptools_update_cmd)
    print('>>>>> Bumping pip...', file=sys.stderr)
    subprocess.check_call(pip_update_cmd)
    print('>>>>> Installing octomachinery...', file=sys.stderr)
    subprocess.check_call(octomachinery_install_cmd)
    new_env = dict(os.environ)
    new_env['READTHEDOCS_EXEC'] = 'True'
    print('>>>>> Restarting Sphinx build...', file=sys.stderr)
    print(f"Sphinx build command is `{sys.executable} {' '.join(sys.argv)}`",
        file=sys.stderr)
    os.execve(sys.executable, (sys.executable, *sys.argv), new_env)


def merge_dicts(ds):
    """Merge a sequence of dictionaries."""
    result = {}
    for d in ds:
        for k, v in d.items():
            if k not in result:
                if hasattr(v, 'copy'):
                    result[k] = v.copy()
                else:
                    result[k] = v
            elif hasattr(result[k], 'update'):
                result[k].update(v)
            elif hasattr(result[k], 'extend'):
                result[k].extend(v)
            elif result[k] is None:
                result[k] = v
            elif result[k] == '' and v != '':
                result[k] = v
    return result


def _point_mutation(individual, idx, random_state):
    """Apply a point mutation on individual at position idx

    Args:
        individual: instance of Base
        idx: index
        random_state: an instance of np.random.RandomState

    Returns:
        mutated individual
    """
    el, c, r, lst = individual.mapping[idx]
    gene = lst[r]
    if isinstance(gene, list):
        new_gene = gene[:]
        j = random_state.randint(0, len(gene))
        if j == 0:
            choices = individual.pset.operators[:]
            if len(choices) > 1:
                prim = individual.pset.mapping[gene[j]]
                choices.pop(choices.index(prim))
            new_j = individual.pset.imapping[random_state.choice(choices)]
        else:
            valid_inputs = individual._valid_inputs[idx][:]
            if len(valid_inputs) > 1:
                valid_inputs.pop(valid_inputs.index(gene[j]))
            new_j = random_state.choice(valid_inputs)
        new_gene[j] = new_j
    else:
        new_gene = random_state.randint(0, len(individual) - individual.
            n_out - 1)
    new_individual = individual.clone()
    new_individual[idx] = new_gene
    return new_individual


def merge_flags(cfg1, cfg2):
    """Merge values from cffi config flags cfg2 to cf1

    Example:
        merge_flags({"libraries": ["one"]}, {"libraries": ["two"]})
        {"libraries": ["one", "two"]}
    """
    for key, value in cfg2.items():
        if key not in cfg1:
            cfg1[key] = value
        else:
            if not isinstance(cfg1[key], list):
                raise TypeError('cfg1[%r] should be a list of strings' % (key,)
                    )
            if not isinstance(value, list):
                raise TypeError('cfg2[%r] should be a list of strings' % (key,)
                    )
            cfg1[key].extend(value)
    return cfg1


def index_of_object(alist, obj):
    """Effectively implements list.index(obj) but returns the index of
    the first item in the list that *is* the supplied object (rather than
    comparing values) """
    for idx, body in enumerate(alist):
        if body is obj:
            return idx
    raise Exception('Object {0} not found in list'.format(str(obj)))


def addmany(sequence):
    """Like "for item, score in sequence: self.add(item, score)".

        This is simply faster than calling add() len(seq) times.
        """


def generic_find_uq_constraint_name(table, columns, insp):
    """Utility to find a unique constraint name in alembic migrations"""
    for uq in insp.get_unique_constraints(table):
        if columns == set(uq['column_names']):
            return uq['name']


def fix_format_string(fmt, dimen=1, key_format='_%s'):
    """ Fixes a format string so that it contains dimen slots with %s inside
        arguments are:
         --- dimen is the number of slots we need
         --- key_format is the format in which the %s is embedded. By default '_%s'
             for example if each item has to be surrounded by {} set key_format to _{%s}
    """
    assert dimen >= 1
    actual_nb_slots = 0
    curpos = 0
    str_size = len(fmt)
    while curpos < str_size and actual_nb_slots < dimen:
        new_pos = fmt.find('%', curpos)
        if new_pos < 0:
            break
        actual_nb_slots += 1
        if actual_nb_slots >= dimen:
            break
        curpos = new_pos + 2
    nb_missing = max(0, dimen - actual_nb_slots)
    return fmt + nb_missing * (key_format % '%s')


@classmethod
def get_format_string(cls):
    """See BranchFormat.get_format_string()."""
    return b'Bazaar-NG branch format 5\n'


def product(numbers):
    """Get the product of all the numbers in `numbers`."""
    from combi._python_toolbox import misc_tools
    return misc_tools.general_product(numbers, start=1)


def color_select(deselect: bool=False):
    """Select all Grease Pencil strokes using current color

    :param deselect: Deselect, Unselect strokes
    :type deselect: bool
    """
    pass


def wildcard_in_db(namespace):
    """Return True if a wildcard character appears in the database name."""
    return namespace.find('*') < namespace.find('.')


def iterate_chunks(i, size=10):
    """
    Iterate over an iterator ``i`` in ``size`` chunks, yield chunks.
    Similar to pagination.

    Example::

        >>> list(iterate_chunks([1, 2, 3, 4], size=2))
        [[1, 2], [3, 4]]
    """
    accumulator = []
    for n, i in enumerate(i):
        accumulator.append(i)
        if (n + 1) % size == 0:
            yield accumulator
            accumulator = []
    if accumulator:
        yield accumulator


def _splitDict(inDict, keys):
    """Splits a dictionary into two parts:
    - outDict contains any keys listed in "keys";
      this is returned by the function
    - inDict has those keys removed (this is the dictionary passed in;
      it is modified by this call)
    """
    outDict = {}
    for key in keys:
        if key in inDict:
            outDict[key] = inDict.pop(key)
    return outDict


@classmethod
def _condense_values_by_column(cls, input_df, value_cols, by_cols):
    """
        condense the value_cols by by_cols.
        """
    return input_df.groupby(by=by_cols)[value_cols].first()


def get_length():
    """Returns the number of data items in an interaction center.
        Note, not all data are currently included

        Returns
        -------
            the number of data items in an interaction center
        """
    LENGTH = 7
    return LENGTH


def TransconductanceAmplifierFourPort(G, Zi, Zo, Z0=50.0):
    """TransconductanceAmplifierFourPort
    Four port transconductance amplifier
    @param G float transconductance gain
    @param Zi float or complex input impedance
    @param Zo float or complex output impedance
    @param Z0 (optional) float reference impedance (defaults to 50 ohms)
    @return list of list s-parameter matrix for a transconductance amplifier
    @remark
    The voltage sense element senses the voltage with the plus terminal at port 1
    and and the minus terminal at port 2 shunted with impedance of Zi.

    The current generated by the amplifier enters port 4 and exits port 3 and
    is shunted with Zo.

    """
    S11 = Zi / (Zi + 2.0 * Z0)
    S12 = 2.0 * Z0 / (Zi + 2.0 * Z0)
    S13 = 0
    S14 = 0
    S21 = S12
    S22 = S11
    S23 = 0
    S24 = 0
    S31 = 2.0 * G * Zi * Zo * Z0 / ((Zi + 2.0 * Z0) * (Zo + 2.0 * Z0))
    S32 = -S31
    S33 = Zo / (Zo + 2.0 * Z0)
    S34 = 2.0 * Z0 / (Zo + 2.0 * Z0)
    S41 = S32
    S42 = S31
    S43 = S34
    S44 = S33
    return [[S11, S12, S13, S14], [S21, S22, S23, S24], [S31, S32, S33, S34
        ], [S41, S42, S43, S44]]


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


def getOLAPSource():
    """Return an IOLAPSource providing object."""


def kg2lbs(mass_kg):
    """Convert mass value from kg to lbs"""
    return mass_kg / 0.453592


def is_pull_request(issue):
    """Return True if the given issue is a pull request."""
    return bool(issue.get('pull_request', {}).get('html_url', None))


def snap_cursor_to_selected():
    """Snap cursor to center of selected item(s)

    """
    pass


def golds_to_gold_tuples(docs, golds):
    """Get out the annoying 'tuples' format used by begin_training, given the
    GoldParse objects."""
    tuples = []
    for doc, gold in zip(docs, golds):
        text = doc.text
        ids, words, tags, heads, labels, iob = zip(*gold.orig_annot)
        sents = [((ids, words, tags, heads, labels, iob), [])]
        tuples.append((text, sents))
    return tuples


def print_verbose(string: str, verbose: bool=True):
    """
    Verbosity print.

    :param string: str: String to print.
    :param verbose: bool: Enable or disable verbosity.
        (Default value = True)

    """
    if verbose:
        print(string)


def recursive_index_decode(int_array, max=32767, min=-32768):
    """Unpack an array of integers using recursive indexing.
    :param int_array: the input array of integers
    :param max: the maximum integer size
    :param min: the minimum integer size
    :return the array of integers after recursive index decoding"""
    out_arr = []
    encoded_ind = 0
    while encoded_ind < len(int_array):
        decoded_val = 0
        while int_array[encoded_ind] == max or int_array[encoded_ind] == min:
            decoded_val += int_array[encoded_ind]
            encoded_ind += 1
            if int_array[encoded_ind] == 0:
                break
        decoded_val += int_array[encoded_ind]
        encoded_ind += 1
        out_arr.append(decoded_val)
    return out_arr


def get_neighbor_port(graph, neighbor):
    """
    Function for get port for connector according neighbor listener port.
    :param graph: graph
    :param neighbor: neighbor name
    :return: port number
    """
    test = graph.nodes(data=True)[neighbor]
    try:
        if 'listener' in test:
            for item in test['listener']:
                if 'role' in item:
                    if 'inter-route' in item['role']:
                        return item['port']
                else:
                    raise AttributeError
    except AttributeError:
        raise AttributeError("Listener doesn't contains role!")


def not_(child):
    """Select devices that does not match the given selectors.

    >>> not_(and_(tag('sports'), tag('business')))
    {'not': {'and': [{'tag': 'sports'}, {'tag': 'business'}]}}

    """
    return {'not': child}


def p_comp_if_2(p):
    """comp_if : IF old_test comp_iter"""
    ifs, iters = p[3]
    p[0] = [p[2]] + ifs, iters


def button_start_released(controller):
    """
    Callback function that is triggered, when the start button was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('ACTION:' + str(controller.number) + ':' + controller.name +
        ':Button Start released')


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

        :param DeviceLinkSuccessDetails val:
        :rtype: EventDetails
        """
    return cls('device_link_success_details', val)


@classmethod
def make_key(cls, *args):
    """Helper method to create a valid key provider components as args"""
    return '/'.join(args)


@staticmethod
def actions():
    """Dictionary of actions that can be performed on object

        Returns:
            Dict[str, str]: Dictionary of actions that can be performed on object
        """
    return {'show': 'ckanext_showcase_show', 'update':
        'ckanext_showcase_update', 'create': 'ckanext_showcase_create',
        'delete': 'ckanext_showcase_delete', 'list':
        'ckanext_showcase_list', 'associate':
        'ckanext_showcase_package_association_create', 'disassociate':
        'ckanext_showcase_package_association_delete', 'list_datasets':
        'ckanext_showcase_package_list', 'list_showcases':
        'ckanext_package_showcase_list'}


def pcfg(cfg):
    """
    prints out the config file to the prompt with a nice stagger Look for
    readability

    Args:
        cfg: dict of dict in a heirarcy of  {section, {items, values}}
    """
    for sec in cfg.keys():
        print(repr(sec))
        try:
            for item in cfg[sec].keys():
                print('\t' + item)
                values = cfg[sec][item]
                if type(cfg[sec][item]) == list:
                    out = ', '.join(cfg[sec][item])
                else:
                    out = cfg[sec][item]
                print('\t\t' + repr(out))
        except:
            print('\t recipe')


def nosym(calc, val):
    """https://www.quantum-espresso.org/Doc/INPUT_PW.html#nosym
    """
    assert isinstance(val, bool)


def mark_as_retweet(tweets):
    """
    Mark tweet as retweet seeking a concrete number.

    tweets -- list of strings containing sanitized tweets
    return -- list of strings maked as retweets with the '♻' symbol
    """
    coincidence = []
    for num in enumerate(tweets):
        if '59bcc3ad6775562f845953cf01624225' in num[1]:
            coincidence.append(num[0])
    for coinc in coincidence:
        if coinc + 1 < len(tweets):
            tweets[coinc + 1] = '♻' + tweets[coinc + 1]
    for coinc in reversed(coincidence):
        tweets.pop(coinc)
    return tweets


def candidate_edges(edge_onset_eV: float, max_offset_eV: float,
    primary_subshells_only: bool) ->list:
    """Return a list of edges near the specified edge onset energy.
    """
    pass


@classmethod
def __get(cls, identity, object_id):
    """ Read a single object_id from the device information

        :param identity: The identity block to pull data from
        :param object_id: The specific object id to read
        :returns: The requested data (id, length, value)
        """
    return {object_id: identity[object_id]}


def all_satisfy(condition, lista):
    """ Checks if all the values from the list pass the condition

    :param lista:
    :param condition:
    """
    return all(map(condition, lista))


def formula_2004_01_01(famille, period):
    """
        Prestation d'accueil du jeune enfant
        """
    paje_base = famille('paje_base', period)
    paje_naissance = famille('paje_naissance', period)
    paje_clca = famille('paje_clca', period)
    paje_cmg = famille('paje_cmg', period)
    paje_colca = famille('paje_colca', period)
    return paje_base + (paje_naissance + paje_clca + paje_cmg + paje_colca)


@staticmethod
def evaluate(x, z):
    """One dimensional RedshiftScaleFactor model function"""
    return (1 + z) * x


def convert_slice_nones_to_ints(slice_item, target_length):
    """
    Converts None types within a slice to the appropriate ints based on object
    to be sliced.

    The one case where a None is left in the slice object is when the step is negative and
    the stop parameter is None, since this scenario cannot be represented with an int stop
    parameter.

    Parameters
    ----------
    slice_item: `slice`
       Slice for which Nones should be converted.

    target_length: `int`
        Length of object to which slice will be applied.

    Returns
    -------
    new_slice: `slice`
        Slice with Nones replaced with ints.
    """
    if slice_item.step is None:
        step = 1
    else:
        step = slice_item.step
    start = slice_item.start
    stop = slice_item.stop
    if step < 0:
        if slice_item.start is None:
            start = int(target_length)
        stop = slice_item.stop
    else:
        if not slice_item.start:
            start = 0
        if not slice_item.stop:
            stop = int(target_length)
    return slice(start, stop, step)


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

    :type operation_name: string
    :param operation_name: The operation name. This is the same name
            as the method name on the client. For example, if the
            method name is create_foo, and you'd normally invoke the
            operation as client.create_foo(**kwargs), if the
            create_foo operation can be paginated, you can use the
            call client.get_paginator('create_foo').

    """
    pass


def ReinhardHDR(x):
    """
		Reinhard Tonemapping formula. Domain must be within [0, 1].
		"""
    return x / (1.0 + x)


@staticmethod
def runWorkflows(runtime, ert):
    """:type res.enkf.enum.HookRuntimeEnum"""
    hook_manager = ert.getHookManager()
    hook_manager.runWorkflows(runtime, ert)


def complement(seq):
    """returns the complementary sequence without inversing it"""
    tb = str.maketrans('ACGTRYMKWSBDHVNacgtrymkwsbdhvn',
        'TGCAYRKMWSVHDBNtgcayrkmwsvhdbn')
    return str(seq).translate(tb)


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


def get_doi_url(pid):
    """Return the badge for a DOI."""
    return 'https://doi.org/{pid.pid_value}'.format(pid=pid)


def pythonize_path(path: str) ->str:
    """ Replaces argument to valid python dotted notation.

    ex. foo/bar/baz -> foo.bar.baz

    :param str path: path to pythonize
    :return str: pythonized path
    """
    return path.replace('/', '.')


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

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

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


def enable_validate_slicecount():
    """
    Enable the validation of the minimal slice count of 4 slices again (DEFAULT ENABLED)
    """
    global validate_slicecount
    validate_slicecount = True


def commit():
    """Commits changes for transaction capable ICacheAreas"""


def box_aspect(ax, aspect=1):
    """
    Adjust figure size to axes size in inches
    Parameters: aspect: float, optional aspect ratio

    """
    position = ax.get_position()
    fig_width, fig_height = ax.get_figure().get_size_inches()
    fig_aspect = fig_height / fig_width
    pb = position.frozen()
    pb1 = pb.shrunk_to_aspect(aspect, pb, fig_aspect)
    ax.set_position(pb1)


def get_job_source(cursor, name):
    """
    Retrieve the id of a job_source by its name.
    """
    query = 'SELECT id FROM system.job_source WHERE name=%s'
    args = name,
    cursor.execute(query, args)
    if cursor.rowcount == 1:
        datasource_id, = cursor.fetchone()
        return datasource_id


def dequote(string):
    """Remove quotes from around a string."""
    if string.startswith('"') and string.endswith('"') or string.startswith("'"
        ) and string.endswith("'"):
        return string[1:-1]
    else:
        return string


def create(overwrite=False):
    """Create a new layout under ``sitepath``. Subsequently users will add
        content under ``sitepath`` which can then be translated to static
        web-site. Corresponds directly with `create` sub-command from pagd
        command line script.
        """


def writeDensity(temp, model):
    """Main collider densities."""
    temp.append('void density(double x, double y,')
    temp.append('double z, double *density) {\n\n')
    for i, val in enumerate(model.rescaledens):
        temp.append('\tdensity[%d] = %.2f *' % (i, val))
        temp.append(' findvalue(x, y, z, dens);\n')
        temp.append('\tif (density[%d] < 1e3)' % i)
        temp.append(' {\n\t\tdensity[%d] = 1e3;\n\t}\n\n' % i)
    temp.append('}\n\n\n')
    return


def cross_sections_info(cross_sections, logging=None):
    """Log basic info from cross-sections dict.

    Args:
        cross_sections (dict): The keys 'energy', 'citation',
            'link' and 'warning' are checked for relevant information

        logging (module): Active logging module from Python standard
            library. If None, logging will be set up.

    Returns:
        module:
            Active logging module from Python standard library

    """
    if logging is None:
        import logging
        logging.basicConfig(filename='galore.log', level=logging.INFO)
        console = logging.StreamHandler()
        logging.getLogger().addHandler(console)
    if 'energy' in cross_sections:
        logging.info('  Photon energy: {0}'.format(cross_sections['energy']))
    if 'citation' in cross_sections:
        logging.info('  Citation: {0}'.format(cross_sections['citation']))
    if 'link' in cross_sections:
        logging.info('  Link: {0}'.format(cross_sections['link']))
    return logging


def describe_upload_buffer(GatewayARN=None):
    """
    Returns information about the upload buffer of a gateway. This operation is supported for the stored volume, cached volume and tape gateway architectures.
    The response includes disk IDs that are configured as upload buffer space, and it includes the amount of upload buffer space allocated and used.
    See also: AWS API Documentation

    Examples
    Returns information about the upload buffer of a gateway including disk IDs and the amount of upload buffer space allocated/used.
    Expected Output:
    Returns information about the upload buffer of a gateway including disk IDs and the amount of upload buffer space allocated and used.
    Expected Output:

    :example: response = client.describe_upload_buffer(
        GatewayARN='string'
    )

    :type GatewayARN: string
    :param GatewayARN: [REQUIRED]
            The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation to return a list of gateways for your account and region.

    :rtype: dict
    :return: {
        'GatewayARN': 'string',
        'DiskIds': [
            'string',
        ],
        'UploadBufferUsedInBytes': 123,
        'UploadBufferAllocatedInBytes': 123
    }

    """
    pass


@classmethod
def parse_args(cls, subparsers):
    """Create the `files` subparser for the `restore` command.
        :param subparsers: Main argument parser
        """
    fs_parser = subparsers.add_parser(cls.command, description=cls.__doc__)
    fs_parser.add_argument('input', help='.tar.gz file to restore from')


def getAllMetaAttributes():
    """
    Function generating a script to extract all meta attributes of a web page.

    @return script to extract meta attributes
    @rtype str
    """
    source = """
(function() {
    var out = [];
    var meta = document.getElementsByTagName('meta');
    for (var i = 0; i < meta.length; ++i) {
        var e = meta[i];
        out.push({
            name: e.getAttribute('name'),
            content: e.getAttribute('content'),
            httpequiv: e.getAttribute('http-equiv'),
            charset: e.getAttribute('charset')
        });
    }
    return out;
})()"""
    return source


def optimal_block_count(minblkct):
    """Return the optimal block count for a CUDA kernel launch.
    """
    return min(16, max(1, minblkct))


@classmethod
def handle_cursor(cls, cursor, query, session):
    """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
    pass


def plot_dist_frequenza(distribuzione, tipo='categoriale', Y='Percentuale',
    x_label='Valori', y_label='Percentuale', figsize=(12, 8), missing=None):
    """
    distribuzione: inserire risultato della funzione dist_frequenza
    tipo:
        "categoriale": classi non ordinate
        "ordinale": classi ordinate
        "cardinale": valori numerici
    x_label: etichetta asse x
    y_label: etichetta_asse y
    """
    import matplotlib.pyplot as plt
    import seaborn as sns
    if tipo == 'categoriale':
        p_color = 'muted'
    elif tipo == 'ordinale':
        p_color = 'Blues_d'
    elif tipo == 'cardinale':
        p_color = 'Blues_d'
        print(
            '------------------------------------------------------------------------------'
            )
        print(
            'si consiglia di utilizzare una diversa visualizzazione: cerca sul motore di ricerca sns.distplot ed applicalo sulla matrice dati originaria '
            )
        print(
            '------------------------------------------------------------------------------'
            )
    distribuzione = distribuzione.iloc[:-1, :]
    if missing != None:
        distribuzione = distribuzione.drop(missing)
    fig, ax = plt.subplots(figsize=figsize)
    x = 0
    g = sns.barplot(x=distribuzione.index, y=Y, data=distribuzione, ax=ax,
        palette=p_color, order=distribuzione.index)
    for index, row in distribuzione.iterrows():
        stringa = 'N.{},\n {}%'.format(row.Frequenze, row.Percentuale)
        g.text(x, row[Y] - row[Y] * 0.5, stringa, color='black', ha='center')
        x = x + 1
    g.set_xticklabels(g.get_xticklabels(), rotation=90)
    g.set(xlabel=x_label, ylabel=y_label)
    return g


@classmethod
def less_than(cls, a):
    """Returns interval of all values less than the given value

        Returns an interval containing all values less than a.  If closed
        is True, then all values less than or equal to a are returned.

        >>> print Interval.less_than(32)
        (...32)
        """
    return cls(upper_bound=a, upper_closed=False)


@classmethod
def Filesearch(cls, _file_, _path_='C:'):
    """
        Return a list with all the files with the specified name in the specified path.
        """
    import os
    _path_ = _path_ + '\\'
    _result = []
    for RootDir, _Fldrs_, _FlsSrch_ in os.walk(_path_):
        for __files__ in _FlsSrch_:
            if __files__ == _file_:
                __pth = RootDir + '\\' + __files__
                _result.append(__pth)
    return _result


def get_code_point(char: str) ->str:
    """
    Get Character unicode codepoint

    Args:
        char (str): single character

    Returns:
        str

    """
    return '%04x' % ord(char)


@classmethod
def probe_enable(cls, resource):
    """ Activate a probe on a webaccelerator """
    oper = cls.call('hosting.rproxy.probe.enable', cls.usable_id(resource))
    cls.echo('Activating probe on %s' % resource)
    cls.display_progress(oper)
    cls.echo('The probe have been activated')
    return oper


def _parse_known_args(p, *args, **kwargs):
    """_parse_known_args wraps argparse.ArgumentParser._parse_known_args
        to trigger defered functions once after parsing."""
    res = super()._parse_known_args(*args, **kwargs)
    fns = p.callbacks or []
    p.callbacks = None
    for fn in fns:
        fn()
    return res


def c2f(temp_in_celsius=None):
    """
    Convert farenheit to celsius
    """
    return temp_in_celsius * 9.0 / 5.0 + 32


@classmethod
def from_mapping(cls, x0, x1):
    """ Create an STTransform from the given mapping

        See `set_mapping` for details.

        Parameters
        ----------
        x0 : array-like
            Start.
        x1 : array-like
            End.

        Returns
        -------
        t : instance of STTransform
            The transform.
        """
    t = cls()
    t.set_mapping(x0, x1)
    return t


def tokenize_ensembl(anno, keep_unknown=True):
    """
    Take an Ensembl annotation loaded from json and extract the domains, like
    words in a document. Collapse the double strand into one string of domains.

    Omit all domains that are not on the chromosome, e.g. plasmids such
    as p3ABAYE. The GTDB omits plasmids, bc/ they behave differently from the
    chromosome and follow their own "life history" (think the selfish gene).

    Return the assembly ID and a dict of contigs (keys) and associated
    domains (values), the latter linearly ordered. If <keep_unknown>, ORFs
    without Pfam annotations will receive the "unknown" label.
    """
    from collections import defaultdict
    genome = anno['assembly']['accession']
    d = {}
    for g in anno['genes']:
        start = int(g['start'])
        end = int(g['end'])
        strand = g['strand']
        try:
            contig = g['ENA_FEATURE_GENE'][0].split(':')[0]
        except KeyError:
            contig = 'NA'
        uid = contig, start, end
        try:
            domains = g['Pfam']
        except KeyError:
            if keep_unknown:
                domains = ['unknown']
            else:
                pass
        if contig != 'NA':
            d[uid] = domains
    result = defaultdict(list)
    for k, v in sorted(d.items()):
        result[k[0]].extend(v)
    return genome, result


def replace_string(string_value, replace_string, start, end):
    """
    Replaces one string by another
    :param string_value: str, string to replace
    :param replace_string: str, string to replace with
    :param start: int, string index to start replacing from
    :param end: int, string index to end replacing
    :return: str, new string after replacing
    """
    first_part = string_value[:start]
    second_part = string_value[end:]
    return first_part + replace_string + second_part


def validate_int_or_percentage(value):
    """Check if value is either a positive integer (less than 9999) or
    a percetage.

    :param value: number to be validated
    :type value: string
    :returns: True if value is valid
    :rtype: bool
    """
    try:
        return 0 < int(value) <= 9999
    except ValueError:
        if value.endswith('%'):
            try:
                return 0 < int(value[:-1]) <= 100
            except ValueError:
                return False
        return False


def to_bit(val):
    """Convert val to a bit: either 1 if val evaluates to True, or False otherwise."""
    return 1 if val else 0


def return_sign(i, m, n, r):
    """
        Helper function, creates a three-piece step function

        :param i: Value to compare
        :type i: int
        :param m: Middle value
        :type m: int
        :param n: Left extreme value
        :type n: int
        :param r: Right extreme value
        :type r: int

        :returns: int -- Three-piece sign
    """
    if i <= n - m:
        return 1
    elif i <= r:
        return 0
    else:
        return -1


def arctanh(data=None, out=None, name=None, **kwargs):
    """Returns the element-wise inverse hyperbolic tangent of the input array, \\
    computed element-wise.

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

       - arctanh(default) = default
       - arctanh(row_sparse) = row_sparse
       - arctanh(csr) = csr

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

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

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

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


def batch(qs, batch_size=1000):
    """
    Returns a ( start, end, total, queryset ) tuple for each batch in the given
    queryset.

    Usage:
        # Make sure to order your querset
        article_qs = Article.objects.order_by('id')
        for start, end, total, qs in batch_qs(article_qs):
            print "Now processing %s - %s of %s" % (start + 1, end, total)
            for article in qs:
                print article.body
    """
    total = qs.count()
    for start in range(0, total, batch_size):
        end = min(start + batch_size, total)
        yield start, end, total, qs[start:end]


def calculate_inline_block_non_replaced_normal_flow_width(node, context):
    """Implements S10.3.9"""
    raise NotImplementedError('Section 10.3.9')


def rate(rating):
    """Rate the current object with `rating`.
        """


def is_intersecting(trace, dt1, dt2, timestamp_key):
    """
    Check if a trace is intersecting in the given interval

    Parameters
    -----------
    trace
        Trace to check
    dt1
        Lower bound to the interval
    dt2
        Upper bound to the interval
    timestamp_key
        Timestamp attribute

    Returns
    -----------
    boolean
        Is true if the trace is contained
    """
    if trace:
        condition1 = dt1 < trace[0][timestamp_key].replace(tzinfo=None) < dt2
        condition2 = dt1 < trace[-1][timestamp_key].replace(tzinfo=None) < dt2
        condition3 = trace[0][timestamp_key].replace(tzinfo=None
            ) < dt1 < trace[-1][timestamp_key].replace(tzinfo=None)
        condition4 = trace[0][timestamp_key].replace(tzinfo=None
            ) < dt2 < trace[-1][timestamp_key].replace(tzinfo=None)
        if condition1 or condition2 or condition3 or condition4:
            return True
    return False


def copy_data_path_button(full_path: bool=False):
    """Copy the RNA data path for this property to the clipboard

    :param full_path: full_path, Copy full data path
    :type full_path: bool
    """
    pass


def gcd2(a, b):
    """Greatest common divisor using Euclid's algorithm."""
    while a:
        a, b = b % a, a
    return b


@staticmethod
def to_romer(celsius):
    """ Convert celsius to romer """
    return celsius * 21 / 40 + 7.5


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


def formatted_time(t, sep=' '):
    """Return a number of seconds as a string in days, hours, mins and
    maybe secs."""
    t = int(t)
    fmts = ('{:d}d', 86400), ('{:02d}h', 3600), ('{:02d}m', 60)
    parts = []
    for fmt, n in fmts:
        val = t // n
        if parts or val:
            parts.append(fmt.format(val))
        t %= n
    if len(parts) < 3:
        parts.append('{:02d}s'.format(t))
    return sep.join(parts)


def __nonzero__():
    """Always returns True."""
    return True


def make_source_str(layer_name):
    """
    Create a string value representing a Python list of source layers

    Parameters
    ----------
    layer_name : string
       List of Python layer names

    Returns
    -------
    string
        String representation of list of Python layer names

    """
    source_str = []
    for ii in range(len(layer_name)):
        source_str.append(layer_name[ii])
    return repr(source_str)


def callFromThread(callable, *args, **kw):
    """
        Cause a function to be executed by the reactor thread.

        Use this method when you want to run a function in the reactor's thread
        from another thread.  Calling L{callFromThread} should wake up the main
        thread (where L{reactor.run()<reactor.run>} is executing) and run the
        given callable in that thread.

        If you're writing a multi-threaded application the C{callable} may need
        to be thread safe, but this method doesn't require it as such. If you
        want to call a function in the next mainloop iteration, but you're in
        the same thread, use L{callLater} with a delay of 0.
        """


def mjd(year, month, day, hour=0, minute=0, second=0):
    """
    Calculate the modified Julian date from an ordinary date and time.

    Notes
    -----
    The formulas are taken from Wikipedia.

    Example
    -------
    >>> mjd(2000, 1, 1)
    51544.0
    """
    a = (14 - month) // 12
    y = year + 4800 - a
    m = month + 12 * a - 3
    jdn = day + (153 * m + 2
        ) // 5 + 365 * y + y // 4 - y // 100 + y // 400 - 32045
    jd = jdn + (hour - 12) / 24.0 + minute / 1400.0 + second / 86400.0
    mjd = jd - 2400000.5
    return mjd


def has_method(obj, name):
    """
    Check if function 'name' was defined in obj.
    """
    return callable(getattr(obj, name, None))


def debug_trace():
    """Set a tracepoint in the Python debugger that works with Qt"""
    from PyQt4.QtCore import pyqtRemoveInputHook
    from pudb import set_trace
    pyqtRemoveInputHook()
    set_trace()


@classmethod
def _eager_b(cls, eager):
    """
        Builds the provided list of eager values, preparing them
        according to the current model rules.

        The composition process includes the extension of the provided
        sequence of eager values with the base ones defined in the
        model, if not handled correctly this is an expensive operation.

        :type eager: List/Tuple
        :param eager: The base sequence containing the various fields
        that should be eagerly loaded for the operation.
        :rtype: Tuple
        :return: The "final" resolved tuple that may be used for the eager
        loaded operation performance.
        """
    eager = list(eager) if eager else []
    eagers = cls.eagers()
    eager.extend(eagers)
    if not eager:
        return eager
    eager = tuple(set(eager))
    return eager


def _get_testname(test_path):
    """Get test name out of full test path."""
    path_end = test_path.find('.py/')
    if path_end:
        offset = path_end + 4
        return test_path[offset:]
    return None


def from_string(unicode_string):
    """
    Converts the given String to a byte array.

    :param unicode_string: The String to be converted to a byte array.
    :return: A byte array representing the String.
    """
    result = None
    if unicode_string is not None:
        result = bytearray(unicode_string.encode('utf-8'))
    return result


def intersect_incomparable_lists(superset, subset, name_map: dict) ->list:
    """
    Function for identifying the intersection of two lists by
    using a proxy identifier (alt_name) for elements in superset.

    :param superset: A list or set of strings
    :param subset: A list or set of strings
    :param name_map: A dictionary whose keys are in superset and values are in subset
    :return: A list of strings that are in both superset and subset
    """
    intersection = list()
    for seq_name in superset:
        alt_name = name_map[seq_name]
        if alt_name in subset:
            intersection.append(seq_name)
    return intersection


def parse_args(args):
    """Separate script and command args

    :param args: script args
    :return: tuple(['script args'],['command', 'names', 'and commands args'])
    """
    index = None
    for i, arg in enumerate(args):
        if not arg.startswith('-'):
            index = i
            break
    if index is None:
        return args, []
    return args[:index], args[index:]


@staticmethod
def split_us(unique_uid, heldout_us_val=1, heldout_us_test=1):
    """
        Split the users into three different sets
        ---------------------
        :param unique_uid: num of unique user_ids
        :param heldout_us_val: num of user to keep in val_set
        :param heldout_us_test: num of user to keep in test_set
        :return tr_us: users used in tr_set
        :return val_us: users used in val_set
        :return test_us: users used in test_set
        """
    n_us = unique_uid.size
    assert isinstance(heldout_us_val, int), """Error in Framework configuration.
 The heldout_us_val parameter in cfg.JSON must be an integer greater than 0."""
    assert heldout_us_val <= int(0.5 * n_us), """Error in Framework configuration.
The heldout_us_val parameter in cfg.JSONis too much high. Reduce it"""
    assert heldout_us_val > 0, """Error in Framework configuration.
 The heldout_us_val parameter in cfg.JSON must be an integer greater than 0."""
    assert isinstance(heldout_us_test, int), """Error in Framework configuration.
 The heldout_us_test parameter in cfg.JSON must be an integer greater than 0."""
    assert heldout_us_test <= int(0.5 * n_us), """Error in Framework configuration.
The heldout_us_test parameter in cfg.JSONis too much high. Reduce it"""
    assert heldout_us_test > 0, """Error in Framework configuration.
 The heldout_us_val parameter in cfg.JSON must be an integer greater than 0."""
    tr_us = unique_uid[:n_us - heldout_us_val - heldout_us_test]
    val_us = unique_uid[n_us - heldout_us_val - heldout_us_test:n_us -
        heldout_us_test]
    test_us = unique_uid[n_us - heldout_us_test:]
    return tr_us, val_us, test_us


def next_id(prev_id):
    """Generate next lexical id.

    Increments by one and adds padding if required.

    >>> next_id("0098")
    '0099'
    >>> next_id("0099")
    '0100'
    >>> next_id("0999")
    '11000'
    >>> next_id("11000")
    '11001'
    """
    num_digits = len(prev_id)
    if prev_id.count('9') == num_digits:
        raise OverflowError('max lexical version reached: ' + prev_id)
    _prev_id_val = int(prev_id, 10)
    _maybe_next_id_val = int(_prev_id_val) + 1
    _maybe_next_id_str = '{0:0{1}}'.format(_maybe_next_id_val, num_digits)
    _is_padding_ok = prev_id[0] == _maybe_next_id_str[0]
    _next_id_str = None
    if _is_padding_ok:
        _next_id_str = _maybe_next_id_str
    else:
        _next_id_str = str(_maybe_next_id_val * 11)
    return _next_id_str


def is_hero_type(page):
    """Method to check if page belongs to a hero or creep-hero(Warlock's Golem).

    :param page: Page name as string.
    :return: True if page belongs to hero else False
    """
    return '/Responses' in page


def clear(zelf):
    """ clear the ready flag. """
    zelf._ready.clear()


def check_int_zero_one(input_param):
    """Judge whether it is 0 or 1."""
    if input_param in (0, 1):
        return input_param
    raise ValueError('The data must be 0 or 1.')


def dump_class_dummy(target: object, indent: int=0, no_print: bool=False
    ) ->str:
    """Pseudo implementation of DumpClassCallback outputs and returns nothing.

    Parameters
    ----------
    target: object
    indent: int
    no_print: bool

    Returns
    -------
    str
        Always empty string

    """
    return ''


def p_item_list(t):
    """item : list NEWLINE"""
    if len(t[1]) == 1:
        t[0] = t[1][0]
    else:
        t[0] = t[1]


@classmethod
def from_bytes(cls, input, **structure_kwargs):
    """ Create an header structure from PDS-compliant data.

        Parameters
        ----------
        input : bytes, str or unicode
            A string or bytes containing the data for header.
        structure_kwargs :  dict, optional
            Keywords that are passed directly to the `HeaderStructure` constructor.

        Returns
        -------
        HeaderStructure
            An object representing the PDS4 header structure. The data attribute will contain *input*.
            Other attributes may be specified via *structure_kwargs*.
        """
    from .read_headers import new_header
    return new_header(input, **structure_kwargs)


def reflow_paragraph(text, space, leading_space=''):
    """
    Reflow a flattened paragraph so it fits inside horizontal
    space
    """
    words = text.split(' ')
    growing_string = leading_space
    output_list = []
    while len(words) > 0:
        if growing_string == leading_space:
            growing_string += words[0]
            words.pop(0)
        elif len(growing_string + ' ' + words[0]) <= space:
            growing_string += ' ' + words[0]
            words.pop(0)
        else:
            output_list.append(growing_string + '\n')
            growing_string = leading_space
    output_list.append(growing_string)
    return ''.join(output_list)


def Int2AP(num):
    """string = Int2AP(num)
    Return 'num' converted to a string using characters from the set 'A'..'P'
    """
    val, a2p = [], 'ABCDEFGHIJKLMNOP'
    num = int(abs(num))
    while num:
        num, mod = divmod(num, 16)
        val.insert(0, a2p[mod])
    return ''.join(val)


def list_first(rs):
    """Get the first item in a list, or None if list empty."""
    return rs[0] if len(rs) == 1 else None


def cplx01_f(z, n, a):
    """z**n-a:  Use to find the n-th root of a"""
    return z ** n - a


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

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

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


@staticmethod
def combine_results_and_polls(results, polls):
    """Merge national polling, and geo-level polling if available, into results dataframe."""
    results = results.merge(right=polls.query('geo == "uk"')[['party',
        'voteshare']].rename(columns={'voteshare': 'national_polls'}), on=
        'party', how='outer').sort_values(['ons_id', 'party']).reset_index(drop
        =True)
    if set(polls.geo.unique()) != {'uk'}:
        results = results.merge(right=polls.query('geo != "uk"')[['geo',
            'party', 'voteshare']].rename(columns={'voteshare': 'geo_polls'
            }), on=['geo', 'party'], how='outer').sort_values(['ons_id',
            'party']).reset_index(drop=True)
    return results


def expand_tabs(line: str) ->str:
    """
    Tabs are treated as 1-8 spaces according to
    https://docs.python.org/3/reference/lexical_analysis.html#indentation

    Given a string with tabs, this removes all tab characters and replaces them with the
    appropriate number of spaces.
    """
    result_list = []
    total = 0
    for ch in line:
        if ch == '\t':
            prev_total = total
            total = (total + 8) // 8 * 8
            result_list.append(' ' * (total - prev_total))
        else:
            total += 1
            result_list.append(ch)
    return ''.join(result_list)


def get_fee_fraction(db, feed_address):
    """Get fee fraction from last broadcast from the feed_address address.
    """
    cursor = db.cursor()
    broadcasts = list(cursor.execute(
        'SELECT * FROM broadcasts WHERE (status = ? AND source = ?) ORDER BY tx_index ASC'
        , ('valid', feed_address)))
    cursor.close()
    if broadcasts:
        last_broadcast = broadcasts[-1]
        fee_fraction_int = last_broadcast['fee_fraction_int']
        if fee_fraction_int:
            return fee_fraction_int / 100000000.0
        else:
            return 0
    else:
        return 0