def dictmerge(dict1, dict2):
    """
    Merge the contents of the two dicts.
    If they have keys in common, the value in dict1 is overwritten
    by the value in dict2

    >>> a, b = {'A': 1, 'B': 2}, {'B': 20, 'C': 30}

    >>> dictmerge(a, b) == {'A': 1, 'B': 20, 'C': 30}
    True
    """
    out = dict1.copy()
    out.update(dict2)
    return out


def validate_key_attr(key_attr, table, table_label):
    """Check if the attribute is a valid key attribute."""
    unique_flag = len(table[key_attr].unique()) == len(table)
    nan_flag = sum(table[key_attr].isnull()) == 0
    if not (unique_flag and nan_flag):
        raise AssertionError("'" + key_attr + "' is not a key attribute " +
            'in ' + table_label)
    return True


def load_identity():
    """Empty stack and set to identity.

    """
    pass


def remove_doubles(threshold: float=0.0001, use_unselected: bool=False):
    """Merge vertices based on their proximity

    :param threshold: Merge Distance, Minimum distance between elements to merge
    :type threshold: float
    :param use_unselected: Unselected, Merge selected to other unselected vertices
    :type use_unselected: bool
    """
    pass


def _map(func, kw_gen):
    """Map a function over arguments

    Notes
    -----
    builtin map does not allow for mapping with kwargs.

    Parallel uses of block decomposition will likely replace this method with
    one which can distribute compute.
    """
    for kwargs in kw_gen:
        yield func(**kwargs)


def check_storage_cap_ini_max(df):
    """Initial capacity cannot be greater than the maximum capacity.
    Otherwise, a ValueError is raised."""
    if any(df['cap_ini'] > df['cap_max']):
        raise ValueError(
            f"Initial capacity of storages {df[df['cap_ini'] > df['cap_max']].index.to_list()} is greater than the maximum capacity"
            )


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


def cb_init_hook(optname, value):
    """exec arbitrary code to set sys.path for instance"""
    exec(value)


def openProject(simplaceInstance, solution, project=None):
    """Create a project from the solution and optional project file."""
    simplaceInstance.prepareSession(project, solution)


def select_less():
    """Deselect those bones at the boundary of each selection region

    """
    pass


@classmethod
def launch_instance(cls, argv=None, **kwargs):
    """Launch a global instance of this Application

        If a global instance already exists, this reinitializes and starts it
        """
    app = cls.instance(**kwargs)
    app.initialize(argv)
    app.start()


def taxon_rank(name, database=None):
    """
    Make a taxon rank

    :param name: [Array] A taxonomic name
    :param database: [String] A database name

    :return: A dict

    Usage::

        from pytaxa import constructors as cs
        cs.taxon_rank("species")
        cs.taxon_rank("genus", "ncbi")
    """
    return {'name': name, 'database': database}


def list_sync(api, instance='', **params):
    """
    list all the communities of an instance. If no instance is provided , all the communities

    Args:
        api: the ApiClient instance to use for requests
        instance: the instance id
        **params: optional  dictionary of search parameters as defined in https://api.lumapps.com/docs/community/list

    Returns: list of Lumapps Community resources
    """
    if not params:
        params = dict()
    if not params.get('fields', None):
        params['fields'] = (
            'cursor,items(adminKeys,instance,status,title,type,uid,userKeys,authorId, description)'
            )
    if not params.get('body', None):
        params['body'] = {'lang': 'en'}
        if instance:
            params['body']['instanceId'] = instance
    result = api.get_call('community', 'list', **params)
    return result


@classmethod
def put(cls, f):
    """ decorator to accept PUT method """
    return cls._accept_method(['PUT'], f)


def _remove_dups(L):
    """
    Removes duplicates AND preserves the original order of the elements.
    The set class is not guaranteed to do this.
    """
    seen_before = set([])
    L2 = []
    for i in L:
        if i not in seen_before:
            seen_before.add(i)
            L2.append(i)
    return L2


def _chunks(itera, size):
    """Yield successive same-sized chunks from `itera`.

    Parameters
    ----------
    itera : iterable
        This is the iterable we will return chunks of.
    size : int
        The size of the chunks.

    Yields
    ------
    out : object like `itera`
        The successive same-sized chunks from `itera`-

    Notes
    -----
    We are here using `range` rather than `xrange`. This is just to ease
    the transition from python2 to python3. Note that this will probably
    lead to some inefficiencies for python2 execution. The code is based
    on one question at Stackoverflow [chunks]_.

    References
    ----------
    .. [chunks] Stackoverflow, "How do you split ...",
       http://stackoverflow.com/a/312464
    """
    for i in range(0, len(itera), size):
        yield itera[i:i + size]


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


def _limit(query, hints):
    """Apply a limit to a query.

    :param query: query to apply filters to
    :param hints: contains the list of filters and limit details.

    :returns: query updated with any limits satisfied

    """
    if hints.limit:
        original_len = query.count()
        limit_query = query.limit(hints.limit['limit'])
        if limit_query.count() < original_len:
            hints.limit['truncated'] = True
            query = limit_query
    return query


def calculate(air_temp_c, rh, on_error=float('nan')):
    """Calculate the heat index.

    The heat index is calculated using the air temperature in degrees
    Celsius and the relative humidity as a percentage (0.0 to 100.0).
    See:
    http://www.wpc.ncep.noaa.gov/html/heatindex_equation.shtml

    Parameters
    ----------
    air_temp_c : float
        The air temperature in degrees C.
    rh : float
        The relative humidity, as a percentage (0.0 to 100.0)
    on_error : optional, float('nan')
        The return value when an error occcurs during calculation.  May
        be any type, but preferably a float.

    Returns
    -------
    float
        The heat index in degrees C.

    """
    try:
        at_f = float(air_temp_c) * (9.0 / 5.0) + 32.0
        rh_f = float(rh)
        heat_index = (-42.379 + 2.04901523 * at_f + 10.14333127 * rh_f -
            0.22475541 * at_f * rh_f - 0.00683783 * at_f ** 2 - 0.05481717 *
            rh_f ** 2 + 0.00122874 * at_f ** 2 * rh_f + 0.00085282 * at_f *
            rh_f ** 2 - 1.99e-06 * at_f ** 2 * rh_f ** 2)
        if at_f <= 80.0 or rh_f <= 40.0:
            heat_index = float(air_temp_c)
        else:
            heat_index = (heat_index - 32.0) * (5.0 / 9.0)
    except:
        heat_index = on_error
    return heat_index


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

    The ".dev0" means dirty.

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


def text_len(length, fs):
    """Approximation of text width"""
    return length * 0.6 * fs


def doRead():
    """
        Some data is available for reading on your descriptor.

        @return: If an error is encountered which causes the descriptor to
            no longer be valid, a L{Failure} should be returned.  Otherwise,
            L{None}.
        """


@classmethod
def cmp(cls, value_a, value_b):
    """Return True if 2 values are the same"""
    if type(value_a) is not type(value_b):
        return False
    if isinstance(value_a, (list, tuple)):
        if len(value_a) != len(value_b):
            return False
        for i, a in enumerate(value_a):
            b = value_b[i]
            if not cls.cmp(a, b):
                return False
        return True
    if isinstance(value_a, dict):
        for k, v in value_a.items():
            if not cls.cmp(v, value_b.get(k)):
                return False
        return True
    return value_a == value_b


def evalcontextfilter(f):
    """Decorator for marking eval-context dependent filters.  An eval
    context object is passed as first argument.  For more information
    about the eval context, see :ref:`eval-context`.

    .. versionadded:: 2.4
    """
    f.evalcontextfilter = True
    return f


@staticmethod
def merge_dict_values(norm_current_values, norm_updated_values):
    """ Create an merged update object for manageiq group filters.

            The input dict contain the tag values per category.
            If the new values contain the category, all tags for that category are replaced
            If the new values do not contain the category, the existing tags are kept

        Returns:
            the nested array with the merged values, used in the update post body
        """
    if norm_current_values and not norm_updated_values:
        return norm_current_values
    if not norm_current_values and norm_updated_values:
        return norm_updated_values
    res = norm_current_values.copy()
    res.update(norm_updated_values)
    return res


def object_is_translation(obj):
    """
    Returns True if object is translation object.
    """
    related_name = getattr(obj, 'related_name', None)
    if related_name is None:
        return False
    if related_name != 'translations':
        return False
    return True


def _parse_date_noop_formatter(d):
    """ NOOP - only here for pylint """
    return d


def escape(string, quote=True):
    """Returns a string where HTML metacharacters are properly escaped.

    Compatibility layer to avoid incompatibilities between Python versions,
    Qt versions and Qt bindings.

    >>> import silx.utils.html
    >>> silx.utils.html.escape("<html>")
    >>> "<html>"

    .. note:: Since Python 3.3 you can use the `html` module. For previous
        version, it is provided by `sgi` module.
    .. note:: Qt4 provides it with `Qt.escape` while Qt5 provide it with
        `QString.toHtmlEscaped`. But `QString` is not exposed by `PyQt` or
        `PySide`.

    :param str string: Human readable string.
    :param bool quote: Escape quote and double quotes (default behaviour).
    :returns: Valid HTML syntax to display the input string.
    :rtype: str
    """
    string = string.replace('&', '&')
    string = string.replace('<', '<')
    string = string.replace('>', '>')
    if quote:
        string = string.replace("'", ''')
        string = string.replace('"', '"')
    return string


def autocomplete():
    """Evaluate the namespace up until the cursor and give a list of options or complete the name if there is only one

    """
    pass


def track_to_empty():
    """Create an Empty object which will be copying movement of active track

    """
    pass


def slide_in(clip, duration, side):
    """ Makes the clip arrive from one side of the screen.

    Only works when the clip is included in a CompositeVideoClip,
    and if the clip has the same size as the whole composition.

    Parameters
    ===========

    clip
      A video clip.

    duration
      Time taken for the clip to be fully visible

    side
      Side of the screen where the clip comes from. One of
      'top' | 'bottom' | 'left' | 'right'

    Examples
    =========

    >>> from moviepy.editor import *
    >>> clips = [... make a list of clips]
    >>> slided_clips = [clip.fx( transfx.slide_in, 1, 'left')
                        for clip in clips]
    >>> final_clip = concatenate( slided_clips, padding=-1)

    """
    w, h = clip.size
    pos_dict = {'left': lambda t: (min(0, w * (t / duration - 1)), 'center'
        ), 'right': lambda t: (max(0, w * (1 - t / duration)), 'center'),
        'top': lambda t: ('center', min(0, h * (t / duration - 1))),
        'bottom': lambda t: ('center', max(0, h * (1 - t / duration)))}
    return clip.set_position(pos_dict[side])


def adjust_annotations_font_sizes(fig, factor=1.0):
    """ Adjust annotation font sizes.

    Arguments:
        fig (plotly.graph_objs._figure.Figure): Plotly figure.
        factor (float): The font sizes are multiplied with this factor.
    """
    annotations = getattr(fig.layout, 'annotations', [])
    for annotation in annotations:
        font = getattr(annotation, 'font', None)
        if font is not None:
            size = getattr(font, 'size', None)
            if size is not None:
                font['size'] *= factor


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

        :param GroupCreateType val:
        :rtype: EventType
        """
    return cls('group_create', val)


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

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

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


@staticmethod
def qmake_quote(path):
    """ Return a path quoted for qmake if it contains spaces. """
    path = path.replace('\\', '/')
    if ' ' in path:
        path = '$$quote({})'.format(path)
    return path


def cliffs_delta(control, test):
    """
    Computes Cliff's delta for 2 samples.
    See https://en.wikipedia.org/wiki/Effect_size#Effect_size_for_ordinal_data

    Keywords
    --------
    control, test: numeric iterables.
        These can be lists, tuples, or arrays of numeric types.

    Returns
    -------
        A single numeric float.
    """
    import numpy as np
    from scipy.stats import mannwhitneyu
    if control.__class__ != np.ndarray:
        control = np.array(control)
    if test.__class__ != np.ndarray:
        test = np.array(test)
    c = control[~np.isnan(control)]
    t = test[~np.isnan(test)]
    control_n = len(c)
    test_n = len(t)
    U, _ = mannwhitneyu(t, c, alternative='two-sided')
    cliffs_delta = 2 * U / (control_n * test_n) - 1
    return cliffs_delta


def row_structural_typicality(X_L_list, X_D_list, row_id):
    """
    Returns how typical the row is (opposite of how anomalous the row is).
    """
    count = 0
    assert len(X_L_list) == len(X_D_list)
    for X_L, X_D in zip(X_L_list, X_D_list):
        for r in range(len(X_D[0])):
            for c in range(len(X_L['column_partition']['assignments'])):
                if X_D[X_L['column_partition']['assignments'][c]][r] == X_D[
                    X_L['column_partition']['assignments'][c]][row_id]:
                    count += 1
    return float(count) / (len(X_D_list) * len(X_D[0]) * len(X_L_list[0][
        'column_partition']['assignments']))


def transform_dict_key_data_to_int(dictionary):
    """
    Convierte las keys de un diccionario en valores enteros. Devuelve el mismo diccionario con las keys
    transformads en valores enteros.

    :dictionary: [Dict] - Diccionario a convertir

    :return: [Dict] - Diccionario con las keys convertidas
    """
    aux_dict = dict({})
    for key in dictionary:
        aux_dict[int(key)] = dictionary[key]
    return aux_dict


def smart_truncate(string, max_length=0, word_boundary=False, separator=' ',
    save_order=False):
    """
    Truncate a string.
    :param string (str): string for modification
    :param max_length (int): output string length
    :param word_boundary (bool):
    :param save_order (bool): if True then word order of output string is like input string
    :param separator (str): separator between words
    :return:
    """
    string = string.strip(separator)
    if not max_length:
        return string
    if len(string) < max_length:
        return string
    if not word_boundary:
        return string[:max_length].strip(separator)
    if separator not in string:
        return string[:max_length]
    truncated = ''
    for word in string.split(separator):
        if word:
            next_len = len(truncated) + len(word)
            if next_len < max_length:
                truncated += '{}{}'.format(word, separator)
            elif next_len == max_length:
                truncated += '{}'.format(word)
                break
            elif save_order:
                break
    if not truncated:
        truncated = string[:max_length]
    return truncated.strip(separator)


def mirror_mag_h(height_image, height_object):
    """Usage: Find magnification using height of image and height of object"""
    return height_image / height_object


@classmethod
def declare_unload_callback(cls, entry, unload_callback):
    """Save a unload callback in registry Manager

        :param entry: declaration type name
        :param unload_callback: classmethod pointer
        """
    cls.callback_unload_entries[entry] = unload_callback


def admin_actions(context):
    """
    Track the number of times the action field has been rendered on the page,
    so we know which value to use.
    """
    context['action_index'] = context.get('action_index', -1) + 1
    return context


def calculate_desired_noise_rms(clean_rms, snr):
    """
    Given the Root Mean Square (RMS) of a clean sound and a desired signal-to-noise ratio (SNR),
    calculate the desired RMS of a noise sound to be mixed in.

    Based on https://github.com/Sato-Kunihiko/audio-SNR/blob/8d2c933b6c0afe6f1203251f4877e7a1068a6130/create_mixed_audio_file.py#L20
    :param clean_rms: Root Mean Square (RMS) - a value between 0.0 and 1.0
    :param snr: Signal-to-Noise (SNR) Ratio in dB - typically somewhere between -20 and 60
    :return:
    """
    a = float(snr) / 20
    noise_rms = clean_rms / 10 ** a
    return noise_rms


def sklearn_installed():
    """
    Checks that *scikit-learn* is available.
    """
    try:
        import sklearn
        return True
    except ImportError:
        return False


def lambd_NH3_ClO4_CB89(T, P):
    """n-a: ammonia perchlorate [CB89]."""
    lambd = -0.056
    valid = T == 298.15
    return lambd, valid


def sort_spec(spec):
    """Helper to provide a key function for `sorted`

    Provide key to sort by type first and by whatever identifies a particular
    type of spec dict

    Parameters
    ----------
    spec: dict
      study specification dictionary

    Returns
    -------
    string
    """
    if spec['type'] == 'dicomseries':
        return 'dicomseries' + spec['uid']
    else:
        return spec['type'] + spec['location']


def istime(due):
    """False if time has passed, True if time has not passed"""
    import datetime
    dNt = due.split(' ')
    d = dNt[0].split('-')
    t = dNt[1].split(':')
    now = datetime.datetime.now()
    N_dNt = str(now).split(' ')
    N_d = N_dNt[0].split('-')
    N_t = N_dNt[1].split(':')
    if int(d[0]) < int(N_d[0]):
        return False
    elif int(d[0]) > int(N_d[0]):
        return True
    elif int(d[1]) < int(N_d[1]):
        return False
    elif int(d[1]) > int(N_d[1]):
        return True
    elif int(d[2]) < int(N_d[2]):
        return False
    elif int(d[2]) > int(N_d[2]):
        return True
    elif int(t[0]) < int(N_t[0]):
        return False
    elif int(t[0]) > int(N_t[0]):
        return True
    elif int(t[1]) < int(N_t[1]):
        return False
    elif int(t[1]) > int(N_t[1]):
        return True
    elif float(t[2]) <= float(N_t[2]):
        return False
    else:
        return True


def __init_subclass__(cls, **kwargs):
    """
        Catch-subclass declarations and register them.
        """
    super().__init_subclass__(**kwargs)
    cls.__registry__[cls.__name__] = cls


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

    The ".dev0" means dirty.

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


def parseStreamClient(reactor, *args, **kwargs):
    """
        This method is invoked by L{endpoints.clientFromString}, if the type of
        endpoint matches the return value from this
        L{IStreamClientEndpointStringParserWithReactor}'s C{prefix} method.

        @param reactor: The reactor passed to L{endpoints.clientFromString}.

        @param args: The byte string arguments, minus the endpoint type, in the
            endpoint description string, parsed according to the rules
            described in L{endpoints.quoteStringArgument}.  For example, if the
            description were C{b"my-type:foo:bar:baz=qux"}, C{args} would be
            C{(b'foo', b'bar')}

        @param kwargs: The byte string arguments from the endpoint description
            passed as keyword arguments.  For example, if the description were
            C{b"my-type:foo:bar:baz=qux"}, C{kwargs} would be
            C{dict(baz=b'qux')}.

        @return: a client endpoint
        @rtype: a provider of L{IStreamClientEndpoint}
        """


def load_df(name, engine='pickle', key='df', **kwargs):
    """Load a dataframe from disk.
    """
    import pandas as pd
    func = 'read_{}'.format(engine)
    if engine == 'hdf':
        kwargs['key'] = key
    return getattr(pd, func)(name)


def read_file(filename, mode='r', readlines=True):
    """write_file will open a file, "filename" and write content, "content"
       and properly close the file
    """
    with open(filename, mode) as filey:
        if readlines is True:
            content = filey.readlines()
        else:
            content = filey.read()
    return content


def uint32_tag(name, value):
    """Create a DMAP tag with uint32 data."""
    return name.encode('utf-8') + b'\x00\x00\x00\x04' + value.to_bytes(4,
        byteorder='big')


def _take_first_tag(tags, default, functions):
    """Return the first tag value that isn't None."""
    for f in functions:
        value = f(tags)
        if value is not None:
            return value
    return default


def autocast(s):
    """Try to guess the simple type and convert the value to it.

    @param s string
    @returns the relevant type : a float, string or int
    """
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return s


@classmethod
def devices_by_component(cls, component):
    """Returns the available Devices for Component."""
    for dev in cls.devices:
        if dev.component == component:
            yield dev


def delete():
    """Delete selected files

    """
    pass


def parse_gtfs_time(timestr):
    """
    GTFS time strings are HH:MM:SS (or H:MM:SS if the hours field is less than
    10). The time is relative to noon on a given day, and the hours field can
    go over 23 to represent a time on the following day (GTFS time never
    decreases in a given trip).

    This function is not quite that picky, but its behavior is undefined if
    it's given a string not following the specification.

    This function returns a timedelta, which contains the number of seconds
    since noon represented by a time on a given day.
    """
    split = timestr.split(':')
    seconds = int(split[-1])
    minutes = int(split[-2]) if len(split) > 1 else 0
    hours = int(split[-3]) if len(split) > 2 else 0
    return (hours - 12) * 3600 + minutes * 60 + seconds


def check_interface_stats():
    """Check interface statistic result"""
    pass


def status_is(weather, status, weather_code_registry):
    """
    Checks if the weather status code of a *Weather* object corresponds to the
    detailed status indicated. The lookup is performed against the provided
    *WeatherCodeRegistry* object.

    :param weather: the *Weather* object whose status code is to be checked
    :type weather: *Weather*
    :param status: a string indicating a detailed weather status
    :type status: str
    :param weather_code_registry: a *WeatherCodeRegistry* object
    :type weather_code_registry: *WeatherCodeRegistry*
    :returns: ``True`` if the check is positive, ``False`` otherwise

    """
    weather_status = weather_code_registry.status_for(weather.
        get_weather_code()).lower()
    return weather_status == status


def units_converter(from_units='ip', **kwargs):
    """ Converts IP values to SI units

    Parameters
    ----------
    from_units: str
        specify system to convert from
    **kwargs : [t, v]

    Returns
    -------
    converted values in SI units
    """
    results = list()
    if from_units == 'ip':
        for key, value in kwargs.items():
            if 'tmp' in key or key == 'tr' or key == 'tdb':
                results.append((value - 32) * 5 / 9)
            if key in ['v', 'vr', 'vel']:
                results.append(value / 3.281)
            if key == 'area':
                results.append(value / 10.764)
            if key == 'pressure':
                results.append(value * 101325)
    elif from_units == 'si':
        for key, value in kwargs.items():
            if 'tmp' in key or key == 'tr' or key == 'tdb':
                results.append(value * 9 / 5 + 32)
            if key in ['v', 'vr', 'vel']:
                results.append(value * 3.281)
            if key == 'area':
                results.append(value * 10.764)
            if key == 'pressure':
                results.append(value / 101325)
    return results


@classmethod
def get_example_file_content(cls, example_file, request):
    """
        Returns a binary file that will be served through the request
        This base implementation just renders a template and returns the result as BytesIO or StringIO
        Override this method to return a custom file content

        :param request HttpRequest
        :rtype StringIO|BytesIO
        """
    if example_file.template_name:
        from django.template import loader
        from six import StringIO
        file_content = StringIO()
        file_content.write(loader.render_to_string(template_name=
            example_file.template_name, context={}, request=request))
        return file_content


@classmethod
def needs_credit_status_update(cls, to_status):
    """
        Returns a boolean if the passed in to_status calls for an update to the credit requirement status.
        """
    return to_status in [cls.verified, cls.rejected, cls.declined, cls.
        submitted, cls.error]


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


def drop_engine_after(prev_engine):
    """
    Removes an engine from the singly-linked list of engines.

    Args:
        prev_engine (projectq.cengines.BasicEngine):
            The engine just before the engine to drop.
    Returns:
        Engine: The dropped engine.
    """
    dropped_engine = prev_engine.next_engine
    prev_engine.next_engine = dropped_engine.next_engine
    dropped_engine.next_engine = None
    dropped_engine.main_engine = None
    return dropped_engine


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


@classmethod
def with_optional(cls, converter, pattern=None):
    """Alias for :py:meth:`with_zero_or_one()` method."""
    return cls.with_zero_or_one(converter, pattern)


@classmethod
def topic(cls, **kwargs) ->str:
    """Get MQTT topic for this message type."""
    return 'hermes/asr/textCaptured'


@staticmethod
def keras_version():
    """ Retrieves the Keras major version.
		"""
    from keras import __version__
    return int(__version__.split('.')[0])


def _truncate_seq_pair(tokens_a, tokens_b, max_length):
    """Truncates a sequence pair in place to the maximum length.

     This will always truncate the longer sequence one token at a time.
     This makes more sense than truncating an equal percent
     of tokens from each, since if one sequence is very short then each token
     that's truncated likely contains more information than a longer sequence.
    """
    while True:
        total_length = len(tokens_a) + len(tokens_b)
        if total_length <= max_length:
            break
        if len(tokens_a) > len(tokens_b):
            tokens_a.pop()
        else:
            tokens_b.pop()


def score_stratified_by_confound(score, confounds):
    """
    Helper to summarize the performance score (accuracy, MSE, MAE etc) for each
    level or variant of confound. This is helpful to assess any bias towards a
    particular value when confounds are categorical (such as site or gender). So
    if the MSE (of target) for Females is much lower compared to Males, then it
    may indicate a potential bias of the model towards Females (due to imbalance in
    size?)

    Parameters
    ----------
    score
    confounds

    Returns
    -------

    """
    raise NotImplementedError()


def demo():
    """demo is used to demonstrate typical examples about this class."""
    demostr = """
import clubear as cb
#clubear.csv is generated by cb.manager.demo()
pm=cb.pump('clubear.csv') #start a new pump
pm.keep #check the head lists
cb.check(pm).stats() #check the for stats
pm.qlist=['age','height','weight','price','logsales']
cb.check(pm).stats(niter=20,keep=['price'])
cb.check(pm).corr() #check for correlation
cb.check(pm).table(tv=True) #check table
pm.subsize=10000 #check the subsize
df=pm.go #start to pump data
"""
    print(demostr)


def create_badges_table():
    """
	This Function is used to create Badges Table inside
	Readme
	"""
    pass


def add_last_modified_header(response, last_modified):
    """ Adds the give date to the response as Last-Modified header. """
    if last_modified:
        response.headers.add('Last-Modified', last_modified.strftime(
            '%a, %d %b %Y %H:%M:%S GMT'))


def __new__(cls):
    """
        Will always return the same instance.
        """
    try:
        return cls._ally_singletone
    except AttributeError:
        cls._ally_singletone = super().__new__(cls)
    return cls._ally_singletone


def is_gcs_path(path):
    """Returns True if given path is GCS path, False otherwise."""
    return path.strip().lower().startswith('gs://')


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Toggle border selection

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def check_honeypot(request, form):
    """
    Make sure that the hidden form field is empty, using django-honeypot.
    """
    try:
        from honeypot.decorators import verify_honeypot_value
        return verify_honeypot_value(request, '') is None
    except ImportError:
        return True


def cooling_degree_time(t, t_base=23):
    """Calculate cooling degree time at a single time interval.

    Args:
        t: The temperature at a given time interval.
        t_base: The base temperature above which a given time is considered
            to be in cooling mode. This should be in the same units as the input
            temperature. Default is 23 Celcius, which is a common balance point for
            buildings.
    """
    if t > t_base:
        return t - t_base
    else:
        return 0


@classmethod
def calc_path_scores(cls, path):
    """経路のパスのスコア（フェロモン）を計算する

        蟻のパスを引数として
        各ノードのスコアを合計しその平均(フェロモン)を返す

        Args:
            path(list(str)): アリが通ったパス

        Returns:
            float: 各エッジに加算することになるフェロモン
        """
    score = 0
    for url in path:
        node = cls.get_node(url)
        score += node.score
    if len(path) == 0:
        return 0
    return score / len(path)


def p_simple_expr_function_call(p):
    """simple_expr : function_call"""
    p[0] = 'function_call', p[1]


def range(start, stop, step=1.0):
    """Replacement for built-in range function.

    :param start: Starting value.
    :type start: number
    :param stop: End value.
    :type stop: number
    :param step: Step size.
    :type step: number
    :returns: List of values from `start` to `stop` incremented by `size`.
    :rtype: [float]
    """
    start, stop, step = map(float, (start, stop, step))
    result = [start]
    current = start
    while current < stop:
        current += step
        result.append(current)
    return result


@staticmethod
def _obj_wrapper(func, x_meas, y_meas, kwargs, p):
    """
        Wrapper function that point to objective function.

        :param func: objective function.
        :param kwargs: key arguments to pass on to objective function
        :param p: particle used to calculate objective function
        :return: return the calculated objective function.
        """
    return func(p.pos, x_meas, y_meas, **kwargs)


def get_model_field(model, name):
    """
    Gets a field from a Django model.

    :param model: A Django model, this should be the class itself.
    :param name:  A Django model's field.
    :return:  The field from the model, a subclass of django.db.models.Model
    """
    return model._meta.get_field(name)


def residual_real(re, fit_re, fit_im):
    """
    Relative Residuals as based on Boukamp's definition

    Ref.:
        - Boukamp, B.A. J. Electrochem. SoC., 142, 6, 1885-1894

    Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com)
    """
    modulus_fit = (fit_re ** 2 + fit_im ** 2) ** (1 / 2)
    return (re - fit_re) / modulus_fit


def format_price(v: float) ->str:
    """
    Format price in dollars.
    """
    if v > 1:
        return '$%.2f' % v
    return '%.2f¢' % (100 * v)


def _get_elements(lst, type_=float):
    """
    return all first elements of lst that can be converted to type_. Remove them
    from lst.
    """
    r = []
    try:
        while lst:
            e = lst.pop(0)
            e = type_(e)
            r.append(e)
    except ValueError:
        lst.insert(0, e)
    return r


def render():
    """Plain render method without keyword arguments."""


def print_progress_bar(iteration: int, total: int, prefix: str='', suffix:
    str='', decimals: int=1, length: int=100, fill: str='█'):
    """
    Call in a loop to create terminal progress bar
    @params:
    iteration   - Required  : current iteration (Int)
    total       - Required  : total iterations (Int)
    prefix      - Optional  : prefix string (Str)
    suffix      - Optional  : suffix string (Str)
    decimals    - Optional  : positive number of decimals in percent complete (Int)
    length      - Optional  : character length of bar (Int)
    fill        - Optional  : bar fill character (Str)
    """
    percent = ('{0:.' + str(decimals) + 'f}').format(100 * (iteration /
        float(total)))
    filled_length = int(length * iteration // total)
    bar = fill * filled_length + '░' * (length - filled_length)
    print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix))


@staticmethod
def combine(first, rem):
    """
        Combine first and rem results into one (probability, words) pair
        :param first: a tuple in the form: probability, word
        :param rem: a tuple in the form: probability, list_of_words
        :return:
        """
    first_prob, first_word = first
    rem_prob, rem_words = rem
    return first_prob + rem_prob, [first_word] + rem_words


def CUSTOM_MERGE_SMALL(writer, segments):
    """This policy merges small segments, where "small" is defined using a
    fixed number of documents. Unlike whoosh.filedb.filewriting.MERGE_SMALL,
    this one does nothing unless there's more than one segment to merge.
    """
    from whoosh.filedb.filereading import SegmentReader
    unchanged_segments = []
    segments_to_merge = []
    for segment in segments:
        if segment.doc_count_all() < 10000:
            segments_to_merge.append(segment)
        else:
            unchanged_segments.append(segment)
    if len(segments_to_merge) > 1:
        for segment in segments_to_merge:
            with SegmentReader(writer.storage, writer.schema, segment
                ) as reader:
                writer.add_reader(reader)
    else:
        unchanged_segments.extend(segments_to_merge)
    return unchanged_segments


@classmethod
def object_to_dict(cls, obj):
    """
            This function converts Objects into Dictionary
        """
    dict_obj = dict()
    if obj is not None:
        if type(obj) == list:
            dict_list = []
            for inst in obj:
                dict_list.append(cls.object_to_dict(inst))
            dict_obj['list'] = dict_list
        elif not cls.is_primitive(obj):
            for key in obj.__dict__:
                if type(obj.__dict__[key]) == list:
                    dict_list = []
                    for inst in obj.__dict__[key]:
                        dict_list.append(cls.object_to_dict(inst))
                    dict_obj[key] = dict_list
                elif not cls.is_primitive(obj.__dict__[key]):
                    temp_dict = cls.object_to_dict(obj.__dict__[key])
                    dict_obj[key] = temp_dict
                else:
                    dict_obj[key] = obj.__dict__[key]
        elif cls.is_primitive(obj):
            return obj
    return dict_obj


def zero_insert(input_string):
    """
    Get a string as input if input is one digit add a zero.

    :param input_string: input digit az string
    :type input_string:str
    :return: modified output as str
    """
    if len(input_string) == 1:
        return '0' + input_string
    return input_string


def _to_lowercase(ftype, fname, *_):
    """ Tranforms a feature to it's lowercase representation
    """
    return ftype, fname if fname is ... else fname.lower()


def lowercase_range(code1, code2):
    """
    If the range of characters from code1 to code2-1 includes any
    upper case letters, return the corresponding lower case range.
    """
    code3 = max(code1, ord('A'))
    code4 = min(code2, ord('Z') + 1)
    if code3 < code4:
        d = ord('a') - ord('A')
        return code3 + d, code4 + d
    else:
        return None


def height_from_height_buttocks(segment_length):
    """
    Calculates body height based on the height of the buttocks from the ground

    args:
        segment_length (float): height of the buttocks

    Returns:
        float: total body height
    """
    if segment_length <= 0:
        raise ValueError('segment_length must be > 0')
    return segment_length / 0.485


def hasmethod(obj, m):
    """Return ``True`` if object *obj* contains the method *m*."""
    return hasattr(obj, m) and callable(getattr(obj, m))


def saturation_filter(u, u_max, u_min):
    """ saturation_filter Helper Function

        the output is equal to u_max if u >= u_max, u_min if u <= u_min, and u otherwise
    """
    return max(min(u, u_max), u_min)


def get_script_urls_from_call_stack_as_set(call_stack):
    """Return the urls of the scripts involved in the call stack as a set."""
    script_urls = set()
    if not call_stack:
        return script_urls
    stack_frames = call_stack.strip().split('\n')
    for stack_frame in stack_frames:
        script_url = stack_frame.rsplit(':', 2)[0].split('@')[-1].split(' line'
            )[0]
        script_urls.add(script_url)
    return script_urls


def __new__(cls, r=0, g=0, b=0, a=255):
    """
		Create a :class:`!Color` with the 8 bit red, green, blue and alpha
		components ``r``, ``g``, ``b`` and ``a``. Values will be
		clipped to the range [0; 255].
		"""
    return tuple.__new__(cls, (max(0, min(int(r), 255)), max(0, min(int(g),
        255)), max(0, min(int(b), 255)), max(0, min(int(a), 255))))


def stop():
    """Stop the debug session and drop connection to remote client"""


def insort_right(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it sorted assuming a is sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        if x < a[mid]:
            hi = mid
        else:
            lo = mid + 1
    a.insert(lo, x)


def difference_index(atext, btext):
    """Find the indext of the first character that differs between two texts

    :param atext: The first text
    :type atext: str
    :param btext: The second text
    :type str: str
    :return: The index, or None if there are no differences within the range
    :rtype: int or NoneType
    """
    length = len(atext)
    if len(btext) < length:
        length = len(btext)
    for i in range(length):
        if atext[i] != btext[i]:
            return i
    return None


def getHost():
    """
        Get this port's host address.

        @return: an address describing the listening port.
        @rtype: L{IPv4Address} or L{IPv6Address}.
        """


@classmethod
def create_from_dict(cls, dic):
    """
        Create a list of Bars from a dic.

        Parameters
        ----------
        dic : dict
            Keys are attribute names of Bar, values are corresponding values.

        Returns
        -------
        bar : Bar

        """
    bar = cls()
    bar.__dict__.update(dic)
    return bar


def __contains__(path):
    """Whether a specific directory is in this collection."""


def check_pg_num(pool, pg_num, size, num_osds=0, max_pgs_per_osd=200, pools={}
    ):
    """
    Returns empty string only if the Pool PG numbers are correct for the OSDs.
    Otherwise returns an error message like the one Ceph would return.
    """
    import six
    msg = ''
    max_pgs = max_pgs_per_osd * num_osds
    projected = 0
    if len(pool) < 0:
        projected = projected + pg_num * size
    for pool_name, pool_sizes in six.iteritems(pools):
        if pool_name == pool:
            projected = projected + pg_num * size
        else:
            projected = projected + int(pool_sizes['pg_num']) * int(pool_sizes
                ['size'])
    if projected > max_pgs:
        msg = 'Cannot add pool: ' + str(pool) + ' pg_num ' + str(pg_num
            ) + ' size ' + str(size) + ' would mean ' + str(projected
            ) + ' total pgs, which exceeds max ' + str(max_pgs
            ) + ' (mon_max_pg_per_osd ' + str(max_pgs_per_osd
            ) + ' * num_in_osds ' + str(num_osds) + ')'
    return msg


def upgrade():
    """A no-op migration for marking the Kilo release."""
    pass


def _clampz(a):
    """Prevent a from going < 0"""
    if a < 0:
        return 0
    return a


def signed5(x):
    """ convert to signed 5-bit """
    if x > 15:
        x = x - 32
    return x


@staticmethod
def withdraw(data, *args, **kwargs):
    """
        Returns a list giving details of success and transaction details, or failure
        and reason thererof
        ex.:
            [True, currency, amount, target_address, txid]
            [False, 'Reason for failure/ error message']
        :param data: requests.response() obj
        :param args:
        :param kwargs:
        :return: list
        """
    return data


def format_template(template, content):
    """Render a given pystache template
    with given content"""
    import pystache
    result = u''
    if True:
        result = pystache.render(template, content, string_encoding='utf-8')
    return result


def _find_next_joint(root, current_link, next_joint_name):
    """
    Find the next joint in the URDF tree

    Parameters
    ----------
    root
    current_link: xml.etree.ElementTree
        The current URDF link
    next_joint_name: str
        Optional : The name of the next joint. If not provided, find it automatically as the first child of the link.
    """
    has_next = False
    next_joint = None
    search_by_name = True
    current_link_name = None
    if next_joint_name is None:
        search_by_name = False
        current_link_name = current_link.attrib['name']
    for joint in root.findall('joint'):
        if joint is not None:
            if search_by_name:
                if joint.attrib['name'] == next_joint_name:
                    has_next = True
                    next_joint = joint
            elif joint.find('parent').attrib['link'] == current_link_name:
                has_next = True
                next_joint = joint
                break
    return has_next, next_joint


def CRRAutilityP_invP(uP, gam):
    """
    Evaluates the derivative of the inverse of the CRRA marginal utility function
    (with risk aversion parameter gam) at a given marginal utility level uP.

    Parameters
    ----------
    uP : float
        Marginal utility value
    gam : float
        Risk aversion

    Returns
    -------
    (unnamed) : float
        Marginal consumption corresponding to given marginal utility value
    """
    return -1.0 / gam * uP ** (-1.0 / gam - 1.0)


def checkoutCmd(server, repo, branch, revision=None, name=None):
    """checkoutCmd( "bzr+ssh://pyre.cacr.caltech.edu", "home/projects/pyre/web/repository", "1.0/pyre.db-jiao-experiment")
    """
    if name is None:
        raise ValueError('name is None')
    cmd = ['bzr branch']
    if revision:
        cmd.append('-r %s' % revision)
    cmd.append('%(server)s/%(repo)s/%(branch)s %(name)s' % locals())
    return ' '.join(cmd)


def float_check(value, default=None):
    """value must be a float or default."""
    try:
        return float(value)
    except ValueError:
        return default


def ip_for_request(request):
    """
    Returns ip address for request - first checks ``HTTP_X_FORWARDED_FOR``
    header, since app will generally be behind a public web server.
    """
    meta = request.META
    return meta.get('HTTP_X_FORWARDED_FOR', meta['REMOTE_ADDR']).split(',')[0]


def sibling(name):
    """
        Traverse to a sibling of this path.
        """


def hasClosingPeriod(text: str) ->bool:
    """
    Return True if the text ends with a period or something like '.)'
    """
    if not text:
        return False
    for period in '.።':
        if text[-1] == period:
            return True
        for closingPunctuation in ')]"\'”’»›':
            if text.endswith(period + closingPunctuation):
                return True
    return False


@classmethod
def from_dict(cls, dictionary):
    """Create class instance from a Python dictionary"""
    instance = cls()
    instance._json_data = dictionary
    return instance


def details(client, wid=None, name=None, owner=None):
    """ Fetch the details of a workspace by name or id.

    This function calls the Quetzal API endpoint to retrieve workspace
    details. When the `wid` parameter is set, it will use directly this number
    to do a `GET` on `/workspaces/:id`. When the `name` is set, it will fetch
    and filter the workspace list by this name and its `owner`. Note that
    `name` and `wid` are mutually exclusive options.

    Parameters
    ----------
    client: quetzal.client.Client
        Client object that will be used for the Quetzal API operation.
    wid: int, optional
        Workspace identifier.
    name: str, optional
        Workspace name.
    owner: str, optional
        Username of the workspace owner. If not set and `name` is set, it will
        use the username saved on the `client` configuration object.

    Returns
    -------
    w_details: quetzal.openapi_client.models.Workspace
        Details on the workspace, or ``None`` when it was not found.

    Raises
    ------
    quetzal.client.exceptions.QuetzalAPIException
        When the API returns an error. When the `wid` parameter is set and the
        workspace does not exist, this exception will be raised with its
        `status` member set to 404 (not found).
    urllib3.exceptions.RequestError
        When there was a problem connecting to the server.

    """
    if wid is None and name is None:
        raise ValueError('One of wid or name is needed.')
    if name:
        username = owner or client.configuration.username
        response = client.workspace_fetch(owner=username, name=name)
        if not response.results:
            return None
        w_details = response.results[0]
    else:
        w_details = client.workspace_details(wid)
    return w_details


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

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

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


def volumeFraction(concentration=1, molWeight=17, density=1.347):
    """ molWeight is kDa
      concentration in mM
      density g/ml
  """
    concentration_mg_ml = concentration * molWeight
    volume_fraction = concentration_mg_ml / density / 1000.0
    return volume_fraction


def correctDotPrefix(string):
    """Add dot prefix to file extension if missing"""
    return string if string.find('.') == 0 else '.' + string


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


def position():
    """defines the order of the mobile buttons"""


def int_shape(x):
    """ short for x.shape.as_list() """
    return x.shape.as_list()


@classmethod
def register_notify_callback(cls, callback):
    """A callback registered here will be fired whenever
        a notification is sent out. The callback should
        take a notification object, and event_qualifier.
        """
    cls.notify_callback = callback


def extrude_edges_move(MESH_OT_extrude_edges_indiv=None,
    TRANSFORM_OT_translate=None):
    """Extrude edges and move result

    :param MESH_OT_extrude_edges_indiv: Extrude Only Edges, Extrude individual edges only
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


@classmethod
def from_selector_string(cls, selector_string: str):
    """construct xml selector from input string"""
    selectors = selector_string.split(',')
    return cls(selectors)


def _set_initial_inf(params, name: str, index: int, value: float):
    """Adjust the Parameters.initial_inf parameter"""
    if index is not None:
        raise IndexError('You cannot index the initial_inf parameter')
    params.initial_inf = value


@staticmethod
def p_indexorder(p):
    """indexorder : INDEX_INCR
                      | INDEX_DECR"""
    p[0] = p[1]


@classmethod
def create_headers(klass, attributes):
    """
        Headers for space creation.
        """
    if 'organization_id' in attributes:
        return {'x-contentful-organization': attributes['organization_id']}
    return {}


def main():
    """Sets up a project to use fab_support.
    At a bare minimum it will copy an env.example file if none exists."""
    print('Todo commandline version')


def onfinished():
    """Called after all objects have been emitted from the command function.

        Implementations should return an iterator of objects to forward to
        the output layer.

        This method can be a generator.
        """


def _crc16_checksum(bytes):
    """Returns the CRC-16 checksum of bytearray bytes

    Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html

    Initial value changed to 0x0000 to match Stellar configuration.
    """
    crc = 0
    polynomial = 4129
    for byte in bytes:
        for i in range(8):
            bit = byte >> 7 - i & 1 == 1
            c15 = crc >> 15 & 1 == 1
            crc <<= 1
            if c15 ^ bit:
                crc ^= polynomial
    return crc & 65535


def cnum(num):
    """
    returns str with thousands separated by commas

    >>> khnum.cnum(123456789)
    '123,456,789'
    """
    return '{:,}'.format(num)


@classmethod
def _add_nfa_states_from_queue(cls, nfa, current_states, current_state_name,
    dfa_states, dfa_transitions, dfa_final_states):
    """Add NFA states to DFA as it is constructed from NFA."""
    dfa_states.add(current_state_name)
    dfa_transitions[current_state_name] = {}
    if current_states & nfa.final_states:
        dfa_final_states.add(current_state_name)


def _get_db_operator(db_alias):
    """
    Use south utility to find out the Database Operations object for current db backend alias.
    """
    from db_defaults import db
    from south.db import dbs
    return dbs[db_alias]


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

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


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

        :param EnabledDomainInvitesType val:
        :rtype: EventType
        """
    return cls('enabled_domain_invites', val)


def extract_sample_value_from_thermo_file_path(file_path):
    """ does what it says, returns an int"""
    return int(file_path.split('_X')[1].split('_thermo')[0])


def disp_to_pos(disp_dx, disp_dy, cog_x, cog_y):
    """
    Calculates source position in camera coordinates(x,y) from the reconstructed disp

    Parameters:
    -----------
    disp: DispContainer
    cog_x: float
    Coordinate x of the center of gravity of Hillas ellipse
    cog_y: float
    Coordinate y of the center of gravity of Hillas ellipse

    Returns:
    --------
    (source_pos_x, source_pos_y)
    """
    source_pos_x = cog_x + disp_dx
    source_pos_y = cog_y + disp_dy
    return source_pos_x, source_pos_y


def MakePalette(tr, tg, tb):
    """
    Creates a palette to be applied on an image based on input colour.

    :param `tr`: the red intensity of the input colour;
    :param `tg`: the green intensity of the input colour;
    :param `tb`: the blue intensity of the input colour.
    """
    l = []
    for i in range(255):
        l.extend([tr * i // 255, tg * i // 255, tb * i // 255])
    return l


def get_exception_data(e):
    """Extract the information about an exception.

    Tacker client for the v1 API expects exceptions to have 'type', 'message'
    and 'detail' attributes.This information is extracted and converted into a
    dictionary.

    :param e: the exception to be reraised
    :returns: a structured dict with the exception data
    """
    err_data = {'type': e.__class__.__name__, 'message': e, 'detail': ''}
    return err_data


def selectMaxCDS(trans):
    """select transcript with max CDS length
  """
    maxlen, mt = 0, None
    for t in trans:
        cds1, cds2 = t.cds_start(cdna=True), t.cds_stop(cdna=True)
        try:
            cdslen = cds2 - cds1
        except:
            continue
        if cdslen % 3 != 0:
            continue
        if cdslen > maxlen:
            maxlen, mt = cdslen, t
    return mt


@staticmethod
def boolconvert(value):
    """Convert the string *value* to a boolean. ``"True"`` is converted to
        ``True`` and ``"False"`` is converted to ``False``.

        .. note::

           If value is neither "True" nor "False", it's returned unchanged.

        """
    if value == 'True':
        return True
    elif value == 'False':
        return False
    else:
        return value


def frame_indexing(frame, multi_index, level_i, indexing_type='label'):
    """Index dataframe based on one level of MultiIndex.

    Arguments
    ---------
    frame : pandas.DataFrame
        The datafrme to select records from.
    multi_index : pandas.MultiIndex
        A pandas multiindex were one fo the levels is used to sample the
        dataframe with.
    level_i : int, str
        The level of the multiIndex to index on.
    indexing_type : str
        The type of indexing. The value can be 'label' or 'position'.
        Default 'label'.

    """
    if indexing_type == 'label':
        data = frame.loc[multi_index.get_level_values(level_i)]
        data.index = multi_index
    elif indexing_type == 'position':
        data = frame.iloc[multi_index.get_level_values(level_i)]
        data.index = multi_index
    else:
        raise ValueError("indexing_type needs to be 'label' or 'position'")
    return data


@classmethod
def validate_instance(cls, argument_name, argument, expected_type):
    """
        Validate ``argument`` is a instance of ``expected_type``
        """
    if not isinstance(argument, expected_type):
        raise TypeError(cls._ARGUMENT_TYPE_MESSAGE.format(name=
            argument_name, type=expected_type, arg=argument))


def _simple_breed(best, num, mutation_rate, random_f):
    """Returns num copies of parent with mutation_rate changes"""
    result = []
    score, parent = best
    for child_number in range(num):
        if random_f() <= mutation_rate:
            child = parent.mutate()
            result.append(child)
        else:
            result.append(parent)
    return result


def matrix(*args):
    """Input arguments as rows in list form to construct a functional matrix.

    >>> row1, row2 = row(1, 0), row(0, 1)
    >>> matrix(row1, row2)
    [[1, 0], [0, 1]]
    """
    a = []
    for arg in args:
        a.append(arg)
    return a


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


def fc1():
    """ Test function 1 """
    print('fc1')


def damerau_levenshtein(seq1, seq2):
    """Calculate the Damerau-Levenshtein distance between sequences.

    This distance is the number of additions, deletions, substitutions,
    and transpositions needed to transform the first sequence into the
    second. Although generally used with strings, any sequences of
    comparable objects will work.

    Transpositions are exchanges of *consecutive* characters; all other
    operations are self-explanatory.

    This implementation is O(N*M) time and O(M) space, for N and M the
    lengths of the two sequences.

    >>> damerau_levenshtein('ba', 'abc')
    2
    >>> damerau_levenshtein('fee', 'deed')
    2

    It works with arbitrary sequences too:
    >>> damerau_levenshtein('abcd', ['b', 'a', 'c', 'd', 'e'])
    2
    """
    one_ago = None
    this_row = list(range(1, len(seq2) + 1)) + [0]
    for x in range(len(seq1)):
        two_ago, one_ago, this_row = one_ago, this_row, [0] * len(seq2) + [
            x + 1]
        for y in range(len(seq2)):
            del_cost = one_ago[y] + 1
            add_cost = this_row[y - 1] + 1
            sub_cost = one_ago[y - 1] + (seq1[x] != seq2[y])
            this_row[y] = min(del_cost, add_cost, sub_cost)
            if x > 0 and y > 0 and seq1[x] == seq2[y - 1] and seq1[x - 1
                ] == seq2[y] and seq1[x] != seq2[y]:
                this_row[y] = min(this_row[y], two_ago[y - 2] + 1)
    return this_row[len(seq2) - 1]


def log(text, array=None):
    """Prints a text message. And, optionally, if a Numpy array is provided it
    prints it's shape, min, and max values.
    """
    if array is not None:
        text = text.ljust(25)
        text += 'shape: {:20}  '.format(str(array.shape))
        if array.size:
            text += 'min: {:10.5f}  max: {:10.5f}'.format(array.min(),
                array.max())
        else:
            text += 'min: {:10}  max: {:10}'.format('', '')
        text += '  {}'.format(array.dtype)
    print(text)


def strtobool(val):
    """
    This function was borrowed from distutils.utils. While distutils
    is part of stdlib, it feels odd to use distutils in main application code.

    The function was modified to walk its talk and actually return bool
    and not int.
    """
    val = val.lower()
    if val in ('y', 'yes', 't', 'true', 'on', '1'):
        return True
    elif val in ('n', 'no', 'f', 'false', 'off', '0'):
        return False
    else:
        raise ValueError('invalid truth value %r' % (val,))


@classmethod
def dark_teal(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x11806a``."""
    return cls(1146986)


def is_list(obj):
    """Helper method to see if the object is a Python list.
    >>> is_list([4])
    True
    """
    return type(obj) is list


def reshape(a, *shape, **kwargs):
    """Gives a new shape to an array without changing its data.

    .. versionadded:: 2015.2
    """
    return a.reshape(*shape, **kwargs)


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


def set_feeds(rss_feeds):
    """Set a list of URLs to use and fetch content from.
        """


@staticmethod
def iter_params():
    """return (XOR key, ROL bits)"""
    for xor_key in range(0, 256):
        for rol_bits in range(1, 8):
            yield xor_key, rol_bits


def is_defaults_to_https(domain):
    """
    A domain "defaults to HTTPS" if its canonical endpoint uses HTTPS.
    """
    canonical = domain.canonical
    return canonical.protocol == 'https'


def _add_axis_labels_title(plot, xlabel, ylabel, title):
    """Helper function to add axes labels and a title to stats plots"""
    try:
        if hasattr(plot, 'set_title'):
            plot.set_title(title)
            plot.set_xlabel(xlabel)
            plot.set_ylabel(ylabel)
        else:
            plot.title(title)
            plot.xlabel(xlabel)
            plot.ylabel(ylabel)
    except Exception:
        pass


def mask_to_dict(bits_def, mask_value):
    """
    Describes which flags are set for a mask value

    :param bits_def:
    :param mask_value:
    :return: Mapping of flag_name -> set_value
    :rtype: dict
    """
    return_dict = {}
    for flag_name, flag_defn in bits_def.items():
        flag_bits = flag_defn['bits']
        if not isinstance(flag_defn['bits'], list):
            flag_bits = [flag_bits]
        flag_shift = min(flag_bits)
        flag_mask = 0
        for i in flag_bits:
            flag_mask |= 1 << i
        masked_mask_value = mask_value & flag_mask
        for flag_value, value in flag_defn['values'].items():
            shifted_value = int(flag_value) << flag_shift
            if shifted_value == masked_mask_value:
                assert flag_name not in return_dict
                return_dict[flag_name] = value
    return return_dict


def check_carriers(n):
    """
    Ensure if carrier of stores is defined.

    Parameters
    ----------
    n : pypsa.Network

    """
    if 'carrier' not in n.loads:
        n.loads['carrier'] = 'Load'
    if 'carrier' not in n.stores:
        n.stores['carrier'] = n.stores.bus.map(n.buses.carrier)
    if 'carrier' not in n.lines:
        n.lines['carrier'] = n.lines.bus0.map(n.buses.carrier)
    if 'carrier' not in n.links:
        n.links['carrier'] = n.links.bus0.map(n.buses.carrier)


def has_subkey(subkey: str, key: str):
    """ Check whether a string occurs as one of the "."-separated members of
    another.
    """
    return subkey in key.split('.')


def iterkeys():
    """Iterate over paths in the manifest."""


@classmethod
def delete_(cls, table, **filter_args):
    """Delete rows in the table matching ``filter_args``

        :param type table: the model class
        """
    cls.session.query(table).filter_by(**filter_args).delete()
    cls.session.commit()


def convert_bytes(num):
    """
    Convert num to idiomatic byte unit.

    :param num: the input number.
    :type num: int
    :return: str
    """
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if num < 1024.0:
            return '%3.1f %s' % (num, x)
        num /= 1024.0


def strip_leading_option_delim(args):
    """Remove leading -- if present.

    Using the "--" end of options syntax bypasses docopt's parsing of options.
    """
    if len(args) > 1:
        if args[0] == '--':
            return args[1:]
    return args


@staticmethod
def __cs_bit_add(l, r):
    """
        Private, static method: used by self.__gen_cs() to bitwise add the
        next unsigned short value to the checksum

        Args:
            l (unsigned short): current checksum value
            r (unsigned short): value to add to the current checksum value

        Returns:
            unsigned short: result of bitwise add of l and r
        """
    r += l
    return (r & 65535) + (r >> 16)


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

    The ".dev0" means dirty.

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


@classmethod
def service_declaration(cls, service_name):
    """
        Find and return a service declaration.

        XBlocks declare their service requirements with `@XBlock.needs` and
        `@XBlock.wants` decorators.  These store information on the class.
        This function finds those declarations for a block.

        Arguments:
            service_name (str): the name of the service requested.

        Returns:
            One of "need", "want", or None.
        """
    return cls._combined_services.get(service_name)


@staticmethod
def is_ready() ->bool:
    """Check if this mask mapper can be used"""
    return True


def shuffle_sublists(sublists, rand):
    """
    Shuffles the lists within a list but not the list itself.

    >>> from nutsflow.common import StableRandom
    >>> rand = StableRandom(0)

    >>> sublists = [[1, 2, 3], [4, 5, 6, 7]]
    >>> shuffle_sublists(sublists, rand)
    >>> sublists
    [[1, 3, 2], [4, 5, 7, 6]]

    :param sublists: A list containing lists
    :param Random rand: A random number generator.
    """
    for sublist in sublists:
        rand.shuffle(sublist)


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 get_args(kwargs):
    """
    Return keyword arguments while removing `self`

    Parameters
    ----------
    kwargs : dict
        The keyword arguments dictionary

    Returns
    -------
    dict

    """
    kwargs = dict(kwargs)
    kwargs.pop('self', None)
    return kwargs


@classmethod
def has_index(cls, name=None, columns=None):
    """Check if the table has an index (other than primary key)

        Search either by index name or by column name

        Args:
            name (:obj:`str`): Index name to check
            columns (:obj:`list`): List of columns making the index

        Returns:
            True or False

        Raises:
            SystemExit: If `table` object does not exists
        """
    if not cls.table_exists():
        return False
    if name is not None:
        return cls._has_named_index(name)
    if columns is not None:
        return cls._has_columns_index(columns)
    return False


def describe_security_group_references(DryRun=None, GroupId=None):
    """
    [EC2-VPC only] Describes the VPCs on the other side of a VPC peering connection that are referencing the security groups you've specified in this request.
    See also: AWS API Documentation

    :example: response = client.describe_security_group_references(
        DryRun=True|False,
        GroupId=[
            'string',
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the operation, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation. Otherwise, it is UnauthorizedOperation.

    :type GroupId: list
    :param GroupId: [REQUIRED]
            One or more security group IDs in your account.
            (string) --

    :rtype: dict
    :return: {
        'SecurityGroupReferenceSet': [
            {
                'GroupId': 'string',
                'ReferencingVpcId': 'string',
                'VpcPeeringConnectionId': 'string'
            },
        ]
    }

    """
    pass


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def get_domain_detail(DomainName=None):
    """
    This operation returns detailed information about a specified domain that is associated with the current AWS account. Contact information for the domain is also returned as part of the output.
    See also: AWS API Documentation

    :example: response = client.get_domain_detail(
        DomainName='string'
    )

    :type DomainName: string
    :param DomainName: [REQUIRED]
            The name of the domain that you want to get detailed information about.

    :rtype: dict
    :return: {
        'DomainName': 'string',
        'Nameservers': [
            {
                'Name': 'string',
                'GlueIps': [
                    'string',
                ]
            },
        ],
        'AutoRenew': True|False,
        'AdminContact': {
            'FirstName': 'string',
            'LastName': 'string',
            'ContactType': 'PERSON'|'COMPANY'|'ASSOCIATION'|'PUBLIC_BODY'|'RESELLER',
            'OrganizationName': 'string',
            'AddressLine1': 'string',
            'AddressLine2': 'string',
            'City': 'string',
            'State': 'string',
            'CountryCode': 'AD'|'AE'|'AF'|'AG'|'AI'|'AL'|'AM'|'AN'|'AO'|'AQ'|'AR'|'AS'|'AT'|'AU'|'AW'|'AZ'|'BA'|'BB'|'BD'|'BE'|'BF'|'BG'|'BH'|'BI'|'BJ'|'BL'|'BM'|'BN'|'BO'|'BR'|'BS'|'BT'|'BW'|'BY'|'BZ'|'CA'|'CC'|'CD'|'CF'|'CG'|'CH'|'CI'|'CK'|'CL'|'CM'|'CN'|'CO'|'CR'|'CU'|'CV'|'CX'|'CY'|'CZ'|'DE'|'DJ'|'DK'|'DM'|'DO'|'DZ'|'EC'|'EE'|'EG'|'ER'|'ES'|'ET'|'FI'|'FJ'|'FK'|'FM'|'FO'|'FR'|'GA'|'GB'|'GD'|'GE'|'GH'|'GI'|'GL'|'GM'|'GN'|'GQ'|'GR'|'GT'|'GU'|'GW'|'GY'|'HK'|'HN'|'HR'|'HT'|'HU'|'ID'|'IE'|'IL'|'IM'|'IN'|'IQ'|'IR'|'IS'|'IT'|'JM'|'JO'|'JP'|'KE'|'KG'|'KH'|'KI'|'KM'|'KN'|'KP'|'KR'|'KW'|'KY'|'KZ'|'LA'|'LB'|'LC'|'LI'|'LK'|'LR'|'LS'|'LT'|'LU'|'LV'|'LY'|'MA'|'MC'|'MD'|'ME'|'MF'|'MG'|'MH'|'MK'|'ML'|'MM'|'MN'|'MO'|'MP'|'MR'|'MS'|'MT'|'MU'|'MV'|'MW'|'MX'|'MY'|'MZ'|'NA'|'NC'|'NE'|'NG'|'NI'|'NL'|'NO'|'NP'|'NR'|'NU'|'NZ'|'OM'|'PA'|'PE'|'PF'|'PG'|'PH'|'PK'|'PL'|'PM'|'PN'|'PR'|'PT'|'PW'|'PY'|'QA'|'RO'|'RS'|'RU'|'RW'|'SA'|'SB'|'SC'|'SD'|'SE'|'SG'|'SH'|'SI'|'SK'|'SL'|'SM'|'SN'|'SO'|'SR'|'ST'|'SV'|'SY'|'SZ'|'TC'|'TD'|'TG'|'TH'|'TJ'|'TK'|'TL'|'TM'|'TN'|'TO'|'TR'|'TT'|'TV'|'TW'|'TZ'|'UA'|'UG'|'US'|'UY'|'UZ'|'VA'|'VC'|'VE'|'VG'|'VI'|'VN'|'VU'|'WF'|'WS'|'YE'|'YT'|'ZA'|'ZM'|'ZW',
            'ZipCode': 'string',
            'PhoneNumber': 'string',
            'Email': 'string',
            'Fax': 'string',
            'ExtraParams': [
                {
                    'Name': 'DUNS_NUMBER'|'BRAND_NUMBER'|'BIRTH_DEPARTMENT'|'BIRTH_DATE_IN_YYYY_MM_DD'|'BIRTH_COUNTRY'|'BIRTH_CITY'|'DOCUMENT_NUMBER'|'AU_ID_NUMBER'|'AU_ID_TYPE'|'CA_LEGAL_TYPE'|'CA_BUSINESS_ENTITY_TYPE'|'ES_IDENTIFICATION'|'ES_IDENTIFICATION_TYPE'|'ES_LEGAL_FORM'|'FI_BUSINESS_NUMBER'|'FI_ID_NUMBER'|'IT_PIN'|'RU_PASSPORT_DATA'|'SE_ID_NUMBER'|'SG_ID_NUMBER'|'VAT_NUMBER',
                    'Value': 'string'
                },
            ]
        },
        'RegistrantContact': {
            'FirstName': 'string',
            'LastName': 'string',
            'ContactType': 'PERSON'|'COMPANY'|'ASSOCIATION'|'PUBLIC_BODY'|'RESELLER',
            'OrganizationName': 'string',
            'AddressLine1': 'string',
            'AddressLine2': 'string',
            'City': 'string',
            'State': 'string',
            'CountryCode': 'AD'|'AE'|'AF'|'AG'|'AI'|'AL'|'AM'|'AN'|'AO'|'AQ'|'AR'|'AS'|'AT'|'AU'|'AW'|'AZ'|'BA'|'BB'|'BD'|'BE'|'BF'|'BG'|'BH'|'BI'|'BJ'|'BL'|'BM'|'BN'|'BO'|'BR'|'BS'|'BT'|'BW'|'BY'|'BZ'|'CA'|'CC'|'CD'|'CF'|'CG'|'CH'|'CI'|'CK'|'CL'|'CM'|'CN'|'CO'|'CR'|'CU'|'CV'|'CX'|'CY'|'CZ'|'DE'|'DJ'|'DK'|'DM'|'DO'|'DZ'|'EC'|'EE'|'EG'|'ER'|'ES'|'ET'|'FI'|'FJ'|'FK'|'FM'|'FO'|'FR'|'GA'|'GB'|'GD'|'GE'|'GH'|'GI'|'GL'|'GM'|'GN'|'GQ'|'GR'|'GT'|'GU'|'GW'|'GY'|'HK'|'HN'|'HR'|'HT'|'HU'|'ID'|'IE'|'IL'|'IM'|'IN'|'IQ'|'IR'|'IS'|'IT'|'JM'|'JO'|'JP'|'KE'|'KG'|'KH'|'KI'|'KM'|'KN'|'KP'|'KR'|'KW'|'KY'|'KZ'|'LA'|'LB'|'LC'|'LI'|'LK'|'LR'|'LS'|'LT'|'LU'|'LV'|'LY'|'MA'|'MC'|'MD'|'ME'|'MF'|'MG'|'MH'|'MK'|'ML'|'MM'|'MN'|'MO'|'MP'|'MR'|'MS'|'MT'|'MU'|'MV'|'MW'|'MX'|'MY'|'MZ'|'NA'|'NC'|'NE'|'NG'|'NI'|'NL'|'NO'|'NP'|'NR'|'NU'|'NZ'|'OM'|'PA'|'PE'|'PF'|'PG'|'PH'|'PK'|'PL'|'PM'|'PN'|'PR'|'PT'|'PW'|'PY'|'QA'|'RO'|'RS'|'RU'|'RW'|'SA'|'SB'|'SC'|'SD'|'SE'|'SG'|'SH'|'SI'|'SK'|'SL'|'SM'|'SN'|'SO'|'SR'|'ST'|'SV'|'SY'|'SZ'|'TC'|'TD'|'TG'|'TH'|'TJ'|'TK'|'TL'|'TM'|'TN'|'TO'|'TR'|'TT'|'TV'|'TW'|'TZ'|'UA'|'UG'|'US'|'UY'|'UZ'|'VA'|'VC'|'VE'|'VG'|'VI'|'VN'|'VU'|'WF'|'WS'|'YE'|'YT'|'ZA'|'ZM'|'ZW',
            'ZipCode': 'string',
            'PhoneNumber': 'string',
            'Email': 'string',
            'Fax': 'string',
            'ExtraParams': [
                {
                    'Name': 'DUNS_NUMBER'|'BRAND_NUMBER'|'BIRTH_DEPARTMENT'|'BIRTH_DATE_IN_YYYY_MM_DD'|'BIRTH_COUNTRY'|'BIRTH_CITY'|'DOCUMENT_NUMBER'|'AU_ID_NUMBER'|'AU_ID_TYPE'|'CA_LEGAL_TYPE'|'CA_BUSINESS_ENTITY_TYPE'|'ES_IDENTIFICATION'|'ES_IDENTIFICATION_TYPE'|'ES_LEGAL_FORM'|'FI_BUSINESS_NUMBER'|'FI_ID_NUMBER'|'IT_PIN'|'RU_PASSPORT_DATA'|'SE_ID_NUMBER'|'SG_ID_NUMBER'|'VAT_NUMBER',
                    'Value': 'string'
                },
            ]
        },
        'TechContact': {
            'FirstName': 'string',
            'LastName': 'string',
            'ContactType': 'PERSON'|'COMPANY'|'ASSOCIATION'|'PUBLIC_BODY'|'RESELLER',
            'OrganizationName': 'string',
            'AddressLine1': 'string',
            'AddressLine2': 'string',
            'City': 'string',
            'State': 'string',
            'CountryCode': 'AD'|'AE'|'AF'|'AG'|'AI'|'AL'|'AM'|'AN'|'AO'|'AQ'|'AR'|'AS'|'AT'|'AU'|'AW'|'AZ'|'BA'|'BB'|'BD'|'BE'|'BF'|'BG'|'BH'|'BI'|'BJ'|'BL'|'BM'|'BN'|'BO'|'BR'|'BS'|'BT'|'BW'|'BY'|'BZ'|'CA'|'CC'|'CD'|'CF'|'CG'|'CH'|'CI'|'CK'|'CL'|'CM'|'CN'|'CO'|'CR'|'CU'|'CV'|'CX'|'CY'|'CZ'|'DE'|'DJ'|'DK'|'DM'|'DO'|'DZ'|'EC'|'EE'|'EG'|'ER'|'ES'|'ET'|'FI'|'FJ'|'FK'|'FM'|'FO'|'FR'|'GA'|'GB'|'GD'|'GE'|'GH'|'GI'|'GL'|'GM'|'GN'|'GQ'|'GR'|'GT'|'GU'|'GW'|'GY'|'HK'|'HN'|'HR'|'HT'|'HU'|'ID'|'IE'|'IL'|'IM'|'IN'|'IQ'|'IR'|'IS'|'IT'|'JM'|'JO'|'JP'|'KE'|'KG'|'KH'|'KI'|'KM'|'KN'|'KP'|'KR'|'KW'|'KY'|'KZ'|'LA'|'LB'|'LC'|'LI'|'LK'|'LR'|'LS'|'LT'|'LU'|'LV'|'LY'|'MA'|'MC'|'MD'|'ME'|'MF'|'MG'|'MH'|'MK'|'ML'|'MM'|'MN'|'MO'|'MP'|'MR'|'MS'|'MT'|'MU'|'MV'|'MW'|'MX'|'MY'|'MZ'|'NA'|'NC'|'NE'|'NG'|'NI'|'NL'|'NO'|'NP'|'NR'|'NU'|'NZ'|'OM'|'PA'|'PE'|'PF'|'PG'|'PH'|'PK'|'PL'|'PM'|'PN'|'PR'|'PT'|'PW'|'PY'|'QA'|'RO'|'RS'|'RU'|'RW'|'SA'|'SB'|'SC'|'SD'|'SE'|'SG'|'SH'|'SI'|'SK'|'SL'|'SM'|'SN'|'SO'|'SR'|'ST'|'SV'|'SY'|'SZ'|'TC'|'TD'|'TG'|'TH'|'TJ'|'TK'|'TL'|'TM'|'TN'|'TO'|'TR'|'TT'|'TV'|'TW'|'TZ'|'UA'|'UG'|'US'|'UY'|'UZ'|'VA'|'VC'|'VE'|'VG'|'VI'|'VN'|'VU'|'WF'|'WS'|'YE'|'YT'|'ZA'|'ZM'|'ZW',
            'ZipCode': 'string',
            'PhoneNumber': 'string',
            'Email': 'string',
            'Fax': 'string',
            'ExtraParams': [
                {
                    'Name': 'DUNS_NUMBER'|'BRAND_NUMBER'|'BIRTH_DEPARTMENT'|'BIRTH_DATE_IN_YYYY_MM_DD'|'BIRTH_COUNTRY'|'BIRTH_CITY'|'DOCUMENT_NUMBER'|'AU_ID_NUMBER'|'AU_ID_TYPE'|'CA_LEGAL_TYPE'|'CA_BUSINESS_ENTITY_TYPE'|'ES_IDENTIFICATION'|'ES_IDENTIFICATION_TYPE'|'ES_LEGAL_FORM'|'FI_BUSINESS_NUMBER'|'FI_ID_NUMBER'|'IT_PIN'|'RU_PASSPORT_DATA'|'SE_ID_NUMBER'|'SG_ID_NUMBER'|'VAT_NUMBER',
                    'Value': 'string'
                },
            ]
        },
        'AdminPrivacy': True|False,
        'RegistrantPrivacy': True|False,
        'TechPrivacy': True|False,
        'RegistrarName': 'string',
        'WhoIsServer': 'string',
        'RegistrarUrl': 'string',
        'AbuseContactEmail': 'string',
        'AbuseContactPhone': 'string',
        'RegistryDomainId': 'string',
        'CreationDate': datetime(2015, 1, 1),
        'UpdatedDate': datetime(2015, 1, 1),
        'ExpirationDate': datetime(2015, 1, 1),
        'Reseller': 'string',
        'DnsSec': 'string',
        'StatusList': [
            'string',
        ]
    }

    :returns:
    (string) --

    """
    pass


def copy():
    """Copy selected text to clipboard

    """
    pass


def email_bodies(emails):
    """Return a list of email text bodies from a list of email objects"""
    body_texts = []
    for eml in emails:
        body_texts.extend(list(eml.walk())[1:])
    return body_texts


@staticmethod
def validate_training_data_stats(training_data_stats):
    """
            Method to validate the structure of training data stats
        """
    stat_keys = list(training_data_stats.keys())
    valid_stat_keys = ['means', 'mins', 'maxs', 'stds', 'feature_values',
        'feature_frequencies']
    missing_keys = list(set(valid_stat_keys) - set(stat_keys))
    if len(missing_keys) > 0:
        raise Exception('Missing keys in training_data_stats. Details: %s' %
            missing_keys)


def get_all_ips(server):
    """
        Digs out all the IPs from the server.addresses field
        of an open stack server.
    """
    output = []
    addresses = server.addresses
    for addr_list in addresses.values():
        for addr in addr_list:
            for name, val in addr.items():
                if name == 'addr':
                    output.append(val)
    return sorted(output)


def display_item(project, subject=None, session=None):
    """
    Method to display the tree

    :param project: project ID on XNAT
    :param subject: subject label on XNAT
    :param session: session label on XNAT
    :return: None
    """
    print('Project: %s' % project)
    if subject:
        print('  +Subject: %s' % subject)
        if session:
            print('    *Session: %s' % session)


def create_protection(Name=None, ResourceArn=None):
    """
    Enables AWS Shield Advanced for a specific AWS resource. The resource can be an Amazon CloudFront distribution, Elastic Load Balancing load balancer, or an Amazon Route 53 hosted zone.
    See also: AWS API Documentation

    :example: response = client.create_protection(
        Name='string',
        ResourceArn='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            Friendly name for the Protection you are creating.

    :type ResourceArn: string
    :param ResourceArn: [REQUIRED]
            The ARN (Amazon Resource Name) of the resource to be protected.

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

    """
    pass


@classmethod
def get_thermal_cpu_details(cls, session, server_key):
    """Get ALL thermal relationships between a CPU and server sensors
        Args:
            session:  database session
            server_key(int): key of the server sensors belong to
        Returns:
            list: cpu/sensor relationships
        """
    results = session.run(
        """
            MATCH (:ServerWithBMC { key: $server })-[:HAS_SENSOR]->(sensor:Sensor)
            MATCH (:CPU)<-[rel:HEATED_BY]-(sensor)
            RETURN rel, sensor
            """
        , server=server_key)
    th_cpu_details = []
    for record in results:
        sensor = dict(record.get('sensor'))
        th_cpu_details.append({'sensor': sensor, 'rel': dict(record.get(
            'rel'))})
    return th_cpu_details


def filterNonJournals(citesLst, invert=False):
    """Removes the `Citations` from _citesLst_ that are not journals

    # Parameters

    _citesLst_ : `list [Citation]`

    > A list of citations to be filtered

    _invert_ : `optional [bool]`

    > Default `False`, if `True` non-journals will be kept instead of journals

    # Returns

    `list [Citation]`

    > A filtered list of Citations from _citesLst_
    """
    retCites = []
    for c in citesLst:
        if c.isJournal():
            if not invert:
                retCites.append(c)
        elif invert:
            retCites.append(c)
    return retCites


def randomize_mac_address(apps, schema_editor):
    """
    This data migration is not necessary anymore.
    It will be squashed in future versions.
    """
    pass


@staticmethod
def isUnixsockLocation(location):
    """determine if a location string is for a Unix domain socket"""
    return location.startswith('./u:')


def _is_dynamic(module):
    """
    Return True if the module is special module that cannot be imported by its
    name.
    """
    if hasattr(module, '__file__'):
        return False
    if hasattr(module, '__spec__'):
        return module.__spec__ is None
    else:
        import imp
        try:
            path = None
            for part in module.__name__.split('.'):
                if path is not None:
                    path = [path]
                f, path, description = imp.find_module(part, path)
                if f is not None:
                    f.close()
        except ImportError:
            return True
        return False


def count_type_citizens(model, condition, exclude_jailed=True):
    """Count agents as either Quiescent/Active."""
    count = 0
    for agent in model.schedule.agents:
        if agent.breed == 'cop':
            continue
        if exclude_jailed and agent.jail_sentence:
            continue
        if agent.condition == condition:
            count += 1
    return count


@staticmethod
def setup_command_line(parser):
    """Setup the command line options for single or of literals

        Arguments:
        - `parser`: parser to load with options.
        """
    parser.add_argument('P', metavar='<P>', type=int, help='positive literals')
    parser.add_argument('N', metavar='<N>', type=int, help='negative literals')


def load_pydoc(finder, module):
    """The pydoc module will work without the Tkinter module so ignore the
       error if that module cannot be found."""
    module.IgnoreName('Tkinter')


@classmethod
def GetOutputClasses(cls):
    """Retrieves the available output classes its associated name.

    Yields:
      tuple[str, type]: output class name and type object.
    """
    for _, output_class in iter(cls._output_classes.items()):
        yield output_class.NAME, output_class


def _forced_prefix(name, ns_shortcut='xm'):
    """
    Adds short (colon) prefix if missing.
    """
    if not name.find(':') >= 0:
        name = '%s:%s' % (ns_shortcut, name)
    return name


def _add_governors_to_df(df):
    """
    Add governor info to a DF. Increases memory usage quite a bit.
    """
    i = df.index.get_level_values('i')
    dfg = df.set_index('g', append=True)
    dfg = dfg.reset_index('i')
    dfg = df.loc[dfg.index]
    dfg = dfg[['w', 'l', 'p', 'f']]
    dfg['i'] = i
    dfg = dfg.set_index('i', append=True)
    dfg.index.names = ['file', 's', 'g', 'i']
    dfg = dfg.reset_index('g', drop=True)
    for c in list(dfg.columns):
        try:
            dfg[c] = dfg[c].cat.add_categories(['ROOT'])
        except (AttributeError, ValueError):
            pass
    dfg = dfg.fillna('ROOT')
    dfg.columns = ['gw', 'gl', 'gp', 'gf']
    dfg = df.join(dfg, how='inner')
    return dfg


def lint_repeats(tool_xml, lint_ctx):
    """Lint repeat blocks in tool inputs."""
    repeats = tool_xml.findall('./inputs//repeat')
    for repeat in repeats:
        if 'name' not in repeat.attrib:
            lint_ctx.error('Repeat does not specify name attribute.')
        if 'title' not in repeat.attrib:
            lint_ctx.error('Repeat does not specify title attribute.')


def _clean_title(title):
    """Clean the Title field of some unnecessary annotations."""
    title = title.replace('<', '').replace('>', '').replace(' :', ':').split(
        '/')[0]
    return title.strip(':.,; ')


@classmethod
def apply(cls, *args, **kwargs):
    """Decorator for schema application with parameters."""
    return lambda fget: cls(fget, *args, **kwargs)


def chunk(seq, num):
    """
    cut list into n chunks
    """
    avg = len(seq) / float(num)
    out = []
    last = 0.0
    while last < len(seq):
        out.append(seq[int(last):int(last + avg)])
        last += avg
    return out


def expand_indent(line):
    """Return the amount of indentation.

    Tabs are expanded to the next multiple of 8.

    >>> expand_indent('    ')
    4
    >>> expand_indent('\\t')
    8
    >>> expand_indent('       \\t')
    8
    >>> expand_indent('        \\t')
    16
    """
    if '\t' not in line:
        return len(line) - len(line.lstrip())
    result = 0
    for char in line:
        if char == '\t':
            result = result // 8 * 8 + 8
        elif char == ' ':
            result += 1
        else:
            break
    return result


@staticmethod
def find_most_common_color(image):
    """
        Find the most common color of an image and return a tuple of color
        upon the mode of the image.

        Return:
        + An integer if the mode is grayscale;
        + A tuple (red, green, blue) of integers (0 to 255) if the mode is RGB;
        + A tuple (red, green, blue, alpha) of integers (0 to 255) if the mode is RGBA.
        """
    colors_info = image.getcolors(image.width * image.height)
    _, most_common_color = max(colors_info, key=lambda item: item[0])
    return most_common_color


def __call__(request, elements, kw):
    """ A pregenerator is a function associated by a developer with a
        :term:`route`. The pregenerator for a route is called by
        :meth:`pyramid.request.Request.route_url` in order to adjust the set
        of arguments passed to it by the user for special purposes, such as
        Pylons 'subdomain' support.  It will influence the URL returned by
        ``route_url``.

        A pregenerator should return a two-tuple of ``(elements, kw)``
        after examining the originals passed to this function, which
        are the arguments ``(request, elements, kw)``.  The simplest
        pregenerator is::

            def pregenerator(request, elements, kw):
                return elements, kw

        You can employ a pregenerator by passing a ``pregenerator``
        argument to the
        :meth:`pyramid.config.Configurator.add_route`
        function.

        """


def __plugin_list(data, db):
    """
    Get plugin list in vulnerability database

    :param data: PlecostDatabaseQuery object
    :type data: PlecostDatabaseQuery

    :return: results of query
    :rtype: str
    """
    res = []
    res_append = res.append
    res_append('[*] Plugins with vulnerabilities known:\n')
    for i, x in enumerate(db.raw(
        'SELECT DISTINCT(plugin_name) FROM PLUGIN_VULNERABILITIES;').fetchall()
        ):
        res_append('    { %s } - %s' % (i, x[0]))
    res_append('\n')
    return '\n'.join(res)


def search_fields_to_dict(fields):
    """
    In ``SearchableQuerySet`` and ``SearchableManager``, search fields
    can either be a sequence, or a dict of fields mapped to weights.
    This function converts sequences to a dict mapped to even weights,
    so that we're consistently dealing with a dict of fields mapped to
    weights, eg: ("title", "content") -> {"title": 1, "content": 1}
    """
    if not fields:
        return {}
    try:
        int(list(dict(fields).values())[0])
    except (TypeError, ValueError):
        fields = dict(zip(fields, [1] * len(fields)))
    return fields


def _LCObj1a(x=None, param=None, max_radius=None, dbg=None):
    """The objective function for the initial optimization
    process used to put the roots of the denominator of the LCBP NTF inside
    the unit circle."""
    return 1.0


def build_ieee_extended(bitstream, value):
    """writes an 80-bit IEEE extended value to BitstreamWriter
    this is used to handle AIFF's sample rate field"""
    from math import frexp
    if value < 0:
        signed = 1
        value = abs(value)
    else:
        signed = 0
    fmant, exponent = frexp(value)
    if exponent > 16384 or fmant >= 1:
        exponent = 32767
        mantissa = 0
    else:
        exponent += 16382
        mantissa = fmant * 2 ** 64
    bitstream.build('1u 15u 64U', (signed, exponent, int(mantissa)))


def _getitem_via_pathlist(external_dict, path_list, **kwargs):
    """
        y = {'c': {'b': 200}}
        _getitem_via_pathlist(y,['c','b'])
    """
    if 's2n' in kwargs:
        s2n = kwargs['s2n']
    else:
        s2n = 0
    if 'n2s' in kwargs:
        n2s = kwargs['n2s']
    else:
        n2s = 0
    this = external_dict
    for i in range(0, path_list.__len__()):
        key = path_list[i]
        if n2s == 1:
            key = str(key)
        if s2n == 1:
            try:
                int(key)
            except:
                pass
            else:
                key = int(key)
        this = this.__getitem__(key)
    return this


def simple_moving_average(iterable, k=10):
    """Returns an iterator over the simple moving average of the given list of
    values."""
    a = iterable if isinstance(iterable, list) else list(iterable)
    for m in range(len(a)):
        i = m - k
        j = m + k + 1
        w = a[max(0, i):j]
        yield float(sum(w)) / (len(w) or 1)


def select_less():
    """Reduce current selection by deselecting boundary elements

    """
    pass


@staticmethod
def _parse_dms(dms):
    """Convert a string of the form dd:mm:ss.decimal into decimal degrees.
        """
    import re
    tokens = tuple(filter(None, re.split('([\\.\\d]+)', dms.strip())))
    if len(tokens) <= 1:
        raise ValueError('string is not of the expected format')
    sign = 1
    try:
        dd = float(tokens[0])
    except ValueError:
        if tokens[0].strip() == '-':
            sign = -1
        tokens = tokens[1:]
        dd = float(tokens[0])
        if len(tokens) <= 1:
            raise ValueError('string is not of the expected format')
    if len(tokens) <= 2:
        return sign * dd
    mm = float(tokens[2])
    if len(tokens) <= 4:
        return sign * (dd + mm / 60)
    if len(tokens) >= 7:
        raise ValueError('string is not of the expected format')
    ss = float(tokens[4])
    return sign * (dd + mm / 60.0 + ss / 3600.0)


def wrap_as_boogie_manager(manager):
    """
    Wraps a manager instance as a Boogie-compatible manager.
    """
    return manager


def setnewitem_byreturnswappro(ecode, sku, lineno, amt_receivableb,
    amt_receivablea, pcond_id, groupnum, ga_dis, pa_dis, times, products):
    """
    设置返回计算后的换购商品明细的一行信息
    :param ecode: 商品（款号）
    :param sku: 条码
    :param lineno: 行号
    :param amt_receivableb:应收价
    :param amt_receivablea:应收价
    :param pcond_id: 促销优惠明细ID
    :param groupnum:标记翻倍的倍数分组
    :param ga_dis:执行的商品促销ID集合
    :param pa_dis:执行的全场促销ID集合
    :param times:
    :param products:返回的列表
    :return:
    """
    purproduct = {}
    purproduct['ecode'] = ecode
    purproduct['sku'] = sku
    purproduct['lineno'] = lineno
    purproduct['amt_receivableb'] = amt_receivableb
    purproduct['amt_receivablea'] = amt_receivablea
    purproduct['qtty'] = 1
    purproduct['pcond_id'] = pcond_id
    purproduct['groupnum'] = groupnum
    purproduct['ga_dis'] = ga_dis
    purproduct['pa_dis'] = pa_dis
    if times is not None:
        purproduct['times'] = times
    products.append(purproduct)


def is_seq(li):
    """return True if input is either a list or a tuple.
    """
    return isinstance(li, (list, tuple))


@classmethod
def get_method_decorator(cls, Klass: type, name: str) ->'method_decorator':
    """ Get the decorator object, stored as `METHOD_PROPERTY_NAME` on the wrapped method """
    return getattr(getattr(Klass, name), cls.METHOD_PROPERTY_NAME)


def get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'schema': {'schema_version': {'type': 'integer', 'default': 1},
        'action': {'schema_version': 1, 'title': 'Action', 'comment':
        'Use "add" to add a new acknowledge, or "delete" to delete an acknowledge'
        , 'type': 'string', 'default': 'add', 'allowed': ['add', 'delete']},
        'host': {'schema_version': 1, 'title': 'Host', 'comment':
        'The host concerned by the acknowledge.', 'type': 'objectid',
        'data_relation': {'resource': 'host', 'embeddable': True},
        'required': True}, 'service': {'schema_version': 1, 'title':
        'Service', 'comment': 'The service concerned by the acknowledge.',
        'type': 'objectid', 'data_relation': {'resource': 'service',
        'embeddable': True}, 'required': True, 'nullable': True}, 'user': {
        'schema_version': 1, 'title': 'User', 'comment':
        'The user concerned by the acknowledge.', 'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True},
        'required': True}, 'comment': {'schema_version': 1, 'title':
        'Comment', 'comment':
        'The comment of the acknowledge action. Free text.', 'type':
        'string', 'default': ''}, 'processed': {'schema_version': 1,
        'title': 'Processed', 'comment':
        'The action has been set on the host/service by Alignak and it can be considered as effective if processed is True'
        , 'type': 'boolean', 'default': False}, 'notified': {
        'schema_version': 1, 'title': 'Notified', 'comment':
        'The action has been fetched by the Alignak arbiter if notified is True but it is not yet to be considered as an effective scheduled downtime'
        , 'type': 'boolean', 'default': False}, 'sticky': {'schema_version':
        1, 'title': 'Sticky', 'comment':
        'If the sticky option is set, the acknowledgement will remain until the host/service recovers. Otherwise the acknowledgement will automatically be removed when the host/service state changes.'
        , 'type': 'boolean', 'default': True}, 'notify': {'schema_version':
        1, 'title': 'Notify', 'comment':
        'If the notify option is set, a notification will be sent out to contacts indicating that the current host/service problem has been acknowledged, else there will be no notification.'
        , 'type': 'boolean', 'default': False}, 'persistent': {
        'schema_version': 1, 'title': 'Persistent', 'comment':
        'Alignak always consider an acknowledge as persistent. Thus this property is of no importance and it will be removed in a future version.'
        , 'type': 'boolean', 'default': True}, '_realm': {'schema_version':
        1, 'title': 'Realm', 'comment':
        'Realm this element belongs to. Note that this property will always be forced to the value of the concerned host realm.'
        , 'type': 'objectid', 'data_relation': {'resource': 'realm',
        'embeddable': True}}, '_sub_realm': {'schema_version': 1, 'title':
        'Sub-realms', 'comment':
        'Is this element visible in the sub-realms of its realm?', 'type':
        'boolean', 'default': True}, '_users_read': {'schema_version': 1,
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'user', 'embeddable': True}}}}, 'schema_deleted': {}}