def out_16(library, session, space, offset, data, extended=False):
    """Write in an 16-bit value from the specified memory space and offset.

    Corresponds to viOut16* functions of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param space: Specifies the address space. (Constants.*SPACE*)
    :param offset: Offset (in bytes) of the address or register from which to read.
    :param data: Data to write to bus.
    :param extended: Use 64 bits offset independent of the platform.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    if extended:
        return library.viOut16Ex(session, space, offset, data, extended=False)
    else:
        return library.viOut16(session, space, offset, data, extended=False)


def glMapGrid(un: int, u1, u2, vn: int, v1, v2):
    """Define a one- or two-dimensional mesh

    :param un: Specifies the number of partitions in the grid range interval [u1, u2]. Must be positive.
    :type un: int
    :param u2: Specify the mappings for integer grid domain values i=0 and i=un.
    :param vn: Specifies the number of partitions in the grid range interval [v1, v2] (glMapGrid2 only).
    :type vn: int
    :param v2: Specify the mappings for integer grid domain values j=0 and j=vn (glMapGrid2 only).
    """
    pass


def flatten(nested_iterable):
    """
    Flatten a nested iterable into a list.

    Parameters
    ----------
    nested_iterable : list or tuple
        an iterable which can contain other iterables

    Returns
    -------
    flattened : list

    Examples
    --------
    >>> flatten([[0, 1], [2, 3]])
    [0, 1, 2, 3]
    >>> flatten([[0, 1], [[3], [4, 5]]])
    [0, 1, 3, 4, 5]
    """
    flattened = []
    stack = list(nested_iterable)[::-1]
    while len(stack) > 0:
        inp = stack.pop()
        if isinstance(inp, (tuple, list)):
            stack.extend(inp[::-1])
        else:
            flattened.append(inp)
    return flattened


def copy_and_sum_families(family_source, family_target):
    """ methods iterates thru source family and copies its entries to target family
    in case key already exists in both families - then the values are added"""
    for every in family_source:
        if every not in family_target:
            family_target[every] = family_source[every]
        else:
            family_target[every] += family_source[every]


def whitespace_tokenize(text):
    """Runs basic whitespace cleaning and splitting on a peice of text."""
    text = text.strip()
    if not text:
        return []
    tokens = text.split()
    return tokens


def _is_pdb_regex(pdb_regex):
    """Check if provided file is a pdb regex."""
    return '*' in pdb_regex


def array_core(ary):
    """
    Extract the repeated core of a broadcast array.

    Broadcast arrays are by definition non-contiguous due to repeated
    dimensions, i.e., dimensions with stride 0. In order to ascertain memory
    contiguity and copy the underlying data from such arrays, we must create
    a view without the repeated dimensions.

    """
    if not ary.strides:
        return ary
    core_index = []
    for stride in ary.strides:
        core_index.append(0 if stride == 0 else slice(None))
    return ary[tuple(core_index)]


def get_kegg_section(k_record, sname, whole_section=False):
    """Get the section with name _sname_ from a kegg compound record.

       Returns a str, possibly empty."""
    in_section = False
    section = []
    for line in k_record.splitlines():
        if line.startswith(sname):
            in_section = True
            section.append(line)
        elif in_section and line.startswith(' '):
            section.append(line)
        elif in_section and not line.startswith(' '):
            break
    if whole_section:
        sectionlines = section
    else:
        sectionlines = [line[12:] for line in section]
    return '\n'.join(sectionlines)


def df_drop_col(data, cols, destructive=False):
    """Drops one or more columns from a dataframe"""
    if destructive is False:
        data = data.copy(deep=True)
    data.drop(cols, axis=1, inplace=True)
    return data


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 feed_link():
    """return the url of this feed in feed:// format"""


def warning_test():
    """For testing warning function."""
    from warnings import warn
    from hapiclient.util import warning
    warn('Normal warning 1')
    warn('Normal warning 2')
    warning('HAPI Warning 1')
    warning('HAPI Warning 2')
    warn('Normal warning 3')
    warn('Normal warning 4')


def wigner_d_naive_v3(l, m, n, approx_lim=1000000):
    """
    Wigner "small d" matrix. (Euler z-y-z convention)
    example:
        l = 2
        m = 1
        n = 0
        beta = linspace(0,pi,100)
        wd210 = wignerd(l,m,n)(beta)

    some conditions have to be met:
         l >= 0
        -l <= m <= l
        -l <= n <= l

    The approx_lim determines at what point
    bessel functions are used. Default is when:
        l > m+10
          and
        l > n+10

    for integer l and n=0, we can use the spherical harmonics. If in
    addition m=0, we can use the ordinary legendre polynomials.
    """
    from scipy.special import jv, legendre, sph_harm, jacobi
    try:
        from scipy.misc import factorial, comb
    except:
        from scipy.special import factorial, comb
    from numpy import floor, sqrt, sin, cos, exp, power
    from math import pi
    from scipy.special import jacobi
    if l < 0 or abs(m) > l or abs(n) > l:
        raise ValueError('wignerd(l = {0}, m = {1}, n = {2}) value error.'.
            format(l, m, n) + ' Valid range for parameters: l>=0, -l<=m,n<=l.')
    if l > m + approx_lim and l > n + approx_lim:
        return lambda beta: jv(m - n, l * beta)
    if floor(l) == l and n == 0:
        if m == 0:
            return lambda beta: legendre(l)(cos(beta))
        elif False:
            a = sqrt(4.0 * pi / (2.0 * l + 1.0))
            return lambda beta: a * sph_harm(m, l, beta, 0.0).conj()
    jmn_terms = {(l + n): (m - n, m - n), (l - n): (n - m, 0.0), (l + m): (
        n - m, 0.0), (l - m): (m - n, m - n)}
    k = min(jmn_terms)
    a, lmb = jmn_terms[k]
    b = 2.0 * l - 2.0 * k - a
    if a < 0 or b < 0:
        raise ValueError('wignerd(l = {0}, m = {1}, n = {2}) value error.'.
            format(l, m, n) +
            ' Encountered negative values in (a,b) = ({0},{1})'.format(a, b))
    coeff = power(-1.0, lmb) * sqrt(comb(2.0 * l - k, k + a)) * (1.0 / sqrt
        (comb(k + b, b)))
    return lambda beta: coeff * power(sin(0.5 * beta), a) * power(cos(0.5 *
        beta), b) * jacobi(k, a, b)(cos(beta))


def isSubscribed(entity):
    """
        Returns whether entity has any subscription to this node.

        Only returns C{True} when the subscription state (if present) is
        C{'subscribed'} for any subscription that matches the bare JID.

        @param subscriber: bare JID of the subscriptions' entity.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: deferred that returns a C{bool}.
        """


def default_after_userlogin_hook(request, user, client):
    """
    Default function for setting OIDC_AFTER_USERLOGIN_HOOK.
    """
    return None


def reset_arrays(*data, **kwargs):
    """Set to zero multiple arrays

    Defined in src/operator/contrib/reset_arrays.cc:L36

    Parameters
    ----------
    data : NDArray[]
        Arrays
    num_arrays : int, required
        number of input arrays.

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

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


def keyframe_clear_v3d():
    """Remove all keyframe animation for selected objects

    """
    pass


def get_retry_count(request):
    """ Returns the current number of times the current task is being retried """
    return int(request.META.get('HTTP_X_APPENGINE_TASKRETRYCOUNT', 0))


def divmod_by(y):
    """divmod_by(y)(x) = divmod(x, y)

    Be careful with this because division is not commutative.

    You may be interested in func.flip(divmod_by) to reverse the arguments.

    >>> divmod_by(2)(4)
    (2, 0)
    >>> divmod_by(2)(5)
    (2, 1)
    >>> from .func import flip
    >>> flip(divmod_by)(5)(2)
    (2, 1)
    """
    return lambda x: divmod(x, y)


def close():
    """
        Close all pooled connections and disable the pool.
        """
    pass


@staticmethod
def build_config_dict(r: dict) ->dict:
    """Build configuration dictionary from API response."""
    if r.get('theshold') is not None:
        threshold = r.get('threshold')
    else:
        threshold = r.get('threshHold')
    return {'current_firmware_version': r.get('currentFirmVersion'),
        'latest_firmware_version': r.get('latestFirmVersion'), 'maxPower':
        r.get('maxPower'), 'threshold': threshold, 'power_protection': r.
        get('powerProtectionStatus'), 'energy_saving_status': r.get(
        'energySavingStatus')}


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 get_permission_test(model, field, permission, instance=None):
    """
    Fetch a permission test for a field and permission.

    :param model: The model or instance
    :param field: Name of the field or None for instance/model-wide
    :param permission: Permission to check for
    """
    return getattr(model, '__jsonapi_permissions__', {}).get(field, {}).get(
        permission, lambda x: True)


def clean_html(html):
    """
    Clean html tags only
    :param html: input html content
    :return: clean text
    """
    from bs4 import BeautifulSoup
    soup = BeautifulSoup(html)
    text = soup.get_text()
    return text


def _w_long(x):
    """Convert a 32-bit integer to little-endian."""
    return (int(x) & 4294967295).to_bytes(4, 'little')


def cmd(func):
    """Specifies that ``func`` returns a shell command.

    If this function is an operation function defined by :class:`~.FlowProject`, it will
    be interpreted to return a shell command, instead of executing the function itself.

    For example:

    .. code-block:: python

        @FlowProject.operation
        @flow.cmd
        def hello(job):
            return "echo {job._id}"
    """
    if getattr(func, '_flow_with_job', False):
        raise RuntimeError(
            '@cmd should appear below the @with_job decorator in your script')
    setattr(func, '_flow_cmd', True)
    return func


def get_complete_version(version=None):
    """Returns a tuple of the task_list_dev. If version argument is non-empty,
    then checks for correctness of the tuple provided.
    """
    if version is None:
        from task_list_dev import VERSION as version
    else:
        assert len(version) == 5
        assert version[3] in ('alpha', 'beta', 'rc', 'final')
    return version


def _prop_bnds_root_to_leaf_GeneralExpression(node, bnds_dict, feasibility_tol
    ):
    """
    Propagate bounds from parent to children.

    Parameters
    ----------
    node: pyomo.core.base.expression._GeneralExpressionData
    bnds_dict: ComponentMap
    feasibility_tol: float
        If the bounds computed on the body of a constraint violate the bounds of the constraint by more than
        feasibility_tol, then the constraint is considered infeasible and an exception is raised. This tolerance
        is also used when performing certain interval arithmetic operations to ensure that none of the feasible
        region is removed due to floating point arithmetic and to prevent math domain errors (a larger value
        is more conservative).
    """
    expr_lb, expr_ub = bnds_dict[node]
    bnds_dict[node.expr] = expr_lb, expr_ub


def clamp(x: float, x0: float, x1: float) ->float:
    """
    Clamp x to lie within the interval [x0, x1]

    :param x: the value to clamp
    :type x: float
    :param x0: left edge of the interval
    :type x0: float
    :param x1: right edge of the interval
    :type x1: float
    :return: x restricted to [x0, x1]
    :rtype: float
    """
    return max(x0, min(x, x1))


def compose(op, f1, f2):
    """
    A function to compose functions

    :type op: func
    :param op: A two argument function
    :type f1,f2: float, int, bool, func
    :param f1,f2: value or function, given function should take one argument,
        if value given, it will be changed in to one-argument function
    :rtype: func
    :return: A one argument function
    """
    wrap = lambda arg: arg if callable(arg) else lambda x: arg
    return lambda x: op(wrap(f1)(x), wrap(f2)(x))


def sorted_by_value(credit):
    """Return the credit dict as a sorted list by value."""
    return sorted(credit.items(), key=lambda user: user[1], reverse=True)


def text_sort_key(ex):
    """Sort using the number of tokens in the sequence."""
    if hasattr(ex, 'tgt'):
        return len(ex.src[0]), len(ex.tgt[0])
    return len(ex.src[0])


@classmethod
def shows(cls, date=None, days=None):
    """
        Returns all shows airing during the time period specified.

        :param date: Start date for the calendar. (today)
        :param days: Number of days to display starting from the date. (7)
        """
    if date:
        date = date.strftime('%Y%m%d')
    else:
        days = None
    return cls._get('calendar/shows', date, days)


def get_colname(col):
    """Look up the name associated a Spark Column.

    This functions as an inverse of `pyspark.sql.functions.col()`.

    Parameters
    ----------
    col : Column
        A Spark DataFrame Column

    Returns
    -------
    str
        The column's name.
    """
    return col._jc.toString()


def portletsToShow():
    """Get a list of portlets that will be shown.

        Returns a list of dicts with keys corresponding to that returned by
        IPortletRetriever.getPortlets(), with the additional key 'renderer'
        containing the appropriate IPortletRenderer.
        """


def translate(*args, **kw):
    """Translate method to access the translation service
           from resticted code like skins.
        """


def concepts_to_list(doc_id, analyzed, single_document=False):
    """Converts concepts response to flat lists with doc_id included

    :param doc_id: Will be inserted to each row as first element
    :param analyzed: Response json from anacode api for concepts call
    :type analyzed: list
    :param single_document: Is analysis describing just one document
    :type single_document: bool
    :return: dict -- Dictionary with two keys: 'concepts' pointing to flat list
     of found concepts and their metadata and 'concepts_surface_strings'
     pointing to flat list of strings realizing found concepts
    """
    con_list, exp_list = [], []
    for order, text_analyzed in enumerate(analyzed):
        for concept in text_analyzed:
            row = [doc_id, 0, concept.get('concept'), concept.get('freq'),
                concept.get('relevance_score'), concept.get('type')]
            if single_document:
                row[1] += order
            else:
                row[0] += order
            con_list.append(row)
            for string in concept.get('surface', []):
                surface_str, span = string['surface_string'], string['span']
                exp_list.append([row[0], row[1], concept.get('concept'),
                    surface_str, '-'.join(map(str, span))])
    return {'concepts': con_list, 'concepts_surface_strings': exp_list}


def El2Mass(Elements):
    """compute molecular weight from Elements

    :param dict Elements: elements in molecular formula;
        each must contain
        Num: number of atoms in formula
        Mass: at. wt.

    :returns: float mass: molecular weight.

    """
    mass = 0
    for El in Elements:
        mass += Elements[El]['Num'] * Elements[El]['Mass']
    return mass


@staticmethod
def _define_module_argument_spec():
    """
        Define the argument spec for the ansible module
        :return: argument spec dictionary
        """
    argument_spec = dict(location=dict(required=True), source_account_alias
        =dict(required=True, default=None), destination_account_alias=dict(
        default=None), firewall_policy_id=dict(default=None), ports=dict(
        default=None, type='list'), source=dict(defualt=None, type='list'),
        destination=dict(defualt=None, type='list'), wait=dict(default=True
        ), state=dict(default='present', choices=['present', 'absent']),
        enabled=dict(defualt=True, choices=[True, False]))
    return argument_spec


def is_complex_expr(expr):
    """Check if expression in complex

    :param expr: expression to parse
    :type expr: str
    :return: True if '(', ')', '&', '|', '!' or '*' are in expr
    :rtype: bool
    """
    for char in '()&|!*':
        if char in expr:
            return True
    return False


def text_add(radius: float=1.0, view_align: bool=False, enter_editmode:
    bool=False, location: float=(0.0, 0.0, 0.0), rotation: float=(0.0, 0.0,
    0.0), layers: bool=(False, False, False, False, False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False)):
    """Add a text object to the scene

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


def get_tukeyQcrit2(k, df, alpha=0.05):
    """
    return critical values for Tukey's HSD (Q)

    Parameters
    ----------
    k : int in {2, ..., 10}
        number of tests
    df : int
        degrees of freedom of error term
    alpha : {0.05, 0.01}
        type 1 error, 1-confidence level

    not enough error checking for limitations
    """
    from statsmodels.stats.libqsturng import qsturng
    return qsturng(1 - alpha, k, df)


def environment_filename(plan_name):
    """Generates the filename of a deployment plan's environment file
    when it is written out as a file for Heat.

    :type plan_name: str
    :rtype: str
    """
    return '%s-%s' % (plan_name, 'environment.yaml')


def default_filter(src, dst):
    """The default progress/filter callback; returns True for all files"""
    return dst


def code_to_chars(code):
    """Convert each numeric code to its corresponding characters"""
    return '\x1b[' + str(code) + 'm'


def new():
    """Create a new world Data-Block

    """
    pass


def __set_aperture(ap_in):
    """

    Make sure that aperture dictionary has correct format.

    Parameters
    ----------
    ap_in: dict
        Aperture as defined by user.

    Returns
    -------
    ap_out: dict
        Correctly formated and complete aperture dictionary

    """
    sides = ['top', 'right', 'bottom', 'left']
    ap_out = {}
    for side in sides:
        if ap_in and side in ap_in:
            ap_out[side] = ap_in[side]
        else:
            ap_out[side] = 0
    return ap_out


def node_copy_color():
    """Copy color to all selected nodes

    """
    pass


@staticmethod
def _split_kvline(key, string):
    """ Takes a field key and string, removes the key and equals sign """
    return string[len(key) + 1:].strip()


def message(client, feed_id, payload):
    """Message function will be called when a subscribed feed has a new value.
    The feed_id parameter identifies the feed, and the payload parameter has
    the new value.
    """
    print('Feed {0} received new value: {1}'.format(feed_id, payload))


def browserify_node_modules(module_name_list, output_file, babelify=False):
    """
    Browserify a list of libraries from node_modules into a single
    javascript file. Generates source maps in debug mode. Minifies the
    output in release mode.

    Note you may also specify the relative path to the module
    as ``./path/to/module`` or ``./path/to/module/file.js``.
    """
    from .modules import browserify
    if not isinstance(module_name_list, (list, tuple)):
        raise RuntimeError(
            'Browserify Node Modules compiler takes a list of node module names as input.'
            )
    return {'dependencies_fn': browserify.browserify_deps_node_modules,
        'compiler_fn': browserify.browserify_compile_node_modules, 'input':
        module_name_list, 'output': output_file, 'kwargs': {'babelify':
        babelify}}


@classmethod
def dimsOf(cls, x):
    """Calculate total dimension-set of the elements in x

        This is *extremely* messy, as it has to track nested arrays
        where the arrays could be different sizes on all sorts of
        levels...
        """
    try:
        dimensions = [len(x)]
    except (TypeError, AttributeError, ValueError) as err:
        return []
    else:
        childDimension = None
        for child in x:
            newDimension = cls.dimsOf(child)
            if childDimension is not None:
                if newDimension != childDimension:
                    raise ValueError(
                        'Non-uniform array encountered: %s versus %s' % (
                        newDimension, childDimension), x)


def _keysview_isdisjoint(view, other):
    """Return True if two sets have a null intersection."""
    for k in other:
        if k in view:
            return False
    return True


def gen_orgs(g):
    """Generator of orgs."""
    user = g.get_user()
    for org in user.get_orgs():
        print('\t{}, {} public repo(s), {} private repo(s)'.format(org.name,
            org.public_repos, org.total_private_repos))
        yield org


def validate_old_model_data(old_dict, FS):
    """ check if the old hashes match the new ones,
    otherwise we have to throw away all the old data
    """
    if 'hash_vib' not in old_dict:
        old_dict.clear()
    elif old_dict['hash_vib'] != FS.hash_vib:
        old_dict.clear()
    old_dict['hash_vib'] = FS.hash_vib
    return


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


def _get_parent(root):
    """Returns root element for a list.

    :Args:
      root (Element): lxml element of current location

    :Returns:
      lxml element representing list
    """
    elem = root
    while True:
        elem = elem.getparent()
        if elem.tag in ['ul', 'ol']:
            return elem


def prepare_table_data(table: dict, df: bytes, flavor: str) ->list:
    """
    Prepare data for mango extraction
    """
    table['table_df'] = df
    table['flavor'] = flavor
    del table['camelot_coords']
    return table


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

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


@staticmethod
def is_trainable():
    """Return True if the node can be trained, False otherwise."""
    return True


def calculate_co2_emission(phases_co2_emissions, phases_distances):
    """
    Calculates the CO2 emission of the cycle [CO2g/km].

    :param phases_co2_emissions:
        CO2 emission of cycle phases [CO2g/km].
    :type phases_co2_emissions: numpy.array

    :param phases_distances:
        Cycle phases distances [km].
    :type phases_distances: numpy.array | float

    :return:
        CO2 emission value of the cycle [CO2g/km].
    :rtype: float
    """
    n = sum(phases_co2_emissions * phases_distances)
    if isinstance(phases_distances, float):
        d = phases_distances * len(phases_co2_emissions)
    else:
        d = sum(phases_distances)
    return float(n / d)


def find_word(word: str, data: str) ->bool:
    """Find word in line"""
    if word in data:
        return True
    else:
        return False


def sanitize_dataframe(df):
    """Sanitize a DataFrame to prepare it for serialization.

    * Make a copy
    * Raise ValueError if it has a hierarchical index.
    * Convert categoricals to strings.
    * Convert np.int dtypes to Python int objects
    * Convert floats to objects and replace NaNs by None.
    * Convert DateTime dtypes into appropriate string representations
    """
    import pandas as pd
    import numpy as np
    df = df.copy()
    if isinstance(df.index, pd.core.index.MultiIndex):
        raise ValueError('Hierarchical indices not supported')
    if isinstance(df.columns, pd.core.index.MultiIndex):
        raise ValueError('Hierarchical indices not supported')
    for col_name, dtype in df.dtypes.iteritems():
        if str(dtype) == 'category':
            df[col_name] = df[col_name].astype(str)
        elif np.issubdtype(dtype, np.integer):
            df[col_name] = df[col_name].astype(object)
        elif np.issubdtype(dtype, np.floating):
            col = df[col_name].astype(object)
            df[col_name] = col.where(col.notnull(), None)
        elif str(dtype).startswith('datetime'):
            df[col_name] = df[col_name].astype(str).replace('NaT', '')
    return df


def mass_replace(string, word_dict):
    """
    Take a text and replace words that match the key in a dictionary
    with the associated value, return the changed text
    """
    for key in word_dict:
        try:
            string = string.replace(word_dict[key], key)
        except TypeError:
            for variant in word_dict[key]:
                string = string.replace(variant, key)
    return string


def delete_request(request_id):
    """Delete the request associated with the id.

        :param request_id: The unique id for the request.
        :raises KeyError: If `request_id` is not in the database.
        """


def interfaceName(iface):
    """ return a sensible name for the given interface """
    name = getattr(iface, '__name__', repr(iface))
    return getattr(iface, '__identifier__', name)


@staticmethod
def _get_message(cassette, failed_request):
    """Get the final message related to the exception"""
    best_matches = cassette.find_requests_with_most_matches(failed_request)
    if best_matches:
        best_matches_msg = (
            'Found {} similar requests with {} different matcher(s) :\n'.
            format(len(best_matches), len(best_matches[0][2])))
        for idx, best_match in enumerate(best_matches, start=1):
            request, succeeded_matchers, failed_matchers_assertion_msgs = (
                best_match)
            best_matches_msg += (
                '\n%s - (%r).\nMatchers succeeded : %s\nMatchers failed :\n' %
                (idx, request, succeeded_matchers))
            for failed_matcher, assertion_msg in failed_matchers_assertion_msgs:
                best_matches_msg += '%s - assertion failure :\n%s\n' % (
                    failed_matcher, assertion_msg)
    else:
        best_matches_msg = (
            'No similar requests, that have not been played, found.')
    return (
        """Can't overwrite existing cassette (%r) in your current record mode (%r).
No match for the request (%r) was found.
%s"""
         % (cassette._path, cassette.record_mode, failed_request,
        best_matches_msg))


def set_txtbox_cursor_pos(txtbox, x_pos, y_pos):
    """Set the cursor position of the texteditpad cursor"""
    txtbox.ppos = x_pos, y_pos
    txtbox.vpos = x_pos, y_pos


def extract_header(message_dict):
    """Extracts the header from a message dictionary.

    Parameters
    ----------
    message_dict : dict

    Returns
    -------
    str

    """
    header = message_dict['structured_text']['header']
    return header


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


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


@staticmethod
def find_chain(task_name, list_of_groups_of_chains):
    """find the chain containing the task
        :param `task_name` : The task to search for.
        :param `list_of_groups_of_chains` : list of groups of chains to search
            for the task

        :return : the list representing the chain containing task_name"""
    for group in list_of_groups_of_chains:
        for chain in group:
            if task_name in chain:
                return chain
    return None


@staticmethod
def _is_sadpanda(response):
    """Return True if the response object contains a sad panda"""
    return response.headers.get('Content-Length'
        ) == '9615' and 'sadpanda.jpg' in response.headers.get(
        'Content-Disposition', '')


def chunkify(iterable, chunksize):
    """
    Splits an iterable into chunks of size ``chunksize``. The last chunk may be smaller than ``chunksize``.
    """
    from .queryset import QuerySet
    if hasattr(iterable, '__getitem__') and not isinstance(iterable, QuerySet):
        for i in range(0, len(iterable), chunksize):
            yield iterable[i:i + chunksize]
    else:
        chunk = []
        for i in iterable:
            chunk.append(i)
            if len(chunk) == chunksize:
                yield chunk
                chunk = []
        if chunk:
            yield chunk


@classmethod
def detect(cls, old_config, new_config):
    """Detect all conflicts in given pair (old_config, new_config) and return a list of them"""
    pass


def _format_block_id(chunk_num):
    """Create a block id given a block (chunk) number
    :param int chunk_num: chunk number
    :rtype: str
    :return: block id
    """
    return '{0:08d}'.format(chunk_num)


def div_sqrt_dim(data=None, name=None, attr=None, out=None, **kwargs):
    """Rescale the input by the square root of the channel dimension.

       out = data / sqrt(data.shape[-1])

    Defined in src/operator/contrib/transformer.cc:L833

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

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

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


def binary_focal_loss(gt, pr, gamma=2.0, alpha=0.25, **kwargs):
    """Implementation of Focal Loss from the paper in binary classification

    Formula:
        loss = - gt * alpha * ((1 - pr)^gamma) * log(pr) \\
               - (1 - gt) * alpha * (pr^gamma) * log(1 - pr)

    Args:
        gt: ground truth 4D keras tensor (B, H, W, C) or (B, C, H, W)
        pr: prediction 4D keras tensor (B, H, W, C) or (B, C, H, W)
        alpha: the same as weighting factor in balanced cross entropy, default 0.25
        gamma: focusing parameter for modulating factor (1-p), default 2.0

    """
    backend = kwargs['backend']
    pr = backend.clip(pr, backend.epsilon(), 1.0 - backend.epsilon())
    loss_1 = -gt * (alpha * backend.pow(1 - pr, gamma) * backend.log(pr))
    loss_0 = -(1 - gt) * ((1 - alpha) * backend.pow(pr, gamma) * backend.
        log(1 - pr))
    loss = backend.mean(loss_0 + loss_1)
    return loss


def architecture_flag(compiler, arch, os=None):
    """
    returns flags specific to the target architecture and compiler
    """
    if not compiler or not arch:
        return ''
    if str(compiler) in ['gcc', 'apple-clang', 'clang', 'sun-cc']:
        if str(arch) in ['x86_64', 'sparcv9', 's390x']:
            return '-m64'
        elif str(arch) in ['x86', 'sparc']:
            return '-m32'
        elif str(arch) in ['s390']:
            return '-m31'
        elif os == 'AIX':
            if str(arch) in ['ppc32']:
                return '-maix32'
            elif str(arch) in ['ppc64']:
                return '-maix64'
    return ''


def descr(col):
    """Array-interface compliant full description of a column.

    This returns a 3-tuple (name, type, shape) that can always be
    used in a structured array dtype definition.
    """
    col_dtype = 'O' if col.info.dtype is None else col.info.dtype
    col_shape = col.shape[1:] if hasattr(col, 'shape') else ()
    return col.info.name, col_dtype, col_shape


def get_Tuple_params(tpl):
    """Python version independent function to obtain the parameters
    of a typing.Tuple object.
    Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
    """
    try:
        return tpl.__tuple_params__
    except AttributeError:
        try:
            if tpl.__args__ is None:
                return None
            if tpl.__args__[0] == ():
                return ()
            elif tpl.__args__[-1] is Ellipsis:
                return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None
            else:
                return tpl.__args__
        except AttributeError:
            return None


def is_uid_in_all_keys(uid, uids):
    """
    Check if uid is found in each of the uid lists for each SQL table
    :param uid: study instance uid
    :type uid: str
    :param uids: lists of study instance uids organized by SQL table
    :type uids: dict
    :return: True only if uid is found in each of the tables
    :rtype: bool
    """
    table_answer = {}
    for table in list(uids):
        table_answer[table] = False
    for table, value in uids.items():
        if uid in value:
            table_answer[table] = True
    final_answer = True
    for table, value in table_answer.items():
        if table not in 'unique':
            final_answer *= value
    return final_answer


def psi_K_CO3_SO4_HMW84(T, P):
    """c-a-a': potassium carbonate sulfate [HMW84]."""
    psi = -0.009
    valid = T == 298.15
    return psi, valid


def nearly_equal(point1, point2, ndigits=6):
    """Are the points nearly equal"""
    return round(point1[0] - point2[0], ndigits) == 0 and round(point1[1] -
        point2[1], ndigits) == 0


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 load_reverse_iptags(reverse_ip_tags, transceiver, progress_bar):
    """ Loads all the reverse IP tags individually.

        :param reverse_ip_tags: the reverse IP tags to be loaded
        :param transceiver: the transceiver object
        :rtype: None
        """
    for reverse_ip_tag in progress_bar.over(reverse_ip_tags, False):
        transceiver.set_reverse_ip_tag(reverse_ip_tag)


@staticmethod
def getNonInstallableProducts():
    """Hide in the add-ons configlet."""
    return []


def int_with_default(value, default):
    """Parse and integer from a string and return default if it fails."""
    try:
        return int(value)
    except ValueError:
        return default


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


def _chord(x, y0, y1):
    """
    Compute the area of a triangle defined by the origin and two
    points, (x,y0) and (x,y1).  This is a signed area.  If y1 > y0
    then the area will be positive, otherwise it will be negative.
    """
    return 0.5 * x * (y1 - y0)


def validate_basis_string(instr):
    """ validate that only one basis set is present,
    in a recognised format

    :param instr: content of basis set
    :return: passed
    """
    lines = instr.strip().splitlines()
    indx = 0
    try:
        anum, nshells = lines[indx].strip().split()
        anum, nshells = int(anum), int(nshells)
    except ValueError:
        raise ValueError("expected 'anum nshells': {}".format(lines[indx].
            strip()))
    for i in range(nshells):
        indx += 1
        try:
            btype, stype, nfuncs, charge, scale = lines[indx].strip().split()
            btype, stype, nfuncs = [int(i) for i in [btype, stype, nfuncs]]
            charge, scale = [float(i) for i in [charge, scale]]
        except ValueError:
            raise ValueError(
                "expected 'btype, stype, nfuncs, charge, scale': {}".format
                (lines[indx].strip()))
        if btype == 0:
            for _ in range(nfuncs):
                indx += 1
    if len(lines) > indx + 1:
        raise ValueError(
            """the basis set string contains more than one basis set or has trailing empty lines:
{}"""
            .format(instr))
    return True


def process_samples(lims_process):
    """Retrieve LIMS input samples from a process."""
    for artifact in lims_process.all_inputs():
        for lims_sample in artifact.samples:
            yield {'sample': lims_sample, 'artifact': artifact}


@classmethod
def deserialize(cls, serialized):
    """Deserializes the StridedWindowData from the Protobuf format.
        """
    in_shape = (serialized.in_height, serialized.in_width, serialized.
        in_channels)
    window_shape = serialized.window_height, serialized.window_width
    strides = serialized.stride_height, serialized.stride_width
    pad = serialized.pad_height, serialized.pad_width
    out_channels = serialized.out_channels
    return cls(in_shape, window_shape, strides, pad, out_channels)


def fix_ical_datetime_format(dt_str):
    """
    ICAL generation gives timezones in the format of 2018-06-30T14:00:00-04:00.
    The Timezone offset -04:00 has a character not recognized by the timezone offset
    code (%z).  The being the colon in -04:00.  We need it to instead be -0400
    """
    if dt_str and ':' == dt_str[-3:-2]:
        dt_str = dt_str[:-3] + dt_str[-2:]
        return dt_str
    return dt_str


def io_chunker(arr):
    """
    Assumes arr is an array of indices. Will return indices thus that
    adjacent items can be read in one go. Much faster for some cases!
    """
    idx = []
    for _i in range(len(arr)):
        if _i == 0:
            idx.append(arr[_i])
            continue
        diff = arr[_i] - arr[_i - 1]
        if diff == 1:
            if isinstance(idx[-1], list):
                idx[-1][-1] += 1
            else:
                idx[-1] = [idx[-1], idx[-1] + 2]
        else:
            idx.append(arr[_i])
    return idx


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

        :param FileDeleteCommentType val:
        :rtype: EventType
        """
    return cls('file_delete_comment', val)


def day_of_week(rdate):
    """Get the ordinal day of the week.

    Parameters
    ----------
    rdate : int
        RDate date format.

    Returns
    -------
    dw : int
        Ordinal day of the week.
    """
    dw = rdate % 7
    return dw


def _get_output(layer, index=0):
    """
    :param layer : NN Layer Proto message
    :param index : Layer output index (Default 0)
    :returns name of output at provided index if present, otherwise None
    """
    if len(layer.output) <= index:
        return None
    return layer.output[index]


@classmethod
def HomogeneousMinnaert(cls, k, alb):
    """Parameterisation for a surface BRDF based on the Minnaert BRDF model.

        The parameters are:
        - K surface parameter
        - Surface albedo

        """
    return (
        '0 Homogeneous surface\n1 (directional effects)\n5 (Minnaert model)\n%f %f\n'
         % (k, alb))


def get_cache_access_details(key=None):
    """Retrieve detailed cache information."""
    from cloudaux.gcp.decorators import _GCP_CACHE
    return _GCP_CACHE.get_access_details(key=key)


def beam_energy(event):
    """
    Gets the beam energy for an event retrieved from HiDRA at Petra III.

    HiDRA events do not usually contain beam energy information. This function takes
    the beam energy value from the configuration file, specifically from the
    'fallback_beam_energy_in_eV' entry in the 'DataRetrievalLayer' parameter group.

    Arguments:

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

    Returns:

        float: the energy of the beam in eV.
    """
    return event.framework_info['beam_energy']


@classmethod
def from_code(cls, environment, code, globals, uptodate=None):
    """Creates a template object from compiled code and the globals.  This
        is used by the loaders and environment to create a template object.
        """
    namespace = {'environment': environment, '__file__': code.co_filename}
    exec(code, namespace)
    rv = cls._from_namespace(environment, namespace, globals)
    rv._uptodate = uptodate
    return rv


def _get_col_items(mapping):
    """Get all column items to format, including both keys of `mapping`
    and MultiIndex levels if any.
    """
    from .variable import IndexVariable
    col_items = []
    for k, v in mapping.items():
        col_items.append(k)
        var = getattr(v, 'variable', v)
        if isinstance(var, IndexVariable):
            level_names = var.to_index_variable().level_names
            if level_names is not None:
                col_items += list(level_names)
    return col_items


@classmethod
def barcode_field_default(cls, width, heigth='', ratio=''):
    """Sets barcode field defaults. Applied until new defaults are applied."""
    return cls(cls.BARCODE_FIELD_DEFAULT, width, ratio, heigth)


@classmethod
def _fromJSON(cls, jsonobject):
    """Generates a new instance of :class:`maspy.core.Sii` from a decoded
        JSON object (as generated by :func:`maspy.core.Sii._reprJSON()`).

        :param jsonobject: decoded JSON object

        :returns: a new instance of :class:`Sii`
        """
    newInstance = cls(None, None)
    newInstance.__dict__.update(jsonobject)
    return newInstance


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

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

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


def apply(args=None, kwargs=None, **request):
    """Trace task execution capturing state changes and logging.

        :keyword args: Positional arguments.
        :type args: list or tuple

        :keyword kwargs: Keyword arguments.
        :type kwargs: mapping

        :param \\*\\*request: Execution request (xxx document).

        :retval: Instance of :class:`~tatoo.result.EagerResult` class.

        """


def getCubes():
    """Returns a list of ICube in the catalog."""


def build_feature_dict(opt):
    """Make mapping of feature option to feature index."""
    feature_dict = {}
    if opt['use_in_question']:
        feature_dict['in_question'] = len(feature_dict)
        feature_dict['in_question_uncased'] = len(feature_dict)
    if opt['use_tf']:
        feature_dict['tf'] = len(feature_dict)
    if opt['use_time'] > 0:
        for i in range(opt['use_time'] - 1):
            feature_dict['time=T%d' % (i + 1)] = len(feature_dict)
        feature_dict['time>=T%d' % opt['use_time']] = len(feature_dict)
    return feature_dict


@staticmethod
def is_string_equivalent(str1, str2):
    """
        Returns True if two strings are the same word regardless of case
        :param str1:
        :param str2:
        :return: bool
        """
    if str(str1).lower() == str(str2).lower():
        return True
    return False


def MakeTuple(object_):
    """
    Returns the given object as a tuple, if it is not, creates one with it inside.

    @param: Any object or tuple
        The object to tupleIZE
    """
    if isinstance(object_, tuple):
        return object_
    else:
        return object_,


@classmethod
def _get_fake_client(cls):
    """Returns python-client instance which initiated via wrong args.

        It is needed for getting client-method args and description for
        saving into DB.
        """
    return cls._client_class()


def generate_all(sumlevel, d):
    """Generate a dict that includes all of the available geoid values, with keys
    for the most common names for those values. """
    from geoid.civick import GVid
    from geoid.tiger import TigerGeoid
    from geoid.acs import AcsGeoid
    sumlevel = int(sumlevel)
    d = dict(d.items())
    if 'cousub' in d:
        d['cosub'] = d['cousub']
        del d['cousub']
    if 'blkgrp' in d:
        d['blockgroup'] = d['blkgrp']
        del d['blkgrp']
    if 'zcta5' in d:
        d['zcta'] = d['zcta5']
        del d['zcta5']
    gvid_class = GVid.resolve_summary_level(sumlevel)
    if not gvid_class:
        return {}
    geoidt_class = TigerGeoid.resolve_summary_level(sumlevel)
    geoid_class = AcsGeoid.resolve_summary_level(sumlevel)
    try:
        return dict(gvid=str(gvid_class(**d)), geoid=str(geoid_class(**d)),
            geoidt=str(geoidt_class(**d)))
    except:
        raise


def convert_float(value):
    """ Returns an float or None for empty strings. """
    if not value:
        return None
    else:
        return float(value)


def condense_rfft(X_full, num_harmonics):
    """Return real fft with fewer harmonics."""
    X_len = X_full.shape[1]
    X_red = X_full[:, :num_harmonics * 2 + 1] / X_len * (1 + 2 * num_harmonics)
    return X_red


def count_from_0(index, collection):
    """Numbering function: consecutive integers starting at 0."""
    return index


@staticmethod
def clear_sky_shortwave_radiation(ra, elevation=0.0, a_s=0.25, b_s=0.5):
    """Return the clear-sky shortwave radiation (:math:`R_{so}`) *[MJ/m²day]*. It is required for computing
        :meth:`net_longwave_radiation`.

        For near sea level or when calibrated values for :math:`a_s` and :math:`b_s` are available
        (`FAO 56 <http://www.fao.org/tempref/SD/Reserved/Agromet/PET/FAO_Irrigation_Drainage_Paper_56.pdf>`_, eq. 36,
        p. 51):

        .. math::

           R_{so} = (a_s + b_s ) R_a

        When calibrated values for :math:`a_s` and :math:`b_s` are not available
        (`FAO 56 <http://www.fao.org/tempref/SD/Reserved/Agromet/PET/FAO_Irrigation_Drainage_Paper_56.pdf>`_,
        eq. 37, p. 51):

        .. math::

           R_{so} = (0.75 + 2 * 10^{−5} z) R_a

        where :math:`z` is the station elevation above sea level *[m]*.

        :param ra: extraterrestrial radiation (:math:`R_a`) *[MJ/m²day]*. See :meth:`extraterrestrial_radiation`
        :type ra: float or np.numpy
        :param elevation: meters above sea level see (:math:`z`) [m]. See :attr:`elevation`
        :type elevation: float or np.numpy
        :param a_s: regression constant (:math:`a_s`) *[-]*. Default :math:`a_s=0.25`. It expresses the fraction of
            extraterrestrial radiation reaching the earth on overcast days (:math:`n = 0`)
        :type a_s: float or np.numpy
        :param b_s: regression constant (:math:`b_s`) *[-]*. Default :math:`b_s=0.50`. The expression
            :math:`a_s+b_s` indicates the fraction of extraterrestrial radiation reaching the earth on clear days
            (:math:`n = N`)
        :type b_s: float or np.numpy
        :return: (*float or np.numpy*) daily clear-sky shortwave radiation (:math:`R_{so}`) *[MJ/m²day]*
        """
    rs0 = (a_s + b_s + 2e-05 * elevation) * ra
    return rs0


def driver_variables_copy():
    """Copy the driver variables of the active F-Curve

    """
    pass


@classmethod
def _from_dict(cls, _dict):
    """Initialize a FontSetting object from a json dictionary."""
    args = {}
    if 'level' in _dict:
        args['level'] = _dict.get('level')
    if 'min_size' in _dict:
        args['min_size'] = _dict.get('min_size')
    if 'max_size' in _dict:
        args['max_size'] = _dict.get('max_size')
    if 'bold' in _dict:
        args['bold'] = _dict.get('bold')
    if 'italic' in _dict:
        args['italic'] = _dict.get('italic')
    if 'name' in _dict:
        args['name'] = _dict.get('name')
    return cls(**args)


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


@classmethod
def get_strings_line_num(cls, strings, substrings, start=None, end=None):
    """
        方法用于统计字符串里某个字符出现的次数
        sub -- 搜索的子字符串
        start -- 字符串开始搜索的位置。默认为第一个字符,第一个字符索引值为0。
        end -- 字符串中结束搜索的位置。字符中第一个字符的索引为 0。默认为字符串的最后一个位置。
        :param filePath:
        :return:
        """
    if start is None:
        start = 0
    if end is None:
        end = len(strings)
    return strings.count(substrings, start=start, end=end)


def checkCanSplit(context, fixt):
    """
        Callback that we use to check whether the fixtures found in a
        context or ancestor are ones we care about.

        Contexts can tell us that their fixtures are reentrant by setting
        _multiprocess_can_split_. So if we see that, we return False to
        disregard those fixtures.
        """
    if not fixt:
        return False
    if getattr(context, '_multiprocess_can_split_', False):
        return False
    return True


@classmethod
def to_ordinal(cls, d):
    """Return year ordinal for date `d`."""
    return d.year


@staticmethod
def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs):
    """Prepare a record hit from Elasticsearch for serialization."""
    links_factory = links_factory or (lambda x, **k: dict())
    record = dict(pid=pid, metadata=record_hit['_source'], links=
        links_factory(pid, record_hit=record_hit, **kwargs), revision=
        record_hit['_version'], created=None, updated=None)
    for key in ['_created', '_updated']:
        if key in record['metadata']:
            record[key[1:]] = record['metadata'][key]
            del record['metadata'][key]
    return record


def parse_header_links(value):
    """
    Return a list of Dicts of parsed link headers proxies.
    i.e. Link: <http:/.../front.jpeg>; rel=front; type="image/jpeg",
    <http://.../back.jpeg>; rel=back;type="image/jpeg"

    :param value: HTTP Link header to parse
    :return: List of Dicts
    """
    links = []
    replace_chars = ' \'"'
    for val in value.split(','):
        try:
            url, params = val.split(';', 1)
        except ValueError:
            url, params = val, ''
        link = {'url': url.strip('<> \'"')}
        for param in params.split(';'):
            try:
                key, value = param.split('=')
            except ValueError:
                break
            link[key.strip(replace_chars)] = value.strip(replace_chars)
        links.append(link)
    return links


def exit(zelf, *args, **kwargs):
    """ shutdown a bot. """
    zelf._status = ''


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


def copy_reduce(reducer, graph, target, in_data, out_size, in_map, out_map):
    """Copy target data and perform reduce based on graph structure.

    Parameters
    ----------
    reducer : str
        Type of reduction: be 'sum', 'max', 'min', 'mean', 'prod', 'none' (no
        reduction)
    graph : GraphIndex
        The graph
    target : int
        The input target (src, dst, edge)
    in_data : Tensor
        The input data
    out_size : int
        Size of first dimension of output data
    in_map : tuple
        Two input id mapping arrays, one for forward, the other for backward
    out_map : tuple
        Two output id mapping arrays, one for forward, the other for backward

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


@classmethod
def call(cls, func):
    """
        Set up builder to call the given function.
        """
    return cls(func)


def filter(function, dictionary, recursive=True):
    """

    Return those items of the dictionary for which function(item) is true. The
    item is a tuple (key,value). If function is None, return the items with
    keys that are true.
    """
    result = {}
    for key in dictionary:
        value = dictionary[key]
        if function(key, value):
            if recursive and type(value) == dict:
                value = filter(function, value)
            result[key] = value
    return result


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

        :returns: this backend supports items resuming
        """
    return True


@classmethod
def from_polysurface(cls, guid):
    """Class method for constructing a block from a Rhino poly-surface.

        Parameters
        ----------
        guid : str
            The GUID of the poly-surface.

        Returns
        -------
        Block
            The block corresponding to the poly-surface.

        Notes
        -----
        In Rhino, poly-surfaces are organised such that the cycle directions of
        the individual sub-surfaces produce normal vectors that point out of the
        enclosed volume. The normal vectors of the faces of the mesh, therefore
        also point "out" of the enclosed volume.

        """
    from compas_rhino.helpers import mesh_from_surface
    return mesh_from_surface(cls, guid)


def create_replication_instance(ReplicationInstanceIdentifier=None,
    AllocatedStorage=None, ReplicationInstanceClass=None,
    VpcSecurityGroupIds=None, AvailabilityZone=None,
    ReplicationSubnetGroupIdentifier=None, PreferredMaintenanceWindow=None,
    MultiAZ=None, EngineVersion=None, AutoMinorVersionUpgrade=None, Tags=
    None, KmsKeyId=None, PubliclyAccessible=None):
    """
    Creates the replication instance using the specified parameters.
    See also: AWS API Documentation

    :example: response = client.create_replication_instance(
        ReplicationInstanceIdentifier='string',
        AllocatedStorage=123,
        ReplicationInstanceClass='string',
        VpcSecurityGroupIds=[
            'string',
        ],
        AvailabilityZone='string',
        ReplicationSubnetGroupIdentifier='string',
        PreferredMaintenanceWindow='string',
        MultiAZ=True|False,
        EngineVersion='string',
        AutoMinorVersionUpgrade=True|False,
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        KmsKeyId='string',
        PubliclyAccessible=True|False
    )

    :type ReplicationInstanceIdentifier: string
    :param ReplicationInstanceIdentifier: [REQUIRED]
            The replication instance identifier. This parameter is stored as a lowercase string.
            Constraints:
            Must contain from 1 to 63 alphanumeric characters or hyphens.
            First character must be a letter.
            Cannot end with a hyphen or contain two consecutive hyphens.
            Example: myrepinstance

    :type AllocatedStorage: integer
    :param AllocatedStorage: The amount of storage (in gigabytes) to be initially allocated for the replication instance.

    :type ReplicationInstanceClass: string
    :param ReplicationInstanceClass: [REQUIRED]
            The compute and memory capacity of the replication instance as specified by the replication instance class.
            Valid Values: dms.t2.micro | dms.t2.small | dms.t2.medium | dms.t2.large | dms.c4.large | dms.c4.xlarge | dms.c4.2xlarge | dms.c4.4xlarge

    :type VpcSecurityGroupIds: list
    :param VpcSecurityGroupIds: Specifies the VPC security group to be used with the replication instance. The VPC security group must work with the VPC containing the replication instance.
            (string) --

    :type AvailabilityZone: string
    :param AvailabilityZone: The EC2 Availability Zone that the replication instance will be created in.
            Default: A random, system-chosen Availability Zone in the endpoint's region.
            Example: us-east-1d

    :type ReplicationSubnetGroupIdentifier: string
    :param ReplicationSubnetGroupIdentifier: A subnet group to associate with the replication instance.

    :type PreferredMaintenanceWindow: string
    :param PreferredMaintenanceWindow: The weekly time range during which system maintenance can occur, in Universal Coordinated Time (UTC).
            Format: ddd:hh24:mi-ddd:hh24:mi
            Default: A 30-minute window selected at random from an 8-hour block of time per region, occurring on a random day of the week.
            Valid Days: Mon, Tue, Wed, Thu, Fri, Sat, Sun
            Constraints: Minimum 30-minute window.

    :type MultiAZ: boolean
    :param MultiAZ: Specifies if the replication instance is a Multi-AZ deployment. You cannot set the AvailabilityZone parameter if the Multi-AZ parameter is set to true .

    :type EngineVersion: string
    :param EngineVersion: The engine version number of the replication instance.

    :type AutoMinorVersionUpgrade: boolean
    :param AutoMinorVersionUpgrade: Indicates that minor engine upgrades will be applied automatically to the replication instance during the maintenance window.
            Default: true

    :type Tags: list
    :param Tags: Tags to be associated with the replication instance.
            (dict) --
            Key (string) --A key is the required name of the tag. The string value can be from 1 to 128 Unicode characters in length and cannot be prefixed with 'aws:' or 'dms:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').
            Value (string) --A value is the optional value of the tag. The string value can be from 1 to 256 Unicode characters in length and cannot be prefixed with 'aws:' or 'dms:'. The string can only contain only the set of Unicode letters, digits, white-space, '_', '.', '/', '=', '+', '-' (Java regex: '^([\\p{L}\\p{Z}\\p{N}_.:/=+\\-]*)$').

    :type KmsKeyId: string
    :param KmsKeyId: The KMS key identifier that will be used to encrypt the content on the replication instance. If you do not specify a value for the KmsKeyId parameter, then AWS DMS will use your default encryption key. AWS KMS creates the default encryption key for your AWS account. Your AWS account has a different default encryption key for each AWS region.

    :type PubliclyAccessible: boolean
    :param PubliclyAccessible: Specifies the accessibility options for the replication instance. A value of true represents an instance with a public IP address. A value of false represents an instance with a private IP address. The default value is true .

    :rtype: dict
    :return: {
        'ReplicationInstance': {
            'ReplicationInstanceIdentifier': 'string',
            'ReplicationInstanceClass': 'string',
            'ReplicationInstanceStatus': 'string',
            'AllocatedStorage': 123,
            'InstanceCreateTime': datetime(2015, 1, 1),
            'VpcSecurityGroups': [
                {
                    'VpcSecurityGroupId': 'string',
                    'Status': 'string'
                },
            ],
            'AvailabilityZone': 'string',
            'ReplicationSubnetGroup': {
                'ReplicationSubnetGroupIdentifier': 'string',
                'ReplicationSubnetGroupDescription': 'string',
                'VpcId': 'string',
                'SubnetGroupStatus': 'string',
                'Subnets': [
                    {
                        'SubnetIdentifier': 'string',
                        'SubnetAvailabilityZone': {
                            'Name': 'string'
                        },
                        'SubnetStatus': 'string'
                    },
                ]
            },
            'PreferredMaintenanceWindow': 'string',
            'PendingModifiedValues': {
                'ReplicationInstanceClass': 'string',
                'AllocatedStorage': 123,
                'MultiAZ': True|False,
                'EngineVersion': 'string'
            },
            'MultiAZ': True|False,
            'EngineVersion': 'string',
            'AutoMinorVersionUpgrade': True|False,
            'KmsKeyId': 'string',
            'ReplicationInstanceArn': 'string',
            'ReplicationInstancePublicIpAddress': 'string',
            'ReplicationInstancePrivateIpAddress': 'string',
            'ReplicationInstancePublicIpAddresses': [
                'string',
            ],
            'ReplicationInstancePrivateIpAddresses': [
                'string',
            ],
            'PubliclyAccessible': True|False,
            'SecondaryAvailabilityZone': 'string'
        }
    }

    :returns:
    Must contain from 1 to 63 alphanumeric characters or hyphens.
    First character must be a letter.
    Cannot end with a hyphen or contain two consecutive hyphens.

    """
    pass


def StripUnicode(string, subs='.'):
    """Strip non-ASCII characters from strings

    :param str string: string to strip Unicode characters from
    :param str subs: character(s) to place into string in place of each
      Unicode character. Defaults to '.'

    :returns: a new string with only ASCII characters
    """
    s = ''
    for c in string:
        if ord(c) < 128:
            s += c
        else:
            s += subs
    return s.encode('ascii', 'replace')


def str_to_bool(text):
    """
    Transforms the strings 'True' and 'False' to their boolean counterparts.
    Raises a `ValueError` if `text` is neither of them.
    """
    text = text.lower()
    if text == 'true':
        return True
    if text == 'false':
        return False
    raise ValueError("Cannot convert '" + str(text) + "' into a boolean")


def noise_map_from_inverse_noise_map(inverse_noise_map):
    """Setup the noise map from an inverse noise map.

    The variance in each pixel is computed as:

    Variance = 1.0 / inverse_noise_map.

    Parameters
    -----------
    inverse_noise_map : ndarray
        The inverse noise_map value of each pixel which is converted to a variance.
    """
    return 1.0 / inverse_noise_map


@staticmethod
def get_value_of_key_from_list_dict(list_dict, selected_key):
    """
        Get value of key from list dict
        :param list_dict:
        :param selected_key:
        :return: list of values that have selected_key in each dict
        Ex: list_dict=[{'id': 1, 'v': 11},
                       {'id': 2, 'v': 22},
                       {'id': 3, 'v': 33}]
             selected_key='id'
          => return [1,2,3]
        """
    result_list = []
    for dict_item in list_dict:
        if selected_key in dict(dict_item).keys():
            result_list.append(dict_item.get(selected_key))
    return result_list


@staticmethod
def isFinal(state):
    """
		True if the given state finishes the game

		This happens when somebody won or when there is no possible
		move left

		:param state:  Current game state (GameState)
		:raises NotImplementedError: if child does not override this function
		"""
    raise NotImplementedError


def default(function, *args, **kwargs):
    """
    Calls ``function`` with any passed in ``args`` and ``kwargs.
    """
    function(*args, **kwargs)


def remove_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    QA = apps.get_model('questionanswers', 'QA')
    for obj in QA.objects.all():
        obj.model_obj = obj.model_obj2
        obj.save()


def find_next_comid(comid, pftable, comids, max_levels=10):
    """Crawls the PlusFlow table to find the next downstream comid that
    is in the set comids. Looks up subsequent downstream comids to a
    maximum number of iterations, specified by max_levels (default 10).
    """
    pftable = pftable.copy()
    nextocomid = [comid]
    comids = set(comids)
    for i in range(max_levels):
        nextocomid = pftable.loc[pftable.FROMCOMID.isin(nextocomid), 'TOCOMID'
            ].tolist()
        if len(set(nextocomid).intersection(comids)) > 0:
            return list(set(nextocomid).intersection(comids))[0]
    return 0


def column_convert():
    """
    Work on aggfunc for pivot_table
    """


def determine_overall_grade():
    """Just submitting: 1
        points assigned by reviewer: 1 , 2, 3
        points for just doing review: 1
        points for quality of review (assigned by submitter): 1, 2
        points for reviewing reviewer: 1
    """
    submission = {'automatic': 1}
    reviewing = {'automatic': 1}
    review_review = {'automatic': 1}


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

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

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


@classmethod
def class_exts(cls):
    """
        Return a set of the file extensions that this reader can deal with.

        Sub-classes should over-ride this function to list what extensions
        they deal with.

        The default interpretation of the returned set is 'file
        extensions including but not exclusively'.
        """
    return set()


def add_args(argparse):
    """Expand argparse instance with display-specific args."""


@staticmethod
def _setup_topic(model):
    """
        This method is needed to setup the topic.
        model = {
            'state_type': str,
            ...
        }
        """
    opt_args = model.get('optional_creation_arguments', {})
    return opt_args.get('topic', '')


@classmethod
def new_figure_manager_given_figure(cls, num, figure):
    """Create a new figure manager instance for the given figure."""
    canvas = cls.FigureCanvas(figure)
    manager = cls.FigureManager(canvas, num)
    return manager


@staticmethod
def get_state_arguments_model():
    """
        This is needed so the BaseState can validate the provided
        model has the required or optional arguments for the state
        to function.
        return = {
            'required_state_arguments': {
                'required_state_arg_1': type,
                'required_state_arg_2': type,
            },
            'optional_state_arguments': {
                'optional_state_arg_1': type,
                'optional_state_arg_2': type,
            },
        }
        """
    return {'required_state_arguments': {'current_num': int, 'is_snapshot':
        bool}, 'required_State_arguments': {}}


def active_frames_delete_all():
    """Delete the active frame(s) of all editable Grease Pencil layers

    """
    pass


def incrementar(símismo, rebanada):
    """
        Incrementa el modelo. En general, no llamarías esta función directamente.

        No se te olvide una llamada al ``super`` cuando reimplementas esta función.

        Parameters
        ----------
        rebanada: Rebanada
            La rebanada del incremento.

        """
    if símismo.corrida.extern:
        símismo.cambiar_vals(símismo.corrida.obt_extern_act())
    if símismo.corrida.clima and símismo.vars_clima:
        t = símismo.corrida.t
        símismo._act_vals_clima(t.fecha(), t.fecha_próxima() - 1 * t.fecha(
            ).freq)


@classmethod
def __prepare__(mcs, name, bases, **kwargs):
    """Prepare `namespace` to include :attr:`source_script`"""
    namespace = dict(source_script=None)
    return namespace


def remove_selected_from_list(the_list, selected_indexes):
    """
    Removes selected elements from the list.
    :param the_list:
    :param selected_indexes: list of indexes to be removed from the list
    :return: processed list
    """
    doc_len = len(the_list)
    tmp = []
    for i in range(0, doc_len):
        if i not in selected_indexes:
            tmp.append(the_list[i])
    return tmp


def copy_weights(teacher_model, student_model, layer_names):
    """Copy weights from teacher_model to student_model,
     for layers with names listed in layer_names
    """
    for name in layer_names:
        weights = teacher_model.get_layer(name=name).get_weights()
        student_model.get_layer(name=name).set_weights(weights)


def cdecl_hook(tokens):
    """Removes `cdecl`, `_cdecl`, and `__cdecl`

    Enabled by default.
    """
    for token in tokens:
        if token not in ('cdecl', '_cdecl', '__cdecl'):
            yield token


def is_leap(year):
    """Determine whether this is a leap year."""
    return year % 4 == 3 or year % 4 == -1


def syntax_warning(message, token):
    """ Raise a warning about dubious syntax.

    Parameters
    ----------
    message : string
        The message to pass to the IndentationError

    token : LexToken
        The current lextoken for the error.

    """
    import warnings
    filename = token.lexer.filename
    lineno = token.lineno
    warnings.warn_explicit(message, SyntaxWarning, filename, lineno)


def edittranslation_init():
    """Edit i18n in current language for the active button

    """
    pass


def _iloc(x, i):
    """
    Returns the item at index i or items at indices i from x,
    where x is a numpy array or pd.Series.
    """
    try:
        return x.iloc[i]
    except AttributeError:
        return x[i]


def _isThumbFunc(symbol, addr):
    """
    Checks whether the provided symbol and address is a Thumb function by
    verifying the LSB is 1 and the symbol is STT_FUNC.
    """
    return addr % 2 == 1 and symbol.is_function


def location(date=None, **kwargs):
    """Select a location expression.

    Location selectors are made up of either an id or an alias and a date
    period specifier. Use a date specification function to generate the time
    period specifier.

    ID location example:

    >>> from pprint import pprint
    >>> l = location(id='4oFkxX7RcUdirjtaenEQIV', date=recent_date(days=4))
    >>> pprint(l, width=76)
    {'location': {'date': {'recent': {'days': 4}},
                  'id': '4oFkxX7RcUdirjtaenEQIV'}}

    Alias location example:

    >>> l = location(us_zip='94103', date=absolute_date(
    ...    resolution='days', start='2012-01-01', end='2012-01-15'))
    >>> pprint(l, width=76)
    {'location': {'date': {'days': {'end': '2012-01-15',
                                    'start': '2012-01-01'}},
                  'us_zip': '94103'}}

    """
    if not len(kwargs) == 1:
        raise ValueError('Must specificy a single location id or alias')
    if date is None:
        raise ValueError('Must specificy a time period specifier')
    kwargs['date'] = date
    return {'location': kwargs}


def escape(s, quote=None):
    """Replace special characters "&", "<" and ">" to HTML-safe sequences.
    If the optional flag quote is true, the quotation mark character (")
    is also translated.

    This is the same as cgi.escape in Python, but always operates on
    bytes, whereas cgi.escape in Python 3 only works on unicodes.
    """
    s = s.replace(b'&', b'&')
    s = s.replace(b'<', b'<')
    s = s.replace(b'>', b'>')
    if quote:
        s = s.replace(b'"', b'"')
    return s


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

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

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


def _contrib_sign_ste(data=None, name=None, attr=None, out=None, **kwargs):
    """Straight-through-estimator of `sign()`.

    In forward pass, returns element-wise sign of the input (same as `sign()`).

    In backward pass, returns gradients of ``1`` everywhere (instead of ``0`` everywhere as in ``sign()``):
    :math:`\\frac{d}{dx}{sign\\_ste(x)} = 1` vs. :math:`\\frac{d}{dx}{sign(x)} = 0`.
    This is useful for quantized training.

    Reference: Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation.

    Example::
      x = sign_ste([-2, 0, 3])
      x.backward()
      x = [-1.,  0., 1.]
      x.grad() = [1.,  1., 1.]

    The storage type of ``sign_ste`` output depends upon the input storage type:
      - round_ste(default) = default
      - round_ste(row_sparse) = row_sparse
      - round_ste(csr) = csr

    Defined in src/operator/contrib/stes_op.cc:L80

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

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

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


def p_Inheritance(p):
    """Inheritance : ":" IDENTIFIER"""
    p[0] = p[2]


def pow_2_of(number):
    """
    squares input number
    helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h
    """
    return number * number


def is_django_unittest(request_or_item):
    """Returns True if the request_or_item is a Django test case, otherwise False"""
    from django.test import SimpleTestCase
    cls = getattr(request_or_item, 'cls', None)
    if cls is None:
        return False
    return issubclass(cls, SimpleTestCase)


def outer_join(a, b):
    """Let a be a list of lists and b a list. We append each element
    of b to each list in a and return the resulting list of lists."""
    outer = []
    for i in range(len(a)):
        for j in range(len(b)):
            outer += [a[i] + [b[j]]]
    return outer


def delete_db_subnet_group(DBSubnetGroupName=None):
    """
    Deletes a DB subnet group.
    See also: AWS API Documentation

    Examples
    This example deletes the specified DB subnetgroup.
    Expected Output:

    :example: response = client.delete_db_subnet_group(
        DBSubnetGroupName='string'
    )

    :type DBSubnetGroupName: string
    :param DBSubnetGroupName: [REQUIRED]
            The name of the database subnet group to delete.
            Note
            You cannot delete the default subnet group.
            Constraints:
            Constraints: Must contain no more than 255 alphanumeric characters, periods, underscores, spaces, or hyphens. Must not be default.
            Example: mySubnetgroup

    :return: response = client.delete_db_subnet_group(
        DBSubnetGroupName='mydbsubnetgroup',
    )

    print(response)

    """
    pass


@classmethod
def get_state(cls, clz):
    """
        Retrieve the state of a given Class.

        :param clz: types.ClassType
        :return: Class state.
        :rtype: dict
        """
    if clz not in cls.__shared_state:
        cls.__shared_state[clz] = clz.init_state() if hasattr(clz, 'init_state'
            ) else {}
    return cls.__shared_state[clz]


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 get_Tuple_params(tpl):
    """Python version independent function to obtain the parameters
    of a typing.Tuple object.
    Omits the ellipsis argument if present. Use is_Tuple_ellipsis for that.
    Tested with CPython 2.7, 3.5, 3.6 and Jython 2.7.1.
    """
    try:
        return tpl.__tuple_params__
    except AttributeError:
        try:
            if tpl.__args__ is None:
                return None
            if tpl.__args__[0] == ():
                return ()
            elif tpl.__args__[-1] is Ellipsis:
                return tpl.__args__[:-1] if len(tpl.__args__) > 1 else None
            else:
                return tpl.__args__
        except AttributeError:
            return None


@classmethod
def header_hash(cls, header):
    """Given a header return the hash."""
    import x11_hash
    return x11_hash.getPoWHash(header)


def check_day_frequency(df, col_name='ds'):
    """Creates a bar chart showing the frequency of the days of the week.

    Used to check that only business days are included in the dataset, and
    that there is a roughly equal distribution of entries across the week.

    :param df:               A DataFrame containing the time series to check
    :type  df:               pd.DataFrame

    :param col_name:     The name of the column of interest
    :type  col_name:     string
    """
    df['day'] = df[col_name].apply(lambda x: x.weekday_name)
    print(df['day'].value_counts())
    df['day'].value_counts().plot(kind='bar')


@classmethod
def _revision_paths(cls, rev, branch, target_platform):
    """Retrieve the API path for revision based builds"""
    if branch not in {'autoland', 'try'}:
        branch = 'mozilla-' + branch
    namespace = 'gecko.v2.' + branch + '.revision.' + rev
    product = 'mobile' if 'android' in target_platform else 'firefox'
    yield '/task/' + namespace + '.' + product + '.' + target_platform


def seat_occupied(info):
    """
        Process 'user occupied seat' event.

        Input:
        `info`  # An object with information about event's time, user's
                # callsign and aircraft, seat number and position on map.
        """


def add_dest(df_conc, dest_labware, dest_start=1):
    """Setting destination locations for samples & primers.
    Adding to df_conc:
      [dest_labware, dest_location]
    """
    dest_start = int(dest_start)
    df_conc['dest_labware'] = dest_labware
    dest_end = dest_start + df_conc.shape[0]
    df_conc['dest_location'] = list(range(dest_start, dest_end))
    return df_conc


def filter_comments(file_stream):
    """
    Filter a filestream, removing comment lines marked with an initial hash.
    """
    for line in file_stream:
        if line.startswith('#'):
            continue
        yield line


def _map_group_to_num(group_name):
    """
    Module-internal helper routine
    """
    group_map = {'engineering': 1, 'DE': 2, 'marketing': 3, 'accounting': 4,
        'finance': 5, 'executive': 6}
    return group_map[group_name]


def adjust_unit(original: dict, incoming: dict) ->dict:
    """
    Adjusts the original unit dictionary with the incoming dictionary

    :param dict original: original dictionary
    :param dict incoming: adjusting dictionary
    :return: adjusted dictionary
    :rtype: dict
    """
    out = dict(original)
    for unit in incoming:
        if unit in out:
            new = out[unit] + incoming[unit]
            if new == 0:
                del out[unit]
            else:
                out[unit] = new
        else:
            out[unit] = incoming[unit]
    return out


@staticmethod
def p_optimisation_type(p):
    """optimisation_type : OPTIMISATION_TYPE_DEFAULT
                             | OPTIMISATION_TYPE_ODT_TYPE_16
                             | OPTIMISATION_TYPE_ODT_TYPE_32
                             | OPTIMISATION_TYPE_ODT_TYPE_64
                             | OPTIMISATION_TYPE_ODT_TYPE_ALIGNMENT
                             | OPTIMISATION_TYPE_MAX_ENTRY_SIZE"""
    p[0] = p[1]


def I(*tuple, **_):
    """A nothing special identity function, does pep8 peph8 me?"""
    return tuple[0] if tuple else None


@classmethod
def from_buffer(cls, bfr, end_offset=None, bytes_value=b'\x00'):
    " Parse a BytesRunField by just skipping the specified number of bytes.\n\n        Note: this *does not* check that the skipped bytes contain `bytes_value`.\n\n        Parameters:\n        * `bfr`: the buffer to scan\n        * `end_offset`: the end offset of the scan, which may be\n          an int or Ellipsis to indicate a scan to the end of the\n          buffer\n        * `bytes_value`: the bytes value to replicate, default\n          `b'\x00'`; if this is an int then a single byte of that value\n          is used\n    "
    if end_offset is None:
        raise ValueError('missing end_offset')
    if isinstance(bytes_value, int):
        bytes_value = bytes((bytes_value,))
    offset0 = bfr.offset
    if end_offset is Ellipsis:
        for _ in bfr:
            pass
    else:
        bfr.skipto(end_offset, discard_data=True)
    field = cls(bfr.offset - offset0, bytes_value)
    return field


def no_intersections(nodes1, degree1, nodes2, degree2):
    """Determine if one triangle is in the other.

    Helper for :func:`combine_intersections` that handles the case
    of no points of intersection. In this case, either the triangles
    are disjoint or one is fully contained in the other.

    To check containment, it's enough to check if one of the corners
    is contained in the other triangle.

    Args:
        nodes1 (numpy.ndarray): The nodes defining the first triangle in
            the intersection (assumed in :math:\\mathbf{R}^2`).
        degree1 (int): The degree of the triangle given by ``nodes1``.
        nodes2 (numpy.ndarray): The nodes defining the second triangle in
            the intersection (assumed in :math:\\mathbf{R}^2`).
        degree2 (int): The degree of the triangle given by ``nodes2``.

    Returns:
        Tuple[Optional[list], Optional[bool]]: Pair (2-tuple) of

        * Edges info list; will be empty or :data:`None`
        * "Contained" boolean. If not :data:`None`, indicates
          that one of the triangles is contained in the other.
    """
    from bezier import _py_triangle_intersection
    located = _py_triangle_intersection.locate_point(nodes2, degree2,
        nodes1[0, 0], nodes1[1, 0])
    if located is not None:
        return None, True
    located = _py_triangle_intersection.locate_point(nodes1, degree1,
        nodes2[0, 0], nodes2[1, 0])
    if located is not None:
        return None, False
    return [], None


@classmethod
def from_similars(cls, learn, layer_ls: list=[0, 7, 2], **kwargs):
    """Gets the indices for the most similar images."""
    train_ds, train_idxs = cls.get_similars_idxs(learn, layer_ls, **kwargs)
    return train_ds, train_idxs


def get_precision(input_number):
    """
    Return precision of input number.

    :param input_number: input number
    :type input_number : float
    :return: precision as int
    """
    input_string = str(input_number)
    if '.' in input_string:
        splitted_input = input_string.split('.')
        return len(splitted_input[1])
    return 0


def _remove_dot_segments(path):
    """
    Remove . and .. segments from path.

    Implements 5.2.4. Remove Dot Segments.
    """
    input = path
    output = []
    while input:
        if input.startswith('./'):
            input = input[2:]
        elif input.startswith('../'):
            input = input[3:]
        elif input.startswith('/./'):
            input = input[2:]
        elif input == '/.':
            input = '/'
        elif input.startswith('/../'):
            input = input[3:]
            if output:
                output.pop()
        elif input == '/..':
            input = '/'
            if output:
                output.pop()
        elif input == '.' or input == '..':
            input = ''
        else:
            start = 1 if input.startswith('/') else 0
            i = input.find('/', start)
            if i > -1:
                output.append(input[:i])
                input = input[i:]
            else:
                output += input
                input = ''
    return ''.join(output)


def getAuthenticationToken():
    """Return the authority by which the agent perform actions."""


def psi_Ca_H_Cl_RGO81(T, P):
    """c-c': calcium hydrogen chloride [RGO81]."""
    theta = 0.0008
    valid = T == 298.15
    return theta, valid


def number_of_nodes(G, t=None):
    """Return the number of nodes in the t snpashot of a dynamic graph.

            Parameters
            ----------

            G : Graph opject
                DyNetx graph object

            t : snapshot id (default=None)
                   If None return the number of nodes in the flattened graph.

            Returns
            -------
            nnodes : int
                The number of nodes in the graph.

            See Also
            --------
            order  which is identical

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


def _merge(program, context):
    """
    Merge a context that was generated with the given program.
    """
    merged = set()
    for inst in reversed(program.insts):
        if inst.target in merged:
            continue
        else:
            merged.add(inst.target)
            if inst.ty is not None:
                if inst.ty.mutable:
                    context[inst.target] = inst.ty.combine(context[inst.target]
                        )
                else:
                    context[inst.target] = None


def _guess_type(mime):
    """
    Returns the codename used by relatorio to identify which template plugin
    it should use to render a mimetype
    """
    mime = mime.lower()
    major, stype = mime.split('/', 1)
    if major == 'application':
        if 'opendocument' in stype:
            return 'oo.org'
        else:
            return stype
    elif major == 'text':
        if stype in ('xml', 'html', 'xhtml'):
            return 'markup'
        else:
            return 'text'


@staticmethod
def __check_neighbor_pixel(x, y, color_ignore, pixel_img, dict_pixel_label,
    list_pixel_full):
    """Check directions of current pixel.
        if color of direction different background color and have label
        label of (x, y) = min(directions)
        @return: label of current pixel (int)
        """
    list_direction = [(x - 1, y), (x - 1, y - 1), (x, y - 1), (x + 1, y - 1)]
    pixel_label = []
    for direction in list_direction:
        if (direction in list_pixel_full and pixel_img[direction] !=
            color_ignore and direction in dict_pixel_label and
            dict_pixel_label[direction] not in pixel_label):
            pixel_label.append(dict_pixel_label[direction])
    return pixel_label


@staticmethod
def info(message, *args, **_kwargs):
    """Displays an info message to the default output stream

        Default implementation just directs output to stdout. Use a logging
        mixin class to customize this behavior.

        See :class:`friendlyshell.basic_logger_mixin.BasicLoggerMixin` for
        examples.

        :param str message: text to be displayed"""
    print(message % args)


def noneorcomplex(s):
    """Turn empty or 'none' to None, else evaluate to complex."""
    if s.lower() in ('', 'none'):
        return None
    else:
        return complex(eval(s, {}, {}))


@staticmethod
def get_url(fmt='json'):
    """
        Get the URL used to push the configuration to the APIC
        if no format parameter is specified, the format will be 'json'
        otherwise it will return '/api/mo/uni.' with the format string
        appended.

        :param fmt: optional format string, default is 'json'
        :returns: URL string
        """
    return '/api/mo/uni/infra.' + fmt


def addToTitle(title, valueToAdd, seperator):
    """
    Combindes values to new title
    :type seperator: str seperator character
    :param valueToAdd: str value
    :param title: Task title without seperator
    :return:
    """
    return str(title + ' ' + seperator + valueToAdd)


def update_view(url):
    """This action will update the current container view with provided url.

    See 'Container.Update()' at
    http://kodi.wiki/view/List_of_built-in_functions
    """
    return 'Container.Update(%s)' % url


def time_to_ssmmm(time_value):
    """
    Format the given time value into a ``SS.mmm`` string.

    Examples: ::

        12        => 12.000
        12.345    => 12.345
        12.345432 => 12.345
        12.345678 => 12.346

    :param float time_value: a time value, in seconds
    :rtype: string
    """
    if time_value is None:
        time_value = 0
    return '%.3f' % time_value


def find_allowed_size(nx_size):
    """
    Finds the next largest "allowed size" for the Fried Phase Screen method

    Parameters:
        nx_size (int): Requested size

    Returns:
        int: Next allowed size
    """
    n = 0
    while 2 ** n + 1 < nx_size:
        n += 1
    nx_size = 2 ** n + 1
    return nx_size


def get_terms_matrix(terms_condidate, terms_chosen):
    """生成与ERRs等对应的候选项字符串矩阵

    Args:
        terms_condidate (np.ndarray): 候选项集合
        terms_chosen (np.ndarray): 被选择的候选项的下标
    """
    return terms_condidate[terms_chosen - 1]


def asnumpy(input):
    """Convert the input tensor to numpy array.

    The data is copied.

    Parameters
    ----------
    input : Tensor
        The input tensor.

    Returns
    -------
    numpy.ndarray
        Numpy array.
    """
    pass


def load_projection_matrix(matrix: 'mathutils.Matrix'):
    """Load a projection matrix into the stack.

    :param matrix: A 4x4 matrix.
    :type matrix: 'mathutils.Matrix'
    """
    pass


def unlock():
    """Unlock the active strip so that it can’t be transformed

    """
    pass


def version_from_string(version_str):
    """ Convert a version string of the form m, m.n or m.n.o to an encoded
    version number (or None if it was an invalid format).  version_str is the
    version string.
    """
    parts = version_str.split('.')
    if not isinstance(parts, list):
        return None
    if len(parts) == 1:
        parts.append('0')
    if len(parts) == 2:
        parts.append('0')
    if len(parts) != 3:
        return None
    version = 0
    for part in parts:
        try:
            v = int(part)
        except ValueError:
            return None
        version = (version << 8) + v
    return version


def split_mpi_user_prog(cmds):
    """An ad-hoc parser that splits mpiexec args and user program's args"""
    opt_with_one_arg = ['-H', '-host', '--host', '-machinefile',
        '--machinefile', '-hostfile', '--hostfile', '-c', '-n', '--n',
        '-np', '-npersocker', '--npersocker', '-npernode', '--npernode',
        '--map-by', '--rank-by', '--bind-to', '-cpus-per-proc',
        '--cpus-per-proc', '-cpus-per-rank', '--cpus-per-rank',
        '-slot-list', '--slot-list', '-rf', '--rankfile',
        '-output-filename', '--output-filename', '-stdin', '--stdin',
        '-xterm', '--xterm', '-path', '--path', '--prefix',
        '--preload-files', '--preload-files-dest-dir', '--tmpdir', '-wd',
        '-wdir', '-x', '-tune', '--tune', '-aborted', '--aborted', '--app',
        '-cf', '--cartofile', '-ompi-server', '--ompi-server',
        '-report-pid', '--report-pid-report-uri', '--report-uri',
        '-server-wait-time', '--server-wait-time']
    opt_with_two_arg = ['--gmca', '--mca']
    idx = 0
    while True:
        if cmds[idx] in opt_with_one_arg:
            idx += 2
        elif cmds[idx] in opt_with_two_arg:
            idx += 3
        elif cmds[idx].startswith('-'):
            idx += 1
        else:
            break
    return cmds[:idx], cmds[idx:]


def check_variable_list_are_valid(variable_type_dict):
    """
    Checks that the provided variable_type_dict is valid, by:

     - Confirming there is no overlap between all variable lists

    :param variable_type_dict: A dictionary, with keys describing variables types, and values listing particular
        variables
    :type variable_type_dict: {str:[str]}
    :return: True, if there is no overlap
    :rtype: bool
    """
    for outer_key, outer_value in variable_type_dict.items():
        for inner_key, inner_value in variable_type_dict.items():
            if inner_key == outer_key:
                continue
            else:
                intersection = set(outer_value).intersection(set(inner_value))
                if len(intersection) > 0:
                    raise ValueError(
                        'Variable lists {} and {} overlap, and share key(s): {}'
                        .format(inner_key, outer_key, intersection))
    return True


def cummin(x):
    """A python implementation of the cummin function in R"""
    for i in range(1, len(x)):
        if x[i - 1] < x[i]:
            x[i] = x[i - 1]
    return x


@classmethod
def score_to_file(cls, deployment, intake_path, output_path, **kwargs):
    """
        Create new batch prediction job, upload the scoring dataset and
        download the scored CSV file concurrently.

        Will block until the entire file is scored.

        Refer to the `create` method for details on the other `kwargs`
        parameters.

        Attributes
        ----------
        deployment : Deployment or string ID
            Deployment which will be used for scoring.

        intake_path : file-like object/string path to file/pandas.DataFrame
              Scoring data

        output_path : str
            Filename to save the result under

        Returns
        -------
        BatchPredictionJob
            Instance of BatchPredictonJob
        """
    kwargs['intake_settings'] = {'type': 'local_file', 'file': intake_path}
    kwargs['output_settings'] = {'type': 'local_file', 'path': output_path}
    return cls.score(deployment, **kwargs)


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

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

    """
    pass


def formula_2009_01_01(foyer_fiscal, period, parameters):
    """
        Investissements OUTRE-MER dans le secteur du logement et autres secteurs d’activité
        2009
        """
    f7qb = foyer_fiscal('f7qb', period)
    f7qc = foyer_fiscal('f7qc', period)
    f7qd = foyer_fiscal('f7qd', period)
    f7qk = foyer_fiscal('f7qk', period)
    return f7qb + f7qc + f7qd + f7qk / 2


def hex2dec(hex, base=16):
    """ Like hex(), but to string """
    hex = hex.upper()
    retval = 0
    chars = '0123456789ABCDEF'
    for count in range(len(hex)):
        value = base ** count
        c = hex[-(count + 1)]
        if c in chars:
            retval += chars.index(c) * value
    return retval


def node_associations(enum):
    """Returns dicts associating nodes -> names and vice versa from an enum.

    Given an enum, returns the dict of names to numbers and numbers to
    names.
    """
    node_to_name = {}
    name_to_node = {}
    for key, value in enum.__dict__.items():
        if not key.startswith('_'):
            node_to_name[value] = key
            name_to_node[key] = value
    return node_to_name, name_to_node


def chunkify(rg, n_max=1000):
    """
    generates sublists of at most n_max
    elements from the provided array
    :param rg: list
    :param n_max: the maximum sublist length
    :return:
    """
    m, n_len = 0, len(rg)
    while m < n_len:
        l, m = m, m + n_max
        yield rg[l:m]


def get_numpy_include_path():
    """
    Gets the path to the numpy headers.
    """
    import builtins
    if hasattr(builtins, '__NUMPY_SETUP__'):
        del builtins.__NUMPY_SETUP__
    import imp
    import numpy
    imp.reload(numpy)
    try:
        numpy_include = numpy.get_include()
    except AttributeError:
        numpy_include = numpy.get_numpy_include()
    return numpy_include


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


def set_dict_val(name, key, val):
    """Set value for dictionary in this class"""
    globals()[name][key] = val


def _evolve_chain(niterations_chain):
    """Evolves a chain for some number of iterations.

    This is used by ``Sampler.run`` to evolve a collection of chains in a
    parallel environment. This is not a staticmethod of ``Sampler`` because
    such functions need to be picklable when using python's multiprocessing
    pool.

    Parameters
    ----------
    niterations_chain : tuple of int, chain
        The number of iterations to run on the given chain.
    """
    niterations, chain = niterations_chain
    for _ in range(niterations):
        chain.step()
    return chain


def merge_stats(left, right):
    """Add `right`'s values to `left` (modifies `left` in-place)"""
    for k, val in getattr(right, 'iteritems', right.items)():
        if isinstance(val, int):
            left[k] += val
        elif hasattr(val, 'extend'):
            left[k].extend(val)
        elif hasattr(val, 'update'):
            left[k].update(val)
        else:
            raise TypeError(val)
    return left