def Edit_String_SimulData(data):
    """
    return string object made of lines which contains laue spots properties

    Called to be Edited in LaueToolsframe.control

    params:

    data tuple of spots properties
    data =(list_twicetheta, list_chi, list_energy, list_Miller, list_posX, list_posY,
           ListName, nb of(parent) grains,
            calibration parameters list, total nb of grains)
    """
    nb_total_grains = data[9]
    lines = 'Simulation Data from LAUE Pattern Program v1.0 2009 \n'
    lines += 'Total number of grains : %s\n' % int(nb_total_grains)
    lines += 'spot# h k l E 2theta chi X Y\n'
    nb = data[7]
    if type(nb) == type(5):
        nb_grains = data[7]
        TWT, CHI, ENE, MIL, XX, YY = data[:6]
        NAME = data[6]
        calib = data[8]
        for index_grain in range(nb_grains):
            nb_of_simulspots = len(TWT[index_grain])
            startgrain = '#G %d\t%s\t%d\n' % (index_grain, NAME[index_grain
                ], nb_of_simulspots)
            lines += startgrain
            for data_index in range(nb_of_simulspots):
                linedata = '%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' % (
                    data_index, MIL[index_grain][data_index][0], MIL[
                    index_grain][data_index][1], MIL[index_grain][
                    data_index][2], ENE[index_grain][data_index], TWT[
                    index_grain][data_index], CHI[index_grain][data_index],
                    XX[index_grain][data_index], YY[index_grain][data_index])
                lines += linedata
        lines += '#calibration parameters\n'
        for param in calib:
            lines += '# %s\n' % param
        return lines
    if isinstance(nb, list):
        print('nb in Edit_String_SimulData', nb)
        gen_i = 0
        TWT, CHI, ENE, MIL, XX, YY = data[:6]
        NAME = data[6]
        calib = data[8]
        for grain_ind in range(len(nb)):
            for tt in range(nb[grain_ind][1]):
                nb_of_simulspots = len(TWT[gen_i])
                startgrain = '#G %d\t%s\t%d\t%d\n' % (grain_ind, NAME[
                    grain_ind], tt, nb_of_simulspots)
                lines += startgrain
                for data_index in range(nb_of_simulspots):
                    linedata = (
                        '%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' %
                        (data_index, MIL[gen_i][data_index][0], MIL[gen_i][
                        data_index][1], MIL[gen_i][data_index][2], ENE[
                        gen_i][data_index], TWT[gen_i][data_index], CHI[
                        gen_i][data_index], XX[gen_i][data_index], YY[gen_i
                        ][data_index]))
                    lines += linedata
                gen_i += 1
        lines += '#calibration parameters\n'
        for param in calib:
            lines += '# %s\n' % param
        return lines


@staticmethod
def gui_dict():
    """
        Return a dictionary with functions that will be shown in the
        configuration gui for the calculator node.

        Each dictionary in the globals_dict represents another level of
        subcategories in the tree view. The keys of the dict is used as labels
        for the subcategories. A list represents a list of functions.

        Each function in the list should be a tuple of three elements: label,
        code, tooltip/documentation.

        For example:

        {'My functions': [
            ('My function 1', 'myplugin.func1()',
             "My function 1 is awesome..."),
            ('My function 2', 'myplugin.func2()',
             "My function 1 is also awesome...")]}

        This should result in a top level category called "My functions"
        containing the two functions "My function 1" and "My function 2".
        """
    return {}


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

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


@classmethod
def _segment(cls, segment):
    """
        Returns a property capable of setting and getting a segment.
        """
    return property(fget=lambda x: cls._get_segment(x, segment), fset=lambda
        x, v: cls._set_segment(x, segment, v))


def _coerce_field_name(field_name, field_index):
    """
    Coerce a field_name (which may be a callable) to a string.
    """
    if callable(field_name):
        if field_name.__name__ == '<lambda>':
            return 'lambda' + str(field_index)
        else:
            return field_name.__name__
    return field_name


def psi_H_Na_CO3_HMW84(T, P):
    """c-c'-a: hydrogen sodium carbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def split_name_length(name):
    """Split name and length from a name like CubeYF_8"""
    split = name.split('_')
    return split[0], int(split[1])


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 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 ensure_iter(var):
    """Ensures that variable is iterable. If it's not by itself, return it
       as an element of a tuple"""
    if getattr(var, '__iter__', False):
        return var
    return var,


def pytest_report_header(config, startdir):
    """ return a string or list of strings to be displayed as header info for terminal reporting.

    :param _pytest.config.Config config: pytest config object
    :param startdir: py.path object with the starting dir

    .. note::

        This function should be implemented only in plugins or ``conftest.py``
        files situated at the tests root directory due to how pytest
        :ref:`discovers plugins during startup <pluginorder>`.
    """


def _computer_get_remote_username(transport, scheduler, authinfo):
    """Internal test to check if it is possible to determine the username on the remote.

    :param transport: an open transport
    :param scheduler: the corresponding scheduler class
    :param authinfo: the AuthInfo object
    :return: tuple of boolean indicating success or failure and an optional string message
    """
    remote_user = transport.whoami()
    return True, remote_user


def rewrite_type(input_data):
    """
    Fix for legacy appenlight clients
    """
    if input_data == 'remote_call':
        return 'remote'
    return input_data


def add_params(p1, p2):
    """
    Add two lists of parameters
    """
    res = []
    for x, y in zip(p1, p2):
        res.append(x + y)
    return res


@classmethod
def size(cls):
    """
        Return the number of elements in the field.
        """
    return cls.characteristic() ** cls.power()


@staticmethod
def compress(tensor):
    """Compresses a tensor and returns it with the context needed to decompress it."""
    pass


def registerConfiglet(id, name, action, condition='', permission='',
    category='Plone', visible=1, appId=None, imageUrl=None, description='',
    REQUEST=None):
    """ Registration of a Configlet """


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

        :param FileRequestsEmailsEnabledDetails val:
        :rtype: EventDetails
        """
    return cls('file_requests_emails_enabled_details', val)


def create(name: str='Group'):
    """Create an object group from selected objects

    :param name: Name, Name of the new group
    :type name: str
    """
    pass


@classmethod
def add_finalizer(cls, id, weak_ref):
    """Registers a finalizer with an id.

        :param id: The id of the object referenced by the weak reference.
        :param weak_ref: The weak reference to register.
        """
    with cls.lock:
        cls.finalizers[id] = weak_ref


def _tracking_uri(tracking_uri):
    """Helper function for URI shorthands.

    Parameters
    ----------
    tracking_uri: str
        "file" will translate to `None`,
        "localhost" to "http://localhost:5000", and
        "localhost-2" to "http://localhost:5002".

    Returns
    -------
    str or None
    """
    if tracking_uri == 'file':
        tracking_uri = None
    elif tracking_uri is not None and tracking_uri.startswith('localhost'):
        split = tracking_uri.split('-')
        port = 5000
        if len(split) > 1:
            port += int(split[1])
        tracking_uri = 'http://localhost:{}'.format(port)
    else:
        tracking_uri = tracking_uri
    return tracking_uri


def PolsOther(t):
    """Number of policies: Other benefits"""
    return 0


def findMeshReferenceImage(overlayList, overlay):
    """Searches the :class:`.OverlayList` and tries to identify a reference
    image for the given :class:`.Mesh` overlay. Returns the identified
    overlay, or ``None`` if one can't be found.
    """
    import fsl.data.vtk as fslvtk
    if not isinstance(overlay, fslvtk.VTKMesh):
        return None
    try:
        prefix = fslvtk.getFIRSTPrefix(overlay.dataSource)
        for ovl in overlayList:
            if prefix.startswith(ovl.name):
                return ovl
    except Exception:
        pass
    return None


def iconcat(a, b):
    """Same as a += b, for a and b sequences."""
    if not hasattr(a, '__getitem__'):
        msg = "'%s' object can't be concatenated" % type(a).__name__
        raise TypeError(msg)
    a += b
    return a


def get_physical_mapping(monitors):
    """
    Returns a list of Xinerama screen indices in their physical order.
    Where physical order is defined as left-to-right and then top-to-bottom.

    :param monitors:  List of (x, y, w, h) rectangles
    :rtype:           List of Xinerama indices
    """
    retval = []
    tosort = []
    for i, (x, y, w, h) in enumerate(monitors):
        tosort.append((x, y, i))
    for x, y, xscreen in sorted(tosort):
        retval.append(xscreen)
    return retval


def sma(df, s, period, column):
    """Gets simple moving average

    Args:
        df (DataFrame): data
        s (slice): the slice object
        period (int): size of the moving period
        column (str): column name to calculate

    Returns:
        pandas.Series
    """
    return df[column][s].rolling(min_periods=period, window=period, center=
        False).mean(), period


def seqlen(lst, schema, min_len, max_len):
    """
    !~~seqlen(min,max)
        corresponding sequences in documents must have a length between
        min and max, included.
    """
    return min_len <= len(lst) <= max_len


@classmethod
def table_name_col(cls):
    """
        Return the name of the metadata column used to store the feature table
        name.
        """
    return 'f_table_name'


def version(val):
    """Calculate a string version from an integer value."""
    if val / 100.0 > 2.0:
        ver = val / 100.0
    else:
        ver = val / 10.0
    return '{:.1f}'.format(ver)


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

        :param RemoveFolderMemberError val:
        :rtype: JobError
        """
    return cls('remove_folder_member_error', val)


@staticmethod
def from_caliper(filename, query):
    """Read in a Caliper `cali` file.

        Args:
            filename (str): name of a Caliper output file in `.cali` format
            query (str): cali-query in CalQL format
        """
    from .readers.caliper_reader import CaliperReader
    return CaliperReader(filename, query).read()


def context_scale_float(data_path: str='', value: float=1.0):
    """Scale a float context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assign value
    :type value: float
    """
    pass


def put(task):
    """Put task into queue; Called by transaction data manager"""


def is_coroutine(function):
    """Returns True if the passed in function is a coroutine"""
    return function.__code__.co_flags & 128 or getattr(function,
        '_is_coroutine', False)


def is_soft_clipped(read):
    """Function that checks the CIGAR string of the sam file and returns true if the read is soft-clipped"""
    match = 0
    for cigar in read.cigar:
        if cigar[0] == 4:
            match += 1
        else:
            pass
    if match > 0:
        return True
    else:
        return False


def is_orca(f):
    """
    Check if the input file is ORCA file format.

    Parameters
    ----------
    f : str
        User input filename.

    Returns
    -------
    bool : bool
        If file is ORCA output file, return True.

    See Also
    --------
    get_coord_orca :
        Find atomic coordinates of molecule from ORCA file.

    Examples
    --------
    >>> orca.out
    ---------------------------------
    CARTESIAN COORDINATES (ANGSTROEM)
    ---------------------------------
      C      0.009657    0.000000    0.005576
      C      0.009657   -0.000000    1.394424
      C      1.212436   -0.000000    2.088849
      C      2.415214    0.000000    1.394425
      C      2.415214   -0.000000    0.005575
    ...

    """
    orca_file = open(f, 'r')
    nline = orca_file.readlines()
    for i in range(len(nline)):
        if 'CARTESIAN COORDINATES (ANGSTROEM)' in nline[i]:
            return True
    return False


def logRequest(ip, message):
    """Logs the ip address and message at the appropriate place."""


@staticmethod
def _checkVerbosity(invVerbosity):
    """
        Check for valid values of invVerbosity (if invalid an exception is thrown)
        :param invVerbosity: [int or str]
        :return: None
        """
    if type(invVerbosity) is str:
        if invVerbosity == '':
            raise ValueError('Passed empty string!')
        if invVerbosity.isdigit():
            pass
        elif invVerbosity[0] == '-':
            if invVerbosity[1:].isdigit():
                pass
            else:
                raise ValueError('Passed str could not be converted to int!')
        else:
            raise ValueError('Passed invalid str!')
    elif type(invVerbosity) is int:
        pass
    else:
        raise TypeError('Type must be either str or int!')


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

    The ".dev0" means dirty.

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


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


@staticmethod
def _warning(source, msg, category=Warning):
    """Return a Warning object with source description."""
    if isinstance(source, str):
        msg = f'@{source}: ' + msg
    elif source:
        msg = f'@{type(source).__name__} {str(source)}: ' + msg
    return category(msg)


def __ne__(A, other):
    """Returns true if both objects are not equal"""
    return not A == other


@staticmethod
def _get_mainchain(df, invert):
    """Return only main chain atom entries from a DataFrame"""
    if invert:
        mc = df[(df['atom_name'] != 'C') & (df['atom_name'] != 'O') & (df[
            'atom_name'] != 'N') & (df['atom_name'] != 'CA')]
    else:
        mc = df[(df['atom_name'] == 'C') | (df['atom_name'] == 'O') | (df[
            'atom_name'] == 'N') | (df['atom_name'] == 'CA')]
    return mc


def twiceTriangleArea(p0, p1, p2):
    """Returns twice the signed area of the triangle specified by the
    2D numpy points (p0, p1, p2)."""
    p1 = p1 - p0
    p2 = p2 - p0
    return p1[0] * p2[1] - p2[0] * p1[1]


def _detect_pybcrypt():
    """
    internal helper which tries to distinguish pybcrypt vs bcrypt.

    :returns:
        True if cext-based py-bcrypt,
        False if ffi-based bcrypt,
        None if 'bcrypt' module not found.

    .. versionchanged:: 1.6.3

        Now assuming bcrypt installed, unless py-bcrypt explicitly detected.
        Previous releases assumed py-bcrypt by default.

        Making this change since py-bcrypt is (apparently) unmaintained and static,
        whereas bcrypt is being actively maintained, and it's internal structure may shift.
    """
    try:
        import bcrypt
    except ImportError:
        return None
    try:
        from bcrypt._bcrypt import __version__
    except ImportError:
        return False
    return True


def lookupNameservers(name, timeout=None):
    """
        Perform an NS record lookup.

        @type name: C{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


def pandas_fillna(df, by, hasna=None, suffix=None):
    """
    Replaces the :epkg:`nan` values for something not :epkg:`nan`.
    Mostly used by @see fn pandas_groupby_nan.

    @param      df      dataframe
    @param      by      list of columns for which we need to replace nan
    @param      hasna   None or list of columns for which we need to replace NaN
    @param      suffix  use a prefix for the NaN value
    @return             list of values chosen for each column, new dataframe (new copy)
    """
    suffix = suffix if suffix else '²'
    df = df.copy()
    rep = {}
    for c in by:
        if hasna is not None and c not in hasna:
            continue
        if df[c].dtype in (str, bytes, object):
            se = set(df[c].dropna())
            val = se.pop()
            if isinstance(val, str):
                cst = suffix
                val = ''
            elif isinstance(val, bytes):
                cst = b'_'
            else:
                raise TypeError(
                    "Unable to determine a constant for type='{0}' dtype='{1}'"
                    .format(val, df[c].dtype))
            val += cst
            while val in se:
                val += suffix
            df[c].fillna(val, inplace=True)
            rep[c] = val
        else:
            dr = df[c].dropna()
            mi = abs(dr.min())
            ma = abs(dr.max())
            val = ma + mi
            if val <= ma:
                raise ValueError(
                    "Unable to find a different value for column '{0}': min={1} max={2}"
                    .format(val, mi, ma))
            df[c].fillna(val, inplace=True)
            rep[c] = val
    return rep, df


def elemwise_div(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs):
    """Divides arguments element-wise.

    The storage type of ``elemwise_div`` output is always dense

    Parameters
    ----------
    lhs : Symbol
        first input
    rhs : Symbol
        second input

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

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


@staticmethod
def __to_list(text):
    """
        Convert string to list by spliting it on new line
        :param text: string with proxies each proxy on new line
        :return: list of strings
        """
    return text.split('\n')


def fieldkey(form, field):
    """ Returns the fieldkey for any given json data field + form. """
    return '%s.%s' % (form['desc'], field['desc'])


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


def repositorios(nome):
    """
    Retornar a lista de repos do usuário
    :param nome: nome do usuário
    :return: list
    """


def woeify(x, y, bins=10, mode='equal'):
    """
    Transforms x into weight of evidence

    Parameters
    ----------
    x
    y
    bins
    mode

    Returns
    -------

    """
    pass


def check_bool(input_param):
    """Bool type judgment."""
    if isinstance(input_param, bool):
        return input_param
    raise TypeError('Input type must be bool!')


def remove_empty(entry):
    """
        Filters all empty strings and 'None' entries from a list
    """
    return entry != None and entry != ''


def PreflightRequest(request, allowOrigins='*', allowMethods=
    'POST, GET, DELETE, OPTIONS', allowHeaders='', allowCredentials=True,
    maxAge=3600, response=None):
    """
    Handles Access-Control preflight requests.

    :param request: The current request.
    :param allowOrigins: Either '*' (all allowed) or a list of hosts e.g ('http://mydomain.com')
    :param allowMethods: 'POST, GET, DELETE, OPTIONS'. Allowed http methods as string.
    :param allowHeaders: Custom headers passed in a request as string.
    :param allowCredentials: True/False. Credentials are made accessible in the client application.
    :param response: The response to be returned. if None `request.response` is used.
    :return: response
    """
    response = response or request.response
    origin = request.headers.get('Origin')
    if origin is None:
        return response
    if allowOrigins != '*':
        if not origin in allowOrigins and not '*' in allowOrigins:
            response.status = '405 Not Allowed'
            return response
    headers = [('Access-Control-Allow-Origin', origin), (
        'Access-Control-Allow-Methods', allowMethods), (
        'Access-Control-Allow-Credentials', str(allowCredentials).lower()),
        ('Access-Control-Max-Age', maxAge), ('Access-Control-Allow-Headers',
        allowHeaders), ('Vary', 'Accept-Encoding, Origin')]
    if hasattr(response, 'headerlist'):
        headers += list(response.headerlist)
    response.headerlist = headers
    return response


def user_can_edit_invoice_type(user, content_type):
    """ true if user has any permission related to this content type """
    if user.is_active and user.is_superuser:
        return True
    permission_codenames = content_type.permission_set.values_list('codename',
        flat=True)
    for codename in permission_codenames:
        permission_name = '%s.%s' % (content_type.app_label, codename)
        if user.has_perm(permission_name):
            return True
    return False


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


@staticmethod
def _get_frame_params(frame):
    """
            Retrieves some params from the frame
            :param frame - the OBD frame
            :return tuple of ecu_number, response_mode
        """
    return frame[4:6], int(frame[6:8])


def read_ignore_patterns(f):
    """Read a git ignore file.

    :param f: File-like object to read from
    :return: List of patterns
    """
    for line in f:
        line = line.rstrip(b'\r\n')
        if not line:
            continue
        if line.startswith(b'#'):
            continue
        while line.endswith(b' ') and not line.endswith(b'\\ '):
            line = line[:-1]
        line = line.replace(b'\\ ', b' ')
        yield line


@classmethod
def register(cls, algorithm_name: str, mutation_class):
    """Register a class with a string key."""
    cls.REGISTRY[algorithm_name] = mutation_class
    return mutation_class


def p_expression_neg(p):
    """expression : NEG expression """
    p[0] = ~p[1]


def build(hub, bname):
    """
    Given the build arguments, Make a package!
    """
    pkg_builder = hub.OPT['pop_build']['pkg_builder']
    getattr(hub, f'pop_build.pkg.{pkg_builder}.build')(bname)


def ABS(n):
    """Returns absolute value of a number."""
    return n if n >= 0 else n * -1


def SUM(*expression):
    """
    Calculates and returns the sum of numeric values.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/sum/
    for more details
    :param expression: expression or variables
    :return: Aggregation operator
    """
    return {'$sum': list(expression)} if len(expression) > 1 else {'$sum':
        expression[0]} if expression else {}


def safe_docstring(input):
    """Takes a docstring input, and returns a version with all ':' characters
    replaced with ' '.

    ':' characters will confuse the method we use to scan for the beginning of a
    class or function body (basically, looking backwards from the first element
    until we find the ':' from the signature), which is why we do this.

    It's safe to sub in safe_docstring for docstring in a copy of the source,
    because even if the docstring text appears elsewhere in the file, the
    scanner won't hit it, and it will take up the same number of characters.

    We could fool this by have a docstring whose text appears at the end of the
    signature as well. Hopefully, that's a rare case, but: TODO: fix that."""
    return input.replace(':', ' ')


def byte_to_str(text, do_convert=True):
    """
    make sure `text` is string if `do_convert`

    :raise AttributeError: Text is not processable
    """
    if not do_convert:
        return text
    elif isinstance(text, str):
        return text
    elif isinstance(text, bytes):
        return text.decode()
    else:
        raise AttributeError(
            'Unable to convert {} to string.Text should be string or bytes'
            .format(type(text)))


def calculate_alternator_current(alternator_status, on_engine,
    gear_box_power_in, max_alternator_current, alternator_current_model,
    engine_start_current, prev_battery_state_of_charge, acceleration, time):
    """
    Calculates the alternator current [A].

    :param alternator_status:
        When the alternator is on due to 1:state of charge or 2:BERS [-].
    :type alternator_status: int

    :param on_engine:
        If the engine is on [-].
    :type on_engine: bool

    :param gear_box_power_in:
        Gear box power [kW].
    :type gear_box_power_in: float

    :param max_alternator_current:
        Max feasible alternator current [A].
    :type max_alternator_current: float

    :param alternator_current_model:
        Alternator current model.
    :type alternator_current_model: callable

    :param engine_start_current:
        Current demand to start the engine [A].
    :type engine_start_current: float

    :param prev_battery_state_of_charge:
        Previous state of charge of the battery [%].

        .. note::

            `prev_battery_state_of_charge` = 99 is equivalent to 99%.
    :type prev_battery_state_of_charge: float

    :param acceleration:
        Acceleration [m/s2].
    :type acceleration: float

    :param time:
        Time [s].
    :type time: float

    :return:
        Alternator current [A].
    :rtype: float
    """
    if alternator_status and on_engine and engine_start_current == 0:
        a_c = alternator_current_model(time, prev_battery_state_of_charge,
            alternator_status, gear_box_power_in, acceleration)
        a_c = max(a_c, -max_alternator_current)
    else:
        a_c = 0.0
    return a_c - engine_start_current


def to_int_or_NA(value):
    """Convert to float unless the value is 'N/A', which is left unchanged."""
    if value == 'N/A':
        return 'N/A'
    else:
        return int(value)


@staticmethod
def p_ref_group_optional_list(p):
    """ref_group_optional_list : ref_group_optional
                                   | ref_group_optional ref_group_optional_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


@classmethod
def default_layout(cls, bottleneck, **kwargs):
    """ Define conv block layout """
    _ = kwargs
    reps = 3 if bottleneck else 2
    return 'cna' * reps


def to_meetup_geo(geo):
    """ from geo location to Meetup data geo """
    return geo


def get_obj_spec(client_factory, obj, select_set=None):
    """Builds the Object Spec object."""
    obj_spec = client_factory.create('ns0:ObjectSpec')
    obj_spec.obj = obj
    obj_spec.skip = False
    if select_set is not None:
        obj_spec.selectSet = select_set
    return obj_spec


def uniq(l):
    """Return list with consecutive duplicates removed."""
    result = l[:1]
    for item in l[1:]:
        if item != result[-1]:
            result.append(item)
    return result


def write(output_fn, table):
    """Write OTU/Taxa tables.
    """
    table.to_csv(output_fn, sep='\t')


@staticmethod
def add_context(widget, setting):
    """Add the context to the top of the list."""
    s = widget.context_settings
    s.insert(0, setting)
    del s[len(s):]


def delete():
    """Delete active screen

    """
    pass


def sim_lorentz_gamma(x, x0, gamma):
    """
    Simulate a Lorentzian lineshape with unit height at the center.

    Simulates discrete points of the continuous Cauchy-Lorentz (Breit-Wigner)
    distribution with unit height at the center.  Gamma (the half-width at
    half-maximum, HWHM) is used as the scale parameter.

    Functional form:

        f(x; x0, gamma) = g ^ 2 / ((x-x0) ^ 2 + g ^ 2)

    Parameters
    ----------
    x : ndarray
        Array of values at which to evaluate distribution.
    x0 : float
        Center of the distribution.
    gamma : float
        Scale parameter, half-width at half-maximum, of distribution.

    Returns
    -------
    f : ndarray
        Distribution evaluated at points in x.

    """
    return gamma ** 2 / (gamma ** 2 + (x - x0) ** 2)


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


def dict_property(store, index):
    """ Helper to create class properties from a dictionary.
    Basically this allows you to remove a lot of possible
    boilerplate code.

    :param store: The store store to pull from
    :param index: The index into the store to close over
    :returns: An initialized property set
    """
    if hasattr(store, '__call__'):
        getter = lambda self: store(self)[index]
        setter = lambda self, value: store(self).__setitem__(index, value)
    elif isinstance(store, str):
        getter = lambda self: self.__getattribute__(store)[index]
        setter = lambda self, value: self.__getattribute__(store).__setitem__(
            index, value)
    else:
        getter = lambda self: store[index]
        setter = lambda self, value: store.__setitem__(index, value)
    return property(getter, setter)


def _get_func_start_line_index(line_splitted_list, func_name):
    """
    Get the start line index of the target function.

    Parameters
    ----------
    line_splitted_list : list of str
        A list of strings separated by line.
    func_name : str
        Target function name.

    Returns
    -------
    func_start_line_index : int
        The start line index of the target function. If target
        function name not found, -1 will be set.
    """
    search_str = 'def %s' % func_name
    for i, line_str in enumerate(line_splitted_list):
        is_in = search_str in line_str
        if not is_in:
            continue
        if i + 1 >= len(line_splitted_list):
            continue
        next_line_str = line_splitted_list[i + 1]
        concatenated_str = line_str + next_line_str
        concatenated_str = concatenated_str.replace('\n', '')
        concatenated_str = concatenated_str.strip()
        is_in = 'def %s(' % func_name in concatenated_str
        if not is_in:
            continue
        return i
    return -1


def _go_to_line(editor, line):
    """
    Move cursor to this line in the current buffer.
    """
    b = editor.application.current_buffer
    b.cursor_position = b.document.translate_row_col_to_index(max(0, int(
        line) - 1), 0)


def always_reversible(iterable):
    """An extension of :func:`reversed` that supports all iterables, not
    just those which implement the ``Reversible`` or ``Sequence`` protocols.

        >>> print(*always_reversible(x for x in range(3)))
        2 1 0

    If the iterable is already reversible, this function returns the
    result of :func:`reversed()`. If the iterable is not reversible,
    this function will cache the remaining items in the iterable and
    yield them in reverse order, which may require significant storage.
    """
    try:
        return reversed(iterable)
    except TypeError:
        return reversed(list(iterable))


def insert_tool(tools, tool, allowed_instances):
    """ Add tool to list if tool is sub class
    of one item in allowed_instances
    """
    allowed_instances = allowed_instances or [object]
    for check_instance in allowed_instances:
        if isinstance(tool, type) and issubclass(tool, check_instance):
            tools.append(tool)
            break


def djb_hash(s):
    """Return the value of DJB's hash function for byte string *s*"""
    h = 5381
    for c in s:
        h = ((h << 5) + h ^ c) & 4294967295
    return h


def ensure_ascii_string(value):
    """
    Convert the provided value to an ASCII string (no Unicode characters).
    """
    if isinstance(value, bytes):
        value = value.decode('ascii', 'backslashreplace')
    else:
        value = bytes(str(value), encoding='utf-8').decode(encoding='ascii',
            errors='backslashreplace')
    return value


@staticmethod
def splitpath(path):
    """
        Splits the path using either slashes
        """
    split1 = path.rpartition(b'/')
    split2 = path.rpartition(b'\\')
    if len(split1[0]) > len(split2[0]):
        return split1
    else:
        return split2


def extract_cells(raw_txt):
    """Manually extract cells in potential broken json `raw_txt`"""
    lines = raw_txt.split('\n')
    cells = []
    i = 0
    while not lines[i].startswith(' "cells"'):
        i += 1
    i += 1
    start = '\n'.join(lines[:i])
    while lines[i] != ' ],':
        while lines[i] != '  {':
            i += 1
        j = i
        while not lines[j].startswith('  }'):
            j += 1
        c = '\n'.join(lines[i:j + 1])
        if not c.endswith(','):
            c = c + ','
        cells.append(c)
        i = j + 1
    end = '\n'.join(lines[i:])
    return start, cells, end


@staticmethod
def get_prereq_pip_packages():
    """Should return either a string path to a requirements file, or a list
        of pip packages to be installed before creating the project.
        Each package should either be:

            * A string representing the package (with optional version).
            * A os_api.PipPackage object.
        """
    return []


def can_search(key):
    """Returns if the user has permission to search the given feature"""


def parseHttpHeader(data):
    """
    Parses the beginning of a HTTP request header (the data up to the

 line) into a pair
    of status line and HTTP headers dictionary.
    Header keys are normalized to all-lower-case.

    FOR INTERNAL USE ONLY!

    :param data: The HTTP header data up to the

 line.
    :type data: bytes

    :returns: tuple -- Tuple of HTTP status line, headers and headers count.
    """
    raw = data.decode('iso-8859-1').splitlines()
    http_status_line = raw[0].strip()
    http_headers = {}
    http_headers_cnt = {}
    for h in raw[1:]:
        i = h.find(':')
        if i > 0:
            key = h[:i].strip().lower()
            value = h[i + 1:].strip()
            if key in http_headers:
                http_headers[key] += ', %s' % value
                http_headers_cnt[key] += 1
            else:
                http_headers[key] = value
                http_headers_cnt[key] = 1
        else:
            pass
    return http_status_line, http_headers, http_headers_cnt


def attr_from_obj(obj, name):
    """Return the value of the attribute name.

    Parameters
    ----------
    obj: object
        Object with attribute name
    name: str
        Attribute name to return
    """
    return getattr(obj, name)


def unique_list(a_list):
    """ Creates an ordered list from a list of tuples or other hashable items.
    From https://code.activestate.com/recipes/576694/#c6
    """
    m_map = {}
    o_set = []
    for item in a_list:
        if item not in m_map:
            m_map[item] = 1
            o_set.append(item)
    return o_set


def is_bookmark(fArg):
    """
    This is a weird hack - I couldn't get isinstance to work on NameBookmark for some
    odd reason.
    """
    return 'NameBookmark' in str(fArg.__class__)


def document_model_driven_signature(section, name, operation_model, include
    =None, exclude=None):
    """Documents the signature of a model-driven method

    :param section: The section to write the documentation to.

    :param name: The name of the method

    :param operation_model: The operation model for the method

    :type include: Dictionary where keys are parameter names and
        values are the shapes of the parameter names.
    :param include: The parameter shapes to include in the documentation.

    :type exclude: List of the names of the parameters to exclude.
    :param exclude: The names of the parameters to exclude from
        documentation.
    """
    params = {}
    if operation_model.input_shape:
        params = operation_model.input_shape.members
    parameter_names = list(params.keys())
    if include is not None:
        for member in include:
            parameter_names.append(member.name)
    if exclude is not None:
        for member in exclude:
            if member in parameter_names:
                parameter_names.remove(member)
    signature_params = ''
    if parameter_names:
        signature_params = '**kwargs'
    section.style.start_sphinx_py_method(name, signature_params)


def provider_parser(subparser):
    """Module provider for Aliyun"""
    subparser.description = """
        Aliyun Provider requires an access key id and access secret with full rights on dns.
        Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
        The referrence for Aliyun DNS production:
        https://help.aliyun.com/product/29697.html"""
    subparser.add_argument('--auth-key-id', help=
        'specify access key id for authentication')
    subparser.add_argument('--auth-secret', help=
        'specify access secret for authentication')


def get_line_number_from_function(fn):
    """Get the line number for the end of the function signature.

    The function signature can be farther down when the parameter
    list is split across multiple lines.

    Args:
        fn: The function from which we are getting the line number.

    Returns:
        The line number for the start of the docstring for this
        function.

    """
    line_number = fn.lineno
    if hasattr(fn, 'args') and fn.args.args:
        last_arg = fn.args.args[-1]
        line_number = last_arg.lineno
    return line_number


def _mean_in_rect(img_array, rect=None):
    """Get mean and standard deviation of pixels within rectangle.

    :param ndarray imgarray: the image data
    :param rect: rectanglular area ``[x0, y0, x1, y1]` where x0 < x1, y0 < y1
    """
    if rect is None:
        sub = img_array
    else:
        sub = img_array[rect[1]:rect[3], rect[0]:rect[2]]
    return sub.mean(), sub.std()


def explain_ag(fsm, state, phi):
    """
    Explain why state of fsm satisfies AG phi.

    fsm -- the fsm;
    state -- a state of fsm satisfying AG phi;
    phi -- the set of states of fsm satifying phi.
    """
    pass


def _single_clustering(Nu, Nc):
    """Compute clustering index

    Parameters
    ----------
    Nu: int
        Number of units
    Nc: int
        Number of clusters

    Returns
    -------
    clust: float
        0 if units are not clustered (checkerboard)
        1 if units form a single cluster
    """
    clust = 1 - (Nc / Nu - 1 / Nu) / (1 - 1 / Nu)
    return clust


def freeze(model):
    """ Set all layers in a model to non-trainable.

    The weights for these layers will not be updated during training.

    This function modifies the given model in-place,
    but it also returns the modified model to allow easy chaining with other functions.
    """
    for layer in model.layers:
        layer.trainable = False
    return model


def merge_location_dict(location_dict_list):
    """
    Takes a list of location_dicts and returns a single location_dict with all the
    users and locations. Automatically merges duplicates. Requires unique user ids/names.
    """
    assert type(location_dict_list) is list, 'Must be passed a list of dicts'
    merged_loc_dict = {}
    for loc_dict in location_dict_list:
        for user, loc in loc_dict.items():
            merged_loc_dict[user] = loc
    return merged_loc_dict


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 _calc_eclipse_time(params):
    """Calculates mid-eclipse time -
    I've included this function here in anticipation of using eccentric orbits
    in the near future.
    """
    T0 = params.T0
    per = params.per
    return T0 + 0.5 * per


def subscribe(observer):
    """Register a callable that will be invoked (with a single
        IBuildControl object) for each Build that is created to satisfy this
        request. There may be multiple Builds created in an attempt to handle
        the request: they may be interrupted by the user or abandoned due to
        a lost worker. The last Build (the one which actually gets to run to
        completion) is said to 'satisfy' the BuildRequest. The observer will
        be called once for each of these Builds, both old and new."""


@classmethod
def _strip_commas(cls, kw):
    """Strip out any leading/training commas from the token"""
    kw = kw[:-1] if kw[-1] == ',' else kw
    return kw[1:] if kw[0] == ',' else kw


@staticmethod
def on_init(comparison):
    """
        Callback function called on initialization
        :return:
        """
    pass


@staticmethod
def queue_compare(node1, node2):
    """
        Compares two nodes for sorting queued nodes.

        :param enarksh.controller.node.Node node1:
        :param enarksh.controller.node.Node node2:

        :rtype: int
        """
    cmp = node2.scheduling_weight - node1.scheduling_weight
    if cmp == 0:
        if node1.name.lower() < node2.name.lower():
            cmp = -1
        elif node1.name.lower() > node2.name.lower():
            cmp = 1
        else:
            cmp = 0
    return cmp


def reversesort(items, formatter, start, stop, sorters):
    """Return a list of items in reverse sorted order.

        Formatter is passed to aid calculation of sort parameters.  Start and
        stop are passed in order to provide a hint as to the range needed, if
        the algorithm can optimize.  Sorters are a list of zero or more
        sub-sort callables with the same signature as this method, which may
        be used if desired to sub-sort values with equivalent sort values
        according to this column.

        The original items sequence should not be mutated."""


@classmethod
def register_conf_options(cls, conf, group):
    """Register the oslo_config options that are needed for a plugin.

        :param conf: A config object.
        :type conf: oslo_config.cfg.ConfigOpts
        :param string group: The group name that options should be read from.
        """
    plugin_opts = cls.get_options()
    conf.register_opts(plugin_opts, group=group)


def getHomeFolder(id=None, verifyPermission=False):
    """ Return a member's home folder object or None.

        o 'id', if passed, is the ID of the member whose folder should be
          returned;  if not passed, use the currently-authenticated member.

        o If 'verifyPermission' is True, return None when the user
          doesn't have the View permission on the folder.

        o Permission:  Public
        """


def interactive(state):
    """Toggle interactive mode"""
    global _interactive
    _interactive = state


def arg_auto_int(value):
    """parsing function for integer arguments"""
    return int(value, 0)


@staticmethod
def percentage(current, total, time_remaining):
    """Returns the progress percentage."""
    return '{}% completed'.format(int(current / total * 100))


@classmethod
def help(cls, nipype_interface, returnhelp=False):
    """ Method to print the full wraped nipype interface help.

        Parameters
        ----------
        cls: process class (mandatory)
            a nipype process class
        nipype_instance: nipype interface (mandatory)
            a nipype interface object that will be documented.
        returnhelp: bool (optional, default False)
            if True return the help string message,
            otherwise display it on the console.
        """
    from .nipype_process import nipype_factory
    cls_instance = nipype_factory(nipype_interface)
    return cls_instance.get_help(returnhelp)


def is_tensor(obj):
    """Returns true if the given object is a framework-specific tensor."""
    pass


@classmethod
def list(cls, context):
    """Return a list of ExtARQ objects."""
    db_extarqs = cls.dbapi.extarq_list(context)
    obj_extarq_list = cls._from_db_object_list(db_extarqs, context)
    return obj_extarq_list


@classmethod
def _get_tests(cls):
    """Yield an extractor's test cases as (URL, RESULTS) tuples"""
    tests = cls.test
    if not tests:
        return
    if len(tests) == 2 and (not tests[1] or isinstance(tests[1], dict)):
        tests = tests,
    for test in tests:
        if isinstance(test, str):
            test = test, None
        yield test


def _string_vals_to_list(dictionary):
    """Convert string values to lists."""
    list_keys = ['conda_install', 'pip_install']
    for kk in list_keys:
        if kk in dictionary.keys():
            dictionary[kk] = dictionary[kk].split()


@classmethod
def filter(cls, o):
    """
            Filter object with this class in data
            return
            True when object contains this datablock
            False otherwhise
            usage:
            class_name.filter(object) from outside world
            self.__class__.filter(object) from instance
        """
    try:
        return cls.__name__ in o
    except:
        pass
    return False


def load_data_file(path):
    """Load a file either from __loader__ or the filesystem."""
    loader = globals().get('__loader__', None)
    if loader:
        return loader.get_data(path)
    with open(path, 'rb') as fi:
        return fi.read()


def censorrevision(tr, node, tombstone=b''):
    """Remove the content of a single revision.

        The specified ``node`` will have its content purged from storage.
        Future attempts to access the revision data for this node will
        result in failure.

        A ``tombstone`` message can optionally be stored. This message may be
        displayed to users when they attempt to access the missing revision
        data.

        Storage backends may have stored deltas against the previous content
        in this revision. As part of censoring a revision, these storage
        backends are expected to rewrite any internally stored deltas such
        that they no longer reference the deleted content.
        """


def msg_delayed_filter(message, now):
    """Return True IFF the message is currently delayed."""
    return now < message.delay_expires


def parse_string(value):
    """
    parses string for python keywords or numeric value

    Parameters
    ----------
    value : str or float
        the value to be parsed (true, false, none, null, na, or float)

    Returns
    -------
    boolean, None, float, original value
    """
    if value is None:
        return None
    value = value.strip()
    if value.lower() == 'true':
        return True
    if value.lower() == 'false':
        return False
    if value.lower() in ['none', 'null', 'na']:
        return None
    try:
        if '.' in value:
            v = float(value)
        else:
            v = int(value)
        return v
    except ValueError:
        return value


def rectangle_props(event):
    """
    Returns the width, height, left, and bottom of a rectangle artist.

    Parameters
    -----------
    event : PickEvent
        The pick event to process

    Returns
    --------
    A dict with keys:
        `width` : The width of the rectangle
        `height` : The height of the rectangle
        `left` : The minimum x-coordinate of the rectangle
        `right` : The maximum x-coordinate of the rectangle
        `bottom` : The minimum y-coordinate of the rectangle
        `top` : The maximum y-coordinate of the rectangle
        `xcenter` : The mean x-coordinate of the rectangle
        `ycenter` : The mean y-coordinate of the rectangle
        `label` : The label for the rectangle or None
    """
    artist = event.artist
    width, height = artist.get_width(), artist.get_height()
    left, bottom = artist.xy
    right, top = left + width, bottom + height
    xcenter = left + 0.5 * width
    ycenter = bottom + 0.5 * height
    label = artist.get_label()
    if label is None or label.startswith('_nolegend'):
        try:
            label = artist._mpldatacursor_label
        except AttributeError:
            label = None
    return dict(width=width, height=height, left=left, bottom=bottom, label
        =label, right=right, top=top, xcenter=xcenter, ycenter=ycenter)


@classmethod
def _get_schema(cls, translator, schema, parent_key_type=None):
    """Returns named tuple with values:

        schema: the schema of a translator,
        id_type: the data type of the id-col, or None of absent

        Note: this method uses the argument schema to store
        data in since this method words recursively. It might
        be worthwhile in the future to refactor this code so this
        is not required.

        :param parent_key_type: passes down the column data type which the
                translator refers to as parent-key
        """
    cls.check_translation_type(translator.keys())
    translation_type = translator[cls.TRANSLATION_TYPE]
    if translation_type == cls.HDICT:
        return cls._get_schema_hdict(translator, schema, parent_key_type)
    elif translation_type == cls.VDICT:
        return cls._get_schema_vdict(translator, schema, parent_key_type)
    elif translation_type == cls.LIST:
        return cls._get_schema_list(translator, schema, parent_key_type)
    elif translation_type == cls.VALUE:
        return cls.SCHEMA_RETURN_TUPLE(schema, None)
    else:
        raise AssertionError('Unexpected translator type %s' % translation_type
            )


def on_segment(p, q, r):
    """Given three colinear points p, q, r, the function checks if point q
    lies on line segment 'pr'."""
    if q.x <= max(p.x, r.x) and q.x >= min(p.x, r.x):
        if q.y <= max(p.y, r.y) and q.y >= min(p.y, r.y):
            return True
    return False


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 set_rule_priorities(RulePriorities=None):
    """
    Sets the priorities of the specified rules.
    You can reorder the rules as long as there are no priority conflicts in the new order. Any existing rules that you do not specify retain their current priority.
    See also: AWS API Documentation

    Examples
    This example sets the priority of the specified rule.
    Expected Output:

    :example: response = client.set_rule_priorities(
        RulePriorities=[
            {
                'RuleArn': 'string',
                'Priority': 123
            },
        ]
    )

    :type RulePriorities: list
    :param RulePriorities: [REQUIRED]
            The rule priorities.
            (dict) --Information about the priorities for the rules for a listener.
            RuleArn (string) --The Amazon Resource Name (ARN) of the rule.
            Priority (integer) --The rule priority.

    :rtype: dict
    :return: {
        'Rules': [
            {
                'RuleArn': 'string',
                'Priority': 'string',
                'Conditions': [
                    {
                        'Field': 'string',
                        'Values': [
                            'string',
                        ]
                    },
                ],
                'Actions': [
                    {
                        'Type': 'forward',
                        'TargetGroupArn': 'string'
                    },
                ],
                'IsDefault': True|False
            },
        ]
    }

    :returns:
    A-Z, a-z, 0-9
    _ - . $ / ~ " ' @ : +
    (using amp;)

    (matches 0 or more characters)

    ? (matches exactly 1 character)

    """
    pass


def inverse_pose(pose):
    """
    Same as pose.inverse()
    :param pose: instance of ``util.Pose``
    """
    return pose.transform().inverse().pose()


def zero_insert(input_string):
    """
    This function get a string as input if input is one digit add a zero
    :param input_string: input digit az string
    :type input_string:str
    :return: modified output as str
    """
    if len(input_string) == 1:
        return '0' + input_string
    return input_string


@staticmethod
def _set_constraints(kerns, STS):
    """
        Sets hyperparameter constraints on kernels.
        """
    if STS.thetabounds is not None:
        kerns[0].variance.constrain_bounded(STS.thetabounds[0][0], STS.
            thetabounds[0][1], warning=False)
        for i in range(STS.dim):
            kerns[i].lengthscale.constrain_bounded(STS.thetabounds[i + 1][0
                ], STS.thetabounds[i + 1][1], warning=False)
    for i in range(STS.dim):
        if STS.kerntype[i] == 'stdp':
            kerns[i].period.constrain_fixed(STS.periods[i], warning=False)
    if STS.dim > 1:
        for i in range(1, STS.dim):
            kerns[i].variance.constrain_fixed(1.0, warning=False)


def is_valid_xml_char_ordinal(i):
    """
    Defines whether char is valid to use in xml document

    XML standard defines a valid char as::

    Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
    """
    return 32 <= i <= 55295 or i in (9, 10, 13
        ) or 57344 <= i <= 65533 or 65536 <= i <= 1114111


def write(sid0_list, sid1_list, pvalue_list, output_file):
    """
    Given three arrays of the same length [as per the output of epistasis(...)], writes a header and the values to the given output file.
    """
    with open(output_file, 'w') as out_fp:
        out_fp.write('{0}\t{1}\t{2}\n'.format('sid0', 'sid1', 'pvalue'))
        for i in range(len(pvalue_list)):
            out_fp.write('{0}\t{1}\t{2}\n'.format(sid0_list[i], sid1_list[i
                ], pvalue_list[i]))


def match_keyword(token, keywords):
    """
    Checks if the given token represents one of the given keywords
    """
    if not token:
        return False
    if not token.is_keyword:
        return False
    return token.value.upper() in keywords


@staticmethod
def list(value):
    """Support comma-separated lists.
        """
    if not value:
        return []
    return value.split(',')


def isSame(a, b):
    """Type (b) is the same as (a) if (a) and (b) are identicial, that means
	that you can use b where you use a, and this also means that isSame(a,b) ==
	isSame(b,a). Basically, when (b) is same as (a), (b) can be considered as an
	alias for (a)."""
    a.isSame(b)


def to_string(value):
    """Returns a string for the value that can be handled by the
    balancer manager.

    :param value: Any value.
    """
    if isinstance(value, bool):
        return '1' if value else '0'
    elif value:
        return str(value)
    else:
        return ''


def dissolve_verts():
    """Delete selected control points, correcting surrounding handles

    """
    pass


@classmethod
def save(cls, info, instance, cleaned_input=None):
    """Save the instance to the database.

        To do something with the instance "before" or "after" saving it,
        override either :meth:`.before_save` and/or :meth:`.after_save`.
        """
    cls.before_save(info, instance, cleaned_input=cleaned_input)
    instance.save()
    cls.after_save(info, instance, cleaned_input=cleaned_input)


def _set_preferred_array(module, array):
    """Set preferred array list. Only called when supported"""
    if module.params['preferred_array'] != ['delete']:
        array.set_host(module.params['host'], preferred_array=module.params
            ['preferred_array'])
    else:
        array.set_host(module.params['host'], personality='')


def _venue(entry):
    """Format an entry's venue data."""
    f = entry.fields
    venue = ''
    if entry.type == 'article':
        venue = f['journal']
        try:
            if f['volume'] and f['number']:
                venue += ' {0}({1})'.format(f['volume'], f['number'])
        except KeyError:
            pass
    elif entry.type == 'inproceedings':
        venue = f['booktitle']
        try:
            if f['series']:
                venue += ' ({})'.format(f['series'])
        except KeyError:
            pass
    elif entry.type == 'inbook':
        venue = f['title']
    elif entry.type == 'techreport':
        venue = '{0}, {1}'.format(f['number'], f['institution'])
    elif entry.type == 'phdthesis' or entry.type == 'mastersthesis':
        venue = ''
    else:
        venue = 'Unknown venue (type={})'.format(entry.type)
    venue = venue.replace('{', '').replace('}', '')
    return venue


@staticmethod
def _aggr_iplist(ranges, rngcls):
    """
        Helper method for creating aggregated IP range from given list of IP ranges.
        """
    if not ranges:
        return None
    ipmin = None
    ipmax = None
    for rng in ranges:
        if ipmin is None or rng.low() < ipmin:
            ipmin = rng.low()
        if ipmax is None or rng.high() > ipmax:
            ipmax = rng.high()
    return rngcls((ipmin, ipmax))


@classmethod
def get_member_group(cls):
    """Returns the first member group."""
    return cls.query.filter(cls.admin == False, cls.super_mod == False, cls
        .mod == False, cls.guest == False, cls.banned == False).first()


@classmethod
def _add_enum_members(meta, clsdict):
    """
        Dispatch ``.add_to_enum()`` call to each member so it can do its
        thing to properly add itself to the enumeration class. This
        delegation allows member sub-classes to add specialized behaviors.
        """
    enum_members = clsdict['__members__']
    for member in enum_members:
        member.add_to_enum(clsdict)


def describe_operation(specification, operation):
    """
    Get a human readable string which describes an operation.

    :param specification: openapi_core Specification
    :param operation: openapi_core Operation

    :return: str representation of the operation.
    """
    return ' '.join((operation.http_method.upper(), specification.
        default_url + operation.path_name))


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

        :param TeamFolderTeamSharedDropboxError val:
        :rtype: BaseTeamFolderError
        """
    return cls('team_shared_dropbox_error', val)


def uid2str(uid):
    """ Convert PyDicom uid to a string """
    return repr(uid).strip("'")


def winsorized_rank_correlation(X, rowvar=False, weighted=False):
    """
    Computes rank correlations using a winsorized ranks.
    Relevant to high dimensional settings where the n_samples < n_features
    resulting too large variance in the ranks.

    Parameters
    ----------
    X: array-like, shape = [n_samples, n_features]
        Data matrix using which we compute the empirical
        correlation

    Returns
    -------
    rank_correlation

    References
    ----------

    Liu, Han, John Lafferty, and Larry Wasserman.
    "The nonparanormal: Semiparametric estimation of high dimensional
    undirected graphs."
    Journal of Machine Learning Research 10.Oct (2009): 2295-2328.
    """
    pass


def content():
    """Give you back the result of your Page to be included inside
        the layout.
        """


def set_working_directory(working_directory: str):
    """
    Sets working directory of python application
    :param working_directory: full name of working directory
    """
    global _working_directory
    _working_directory = working_directory


def edge_subgraph(G, ebunch):
    """Return the subgraph induced on edges in `ebunch`.

    The induced subgraph of the graph contains the edges appearing in `ebunch`
    and only the nodes that appear in some edge in `ebunch`.

    Parameters
    ----------
    ebunch : list, iterable
        A container of edges as 3-tuples (u, v, key), which will be iterated
        through exactly once.

    Returns
    -------
    H : MultiDiGraph
        A subgraph of the graph with the same graph, node, and edge attributes.

    Notes
    -----
    The graph, edge or node attributes just point to the original graph.
    So changes to the node or edge structure will not be reflected in
    the original graph while changes to the attributes will.

    To create a subgraph with its own copy of the edge/node attributes use:
    nx.Graph(G.subgraph(nbunch))

    If edge attributes are containers, a deep copy can be obtained using:
    G.subgraph(nbunch).copy()

    For an inplace reduction of a graph to a subgraph you can remove nodes:
    G.remove_nodes_from([ n in G if n not in set(nbunch)])

    Examples
    --------
    >>> G = nx.Graph()   # or DiGraph, MultiGraph, MultiDiGraph, etc
    >>> G.add_path([0,1,2,3])
    >>> H = G.subgraph([0,1,2])
    >>> H.edges()
    [(0, 1), (1, 2)]

    """
    H = G.__class__()
    G_succ = G.succ
    for u, v, key in ebunch:
        try:
            attrs = G_succ[u][v][key]
        except KeyError:
            raise KeyError('Invalid edge: ({0}, {1}, {2})'.format(u, v, key))
        H.add_edge(u, v, key=key, **attrs)
    for u in H:
        H.node[u] = G.node[u].copy()
    H.graph = G.graph.copy()
    return H


def _formatparamchildren(parameter) ->str:
    """
    Get parameter name and value from Jedi Private API

    Jedi does not expose a simple way to get `param=value` from its API.

    Parameter
    =========

    parameter:
        Jedi's function `Param`

    Returns
    =======

    A string like 'a', 'b=1', '*args', '**kwargs'

    """
    description = parameter.description
    if not description.startswith('param '):
        raise ValueError(
            'Jedi function parameter description have change format.Expected "param ...", found %r".'
             % description)
    return description[6:]


@classmethod
def from_file(cls, f, parent=None):
    """Construct an HFSSNode from an hfss file."""
    return cls._from_file(next(f).strip(), f, parent)


@classmethod
def format_pair(cls, pair):
    """format the pair argument to format understood by remote API."""
    pair = pair.replace('-', cls.delimiter).upper()
    return pair


def get_dotnotation(original: dict, dotnotation: str) ->dict:
    """Use dotted notation to create set values in a dict,
    e.g:
    >>> dotattr({}, 'some.path.in.dict', 'value')
    { "some": { "path": { "in": {"dict": "value" }}}}

    >>> dotattr({'credentials': {'username': 'test'}}, 'credentials.username')
    'test'
    """
    original = original or {}
    parts = dotnotation.split('.')
    current = original
    for part in parts:
        if part is parts[-1]:
            return current[part]
        elif part not in current:
            current[part] = {}
        current = current[part]
    return original


def hashable(data, v):
    """Determine whether `v` can be hashed."""
    try:
        data[v]
    except (TypeError, KeyError, IndexError):
        return False
    return True


def load_numpy_distutils_command_scons(finder, module):
    """the numpy.distutils.command.scons module optionally imports the numscons
       module; ignore the error if the module cannot be found."""
    module.IgnoreName('numscons')


def get_p2p_ssqr_diff_over_var(model):
    """
    Get sum of squared differences of consecutive values as a fraction of the
    variance of the data.
    """
    return model['ssqr_diff_over_var']


def compute_all_shapes(v):
    """Compute the tensor-, index-, and total shape of an expr.

    Returns (shape, size, index_shape, index_size, total_shape, total_size).
    """
    shape = v.ufl_shape
    index_shape = v.ufl_index_dimensions
    total_shape = shape + index_shape
    return shape, index_shape, total_shape


def almosteq(ctx, s, t, rel_eps=None, abs_eps=None):
    """
        Determine whether the difference between `s` and `t` is smaller
        than a given epsilon, either relatively or absolutely.

        Both a maximum relative difference and a maximum difference
        ('epsilons') may be specified. The absolute difference is
        defined as `|s-t|` and the relative difference is defined
        as `|s-t|/\\max(|s|, |t|)`.

        If only one epsilon is given, both are set to the same value.
        If none is given, both epsilons are set to `2^{-p+m}` where
        `p` is the current working precision and `m` is a small
        integer. The default setting typically allows :func:`~mpmath.almosteq`
        to be used to check for mathematical equality
        in the presence of small rounding errors.

        **Examples**

            >>> from mpmath import *
            >>> mp.dps = 15
            >>> almosteq(3.141592653589793, 3.141592653589790)
            True
            >>> almosteq(3.141592653589793, 3.141592653589700)
            False
            >>> almosteq(3.141592653589793, 3.141592653589700, 1e-10)
            True
            >>> almosteq(1e-20, 2e-20)
            True
            >>> almosteq(1e-20, 2e-20, rel_eps=0, abs_eps=0)
            False

        """
    t = ctx.convert(t)
    if abs_eps is None and rel_eps is None:
        rel_eps = abs_eps = ctx.ldexp(1, -ctx.prec + 4)
    if abs_eps is None:
        abs_eps = rel_eps
    elif rel_eps is None:
        rel_eps = abs_eps
    diff = abs(s - t)
    if diff <= abs_eps:
        return True
    abss = abs(s)
    abst = abs(t)
    if abss < abst:
        err = diff / abst
    else:
        err = diff / abss
    return err <= rel_eps


def matchFamilyIsland(genesO, gene2FamIslandD, searchStr):
    """Return the island number, family number, and gene name(s)
associated with searchStr in genesO.geneInfoD. Searches for a match in all
fields of geneInfoD."""
    geneMatchL = []
    for geneNum in genesO.geneInfoD:
        valueT = genesO.numToGeneInfo(geneNum)
        for value in valueT:
            if type(value) == str:
                if searchStr in value:
                    geneMatchL.append(geneNum)
                    break
    outL = []
    for geneNum in geneMatchL:
        geneName = genesO.numToName(geneNum)
        locusIslandNum, famNum, locusFamNum = gene2FamIslandD[geneNum]
        outL.append((geneName, locusIslandNum, famNum, locusFamNum))
    return outL


def fai_to_chromosome_info(fai_entries):
    """Convert the given fai-entries to dinopy chromosome info format.

    Converts from a list of :code:`[chr_name, chr_len, chr_start, line_length, line_length_bytes]` (file-view)
    to a list of :code:`[chr_name, chr_len, (chr_start, chr_stop)]` entries (genome-array-view i.e. without names, newlines, and '>')

    Arguments:
        fai_entries(Iterable): An iterable of valid fai-entries.

    Returns:
        list: A list containing valid chromosome info entries.
    """
    chr_name, chr_len, chr_start, *_ = fai_entries[0]
    chr_start_index = 0
    chromosome_infos = []
    for chr_name, chr_len, *_ in fai_entries:
        if isinstance(chr_name, str):
            chr_name = chr_name.encode()
        chr_end_index = chr_start_index + chr_len
        chromosome_infos.append([chr_name, chr_len, (chr_start_index,
            chr_end_index)])
        chr_start_index = chr_end_index
    return chromosome_infos


def w2bhp(value):
    """float: power: Watts to Brake Horse Power."""
    return value / 745.699872


def vert_connect():
    """Connect selected vertices of faces, splitting the face

    """
    pass


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'HOME':
        'A string indicating the home directory of the current user.'}


def last_continuous_indexes_slice(ol, value):
    """
        from elist.elist import *
        ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
        last_continuous_indexes_slice(ol,"a")
    """
    length = ol.__len__()
    end = None
    slice = []
    for i in range(length - 1, -1, -1):
        if ol[i] == value:
            end = i
            break
        else:
            pass
    if end == None:
        return None
    else:
        slice.append(end)
        for i in range(end - 1, -1, -1):
            if ol[i] == value:
                slice.append(i)
            else:
                break
    slice.reverse()
    return slice


def has_lookahead(parser):
    """ Return True if the parser has the ability to perform lookahead. """
    return hasattr(parser, 'lookahead')


def breadcrumbs():
    """Returns a tuple like ({'name':name, 'url':url}, ...)

        Name is the name to display for that segment of the breadcrumbs.
        URL is the link for that segment of the breadcrumbs.
        """


def create_embedded():
    """
  Imports the phovea_server and creates an application
  """
    from .server import create_application
    return create_application()


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

        :param ShowcaseRemoveMemberType val:
        :rtype: EventType
        """
    return cls('showcase_remove_member', val)


@classmethod
def from_xml_file(cls, filename):
    """
        Instantiate an AVM object from an xml file.
        """
    return cls.from_xml(open(filename, 'rb').read())


def _store_loads(model, unused_card_type, unused_ids, nids_used, eids_used,
    cids_used):
    """helper for ``remove_unused``"""
    for loads in model.loads.values():
        for load in loads:
            if load.type in ['FORCE', 'MOMENT']:
                nids_used.add(load.node_id)
                cids_used.add(load.Cid())
            elif load.type in ['FORCE1', 'FORCE2', 'MOMENT1', 'MOMENT2']:
                nids_used.update(load.node_ids)
            elif load.type == 'GRAV':
                cids_used.add(load.Cid())
            elif load.type == 'RANDPS':
                pass
            elif load.type == 'PLOAD':
                nids_used.update(load.node_ids)
            elif load.type == 'PLOAD1':
                pass
            elif load.type == 'PLOAD2':
                pass
            elif load.type == 'PLOAD4':
                cids_used.add(load.Cid())
            elif load.type == 'DEFORM':
                eids_used.add(load.Eid())
            elif load.type == 'SPCD':
                nids_used.update(load.node_ids)
            elif load.type == 'GMLOAD':
                cids_used.add(load.Cid())
            elif load.type in ['RFORCE', 'RFORCE1']:
                nids_used.add(load.node_id)
                cids_used.add(load.Cid())
            elif load.type == 'TEMP':
                nids_used.update(list(load.temperatures.keys()))
            elif load.type == 'ACCEL':
                cids_used.add(load.Cid())
            elif load.type == 'ACCEL1':
                cids_used.add(load.Cid())
            elif load.type in ['QBDY1', 'QBDY2', 'QBDY3', 'QHBDY']:
                pass
            elif load.type in ['PLOADX1']:
                nids_used.update(load.node_ids)
            elif load.type in ['SLOAD']:
                nids_used.update(load.node_ids)
            elif load.type in ['LOAD', 'LSEQ', 'LOADCYN']:
                pass
            elif load.type in ['QVOL', 'TEMPRB']:
                pass
            elif load.type in ['TEMPAX']:
                pass
            else:
                raise NotImplementedError(load)


def getClusters(fileLocation):
    """Returns the latlongs of the coordinates stored in the coordinates file.

    Parameters
    ----------
    coordinatesFileI : filepath
        Coordinates file "I" generated by the clusterAndAggregate routine.

    Returns
    -------
    list
        Latlongs of the clusters centroids.

    """
    coordinates = [[], []]
    clusterFile = open(fileLocation, 'r')
    for line in clusterFile:
        tokens = line.split(',')
        coordinates[0].append(float(tokens[0]))
        coordinates[1].append(float(tokens[1]))
    return coordinates


def outshift():
    """shift incoming things to outgoing things"""


@classmethod
def supports_metadata(cls):
    """returns True if this audio type supports MetaData"""
    return True


def same(l):
    """Check if all elements of a sequence are equal."""
    if len(l) == 0:
        return True
    else:
        last = l.pop()
        for x in l:
            if x != last:
                return False
        return True


def __iter__():
    """Iterate over revision numbers for this manifest."""


def check_int(cell):
    """
    Colors the cell red if the integer is invalid

    Parameters
    ----------
    cell : QLineEdit()
        a PyQt/PySide object

    Returns
    -------
    value : int / None
        int : the value as a int
        None : is_passed=False
    is_passed : bool
        is this a valid integer
    """
    text = cell.text()
    try:
        value = int(text)
        cell.setStyleSheet('QLineEdit{background: white;}')
        return value, True
    except ValueError:
        cell.setStyleSheet('QLineEdit{background: red;}')
        return None, False


def array_pack(img):
    """
    img: numpy array. I primarily use this for OpenCV images
    """
    d = img.tobytes()
    s = img.shape
    t = img.dtype
    return s, t, d


def dummy_wrap(f, *args, **kwargs):
    """Do nothing except call the function with the parameters.

    :param f: The function to be called
    """
    f(*args, **kwargs)


def fmodifier_paste(only_active: bool=True, replace: bool=False):
    """Add copied F-Modifiers to the selected F-Curves

    :param only_active: Only Active, Only paste F-Modifiers on active F-Curve
    :type only_active: bool
    :param replace: Replace Existing, Replace existing F-Modifiers, instead of just appending to the end of the existing list
    :type replace: bool
    """
    pass


def prunecomments(blocks):
    """Remove comments."""
    i = 0
    while i < len(blocks):
        b = blocks[i]
        if b[b'type'] == b'paragraph' and (b[b'lines'][0].startswith(b'.. '
            ) or b[b'lines'] == [b'..']):
            del blocks[i]
            if i < len(blocks) and blocks[i][b'type'] == b'margin':
                del blocks[i]
        else:
            i += 1
    return blocks


def autogenReplace(autogenCmd, outputLines, autogenDict, entryDict):
    """
    Handle any pattern replacements requested by the user.
    """
    if not autogenDict.has_key('replace'):
        return
    for pathDict in autogenDict['replace']:
        pattern = pathDict['substitute']['pattern']
        containerDst = pathDict['path']
        roles = pathDict.get('onroles', None)
        macro = pathDict['substitute']['macro']
        with autogenCmd.getRoleIfContext(roles, outputLines) as ric:
            outputLines.append('%sREPLACE_PATTERN %s %s %s\n' % (ric.spaces,
                pattern, containerDst, macro))
        outputLines.append('\n')
    return


def get_selected_streams(catalog):
    """
    Gets selected streams.  Checks schema's 'selected' first (legacy)
    and then checks metadata (current), looking for an empty breadcrumb
    and mdata with a 'selected' entry
    """
    selected_streams = []
    for stream in catalog['streams']:
        stream_metadata = stream['metadata']
        if stream['schema'].get('selected', False):
            selected_streams.append(stream['tap_stream_id'])
        else:
            for entry in stream_metadata:
                if not entry['breadcrumb'] and entry['metadata'].get('selected'
                    , None):
                    selected_streams.append(stream['tap_stream_id'])
    return selected_streams


def is_bool(variable):
    """Tests if provided parameter is bool data type"""
    try:
        if type(variable) is bool:
            return True
    except TypeError:
        return False


def __call__(view, info):
    """
        Derive a new view from the supplied view.

        View options, package information and registry are available on
        ``info``, an instance of :class:`pyramid.interfaces.IViewDeriverInfo`.

        The ``view`` is a callable accepting ``(context, request)``.

        """


def chunks_known_length(iterable, size, length=None):
    """
    Yield successive `size`-sized chunks from `iterable`,
    if the length of `iterable is already known or easy to compute.

    https://stackoverflow.com/a/312464/3423324

    :param iterable: The object you want to split into pieces.

    :param size: The size each of the resulting pieces should have.
    :type  size: int

    :param length: Optional. Length of the `iterable`.
                   If set to `None` (default), the length get calculated automatically.
    :type  length: None | int
    """
    if length is None:
        len(iterable)
    for i in range(0, length, size):
        yield iterable[i:i + size]


def get_scaling_function(y_m, y_M, x_m, x_M):
    """
    Returns a linear function y = k x + b, where y \\in [m, M]
    :param y_m:
    :param y_M:
    :param x_m:
    :param x_M:
    :return:
    """
    if x_M <= x_m:
        return lambda _: y_m
    k = (y_M - y_m) / (x_M - x_m)
    b = y_m - k * x_m
    return lambda _: int(k * _ + b)


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 format_unique_id(app_id: str, location_id: str) ->str:
    """Format the unique id for a config entry."""
    return f'{app_id}_{location_id}'


def get_ip_profile(active_connection):
    """
    Get NMSettingIP4Config from NMActiveConnection.
    For any error, return None.
    """
    remote_conn = active_connection.get_connection()
    if remote_conn:
        return remote_conn.get_setting_ip4_config()
    return None


def glPopClientAttrib():
    """Pop the client attribute stack

    """
    pass


def str_to_int(exp):
    """
    Convert a string to an integer.

    The method is primitive, using a simple hash based on the
    ordinal value of the characters and their position in the string.

    Parameters
    ----------
    exp : str
        The string expression to convert to an int.

    Returns
    -------
    sum : int
        An integer that is likely (though not extremely so) to be unique
        within the scope of the program.
    """
    sum_ = 0
    for i, character in enumerate(exp):
        sum_ += i + ord(character) + i * ord(character)
    return sum_


@classmethod
def create_resource(cls):
    """
        Creates a new ModelResource around a new model_class instance
        """
    return cls(cls.model_class())


def mixture_symmetric_point_pos(params, ns, s1, s2, sel_dist1, sel_dist2,
    theta, pts=None):
    """
    Weighted summation of 1d and 2d distributions with positive selection.
    The 1d distribution is equivalent to assuming selection coefficients are
    perfectly correlated.

    params: Parameters for potential optimization.
            The last parameter is the weight for the 2d dist.
            The second-to-last parameter is positive gammma for the point mass.
            The third-to-last parameter is the proportion of positive selection.
            The fourth-to-last parameter is the correlation coefficient for the
                2d distribution.
            The remaining parameters as must be shared between the 1d and 2d
                distributions.
    ns: Ignored
    s1: Cache1D object for 1d distribution
    s2: Cache2D object for 2d distribution
    sel_dist1: Univariate probability distribution for s1
    sel_dist2: Bivariate probability distribution for s2
    theta: Population-scaled mutation rate
    pts: Ignored
    """
    pdf_params = params[:-4]
    rho, ppos, gamma_pos, p2d = params[-4:]
    params1 = list(pdf_params) + [ppos, gamma_pos]
    fs1 = s1.integrate_point_pos(params1, None, sel_dist1, theta, Npos=1,
        pts=None)
    params2 = list(pdf_params) + [rho, ppos, gamma_pos]
    fs2 = s2.integrate_symmetric_point_pos(params2, None, sel_dist2, theta,
        None)
    return (1 - p2d) * fs1 + p2d * fs2


@classmethod
def disable(cls):
    """Disables events from backend.
        """
    return cls.build_send_payload('disable', {}), None


def _calculateForce(pot, r, h=1e-05):
    """Calls pot.force for separation (r) and returns DL_POLY -r dU/dr values rather than
  the dU/dr value normally returned by potentials.Potential.force() method

  @param pot potential from which force should be calculated
  @param r Separation at which force should be calculated
  @param h Increment used when performing numerical differentiation to obtain force

  @return -r dU/dr"""
    dUdr = pot.force(r, h=h)
    return r * dUdr


def _get_pv(obj):
    """
    returns PV name, prefix of None from ophyd object
    """
    if hasattr(obj, 'pvname'):
        return obj.pvname
    elif hasattr(obj, 'prefix'):
        return obj.prefix


def tesla2Oe(tesla):
    """
    Field (Oe) from induction (T).

    Parameters
    ----------
    tesla : ndarray or scalar
        Induction in Tesla.

    Returns
    -------
    o : ndarray or scalar
        field in Oe.

    """
    o = tesla * 10000
    return o


def zip():
    """
        smash incoming things into one single thing, pairing things by iterable
        position
        """


def _filler(p_str, p_len):
    """
    Returns p_str preceded by additional spaces if p_str is shorter than p_len.
    """
    to_fill = p_len - len(p_str)
    return to_fill * ' ' + p_str


def filterLocalVariables(isGlobal, varName, varType):
    """Filters out the local variables"""
    del varName
    del varType
    return not isGlobal


def provider_parser(subparser):
    """Configure a provider parser for Hetzner"""
    subparser.add_argument('--auth-account', help=
        'specify type of Hetzner account: by default Hetzner Robot (robot) or Hetzner konsoleH (konsoleh)'
        )
    subparser.add_argument('--auth-username', help=
        'specify username of Hetzner account')
    subparser.add_argument('--auth-password', help=
        'specify password of Hetzner account')
    subparser.add_argument('--linked', help=
        "if exists, uses linked CNAME as A|AAAA|TXT record name for edit actions: by default (yes); Further restriction: Only enabled if record name or raw FQDN record identifier 'type/name/content' is specified, and additionally for update actions the record name remains the same"
        , default=str('yes'), choices=['yes', 'no'])
    subparser.add_argument('--propagated', help=
        'waits until record is publicly propagated after succeeded create|update actions: by default (yes)'
        , default=str('yes'), choices=['yes', 'no'])
    subparser.add_argument('--latency', help=
        'specify latency, used during checks for publicly propagation and additionally for Hetzner Robot after record edits: by default 30s (30)'
        , default=int(30), type=int)


def __call__(request, result, encoding):
    """Return a modified result.

        `request` is the Zope request. Response headers may be read or
        modified in `request.response`.

        `result` is an iterable of byte strings that represents the response
        body. When unwound, its contents will match the response content type.

        `encoding` is the default encoding used.

        Return the new result iterable, or a string. If a string is returned,
        the Content-Type header will be updated automatically. If a six.text_type
        string is returned, it will be encoded with the current content
        encoding.

        Do not call `request.response.setBody()`. It will have no effect.
        """


@staticmethod
def on_connect(client, result_code):
    """
        User callback: called when the client is connected

        :param client: The Pelix MQTT client which connected
        :param result_code: The MQTT result code
        """
    pass


@classmethod
def from_monitor_metric_list_obj(cls, monitor_metric_list):
    """Returns a list of MetricPayload objects based on the passed
        MonitorMetricList object.
        """
    payloads = []
    for monitor_metric in monitor_metric_list:
        payloads.append(cls(monitor_metric))
    return payloads


def needs_update():
    """return if this feed needs to be updated"""


def _shorten_key(telstate, key):
    """Shorten telstate key by subtracting the first prefix that fits.

    Parameters
    ----------
    telstate : :class:`katdal.sensordata.TelstateToStr` object
        Telescope state
    key : string
        Telescope state key

    Returns
    -------
    short_key : string
        Suffix of `key` after subtracting first matching prefix, or empty
        string if `key` does not start with any of the prefixes (or exactly
        matches a prefix, which is also considered pathological)

    """
    for prefix in telstate.prefixes:
        if key.startswith(prefix):
            return key[len(prefix):]
    return ''


def __setitem__(key, value):
    """
        Either set or update an entry.

        If the key already existed in the cache, then update its
        ``value`` to the new *value* and mark it as the most recently
        used.

        Otherwise, create a new entry for the key, setting it to the
        most recently used.

        This may evict other items.
        """


def assert_str(*args):
    """
    porting helper, assert args type
    """
    for x in args:
        assert isinstance(x, str)


@staticmethod
def _is_enabled(spec):
    """
        Determines if a spec is enabled.

        :param dict spec: Specification to check
        :return: If the spec is enabled
        :rtype: bool
        """
    if 'enabled' in spec:
        return bool(spec['enabled'])
    else:
        return True


def progbar(i, i_max, bar_len=20, spinner=True, spin_rate=3.0):
    """A textual progress bar for the command line

    | Args:
    |   i (int): current progress index
    |   max_i (int): final progress index
    |   bar_len (Optional[int]): length in characters of the bar (no brackets)
    |   spinner (Optional[bool]): show a spinner at the end
    |   spin_rate (Optional[float]): spinner rotation speed (turns per full
    |                                progress)

    | Returns:
    |   bar (str): a progress bar formatted as requested

    """
    block = {(True): '█', (False): ' '}
    spin = '|\\-/'
    perc = i / float(i_max) * bar_len
    bar = '[{0}]'.format(''.join([block[i < perc] for i in range(bar_len)]))
    if spinner:
        bar += ' {0}'.format(spin[int(perc * spin_rate) % len(spin)])
    return bar


def _near_words(first, second, distance, exact=False):
    """
    Returns a query item matching messages that two words within a certain
    distance of each other.

    Args:
        first (str): The first word to search for.
        second (str): The second word to search for.
        distance (int): How many words apart first and second can be.
        exact (bool): Whether first must come before second [default False].

    Returns:
        The query string.

    """
    query = f'{first} AROUND {distance} {second}'
    if exact:
        query = '"' + query + '"'
    return query


def faces_shade_smooth():
    """Display faces smooth (using vertex normals)

    """
    pass


def get_key():
    """Get key from user."""
    try:
        text = input('Enter a key (1 - 25): ')
        key = int(text)
        return key
    except:
        print('Invalid key. Using key: 0.')
        return 0


def keyconfig_preset_add(name: str='', remove_name: bool=False,
    remove_active: bool=False):
    """Add or remove a Key-config Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_name: remove_name
    :type remove_name: bool
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def create_github_repo(config, push=True):
    """If in new project directory, begin clone and push to GitHub."""
    pass


def t_Predicate(t):
    """[A-Z][a-zA-Z]*\\(.+?\\)"""
    return t


def coordinates_controlpanel_install(context):
    """Coordinates controlpanel script"""


def paste():
    """Paste strips from clipboard

    """
    pass


def memberness(context):
    """The likelihood that the context is a "member"."""
    if context:
        texts = context.xpath('.//*[local-name()="explicitMember"]/text()'
            ).extract()
        text = str(texts).lower()
        if len(texts) > 1:
            return 2
        elif 'country' in text:
            return 2
        elif 'member' not in text:
            return 0
        elif 'successor' in text:
            return 1
        elif 'parent' in text:
            return 2
    return 3


def synthesim_vals(offset, tval, varval):
    """
    This is a specialized function that uses memory managed by Vensim
    to give access to values while SyntheSim is active.

    currently not implemented
    """
    raise NotImplementedError


def add_edge(graph, edge):
    """Adds an edge to a given graph.

  If an edge between the two nodes already exists, the one with the largest
  weight is retained.

  Args:
    graph: A `dict`: source_id -> (target_id -> weight) to be augmented.
    edge: A `list` (or `tuple`) of the form `[source, target, weight]`, where
      `source` and `target` are strings, and `weight` is a numeric value of
      type `string` or `float`. The 'weight' component is optional; if not
      supplied, it defaults to 1.0.

  Returns:
    `None`. Instead, this function has a side-effect on the `graph` argument.
  """
    source = edge[0]
    if source not in graph:
        graph[source] = {}
    t_dict = graph[source]
    target = edge[1]
    weight = float(edge[2]) if len(edge) > 2 else 1.0
    if target not in t_dict or weight > t_dict[target]:
        t_dict[target] = weight


def _CallWindowsNetCommand(parameters):
    """
    Call Windows NET command, used to acquire/configure network services settings.

    :param parameters: list of command line parameters

    :return: command output
    """
    import subprocess
    popen = subprocess.Popen(['net'] + parameters, stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    stdoutdata, stderrdata = popen.communicate()
    if stderrdata:
        raise OSError('Failed on call net.exe: %s' % stderrdata)
    return stdoutdata


@classmethod
def append_to_run_from_text(cls, r, text):
    """
        Create a "one-shot" ``_RunContentAppender`` instance and use it to
        append the run content elements corresponding to *text* to the
        ``<w:r>`` element *r*.
        """
    appender = cls(r)
    appender.add_text(text)


@classmethod
def check_uri(cls, uri):
    """Check URI for validity

        Raises ValueError appropriately
        """
    if len(uri) > cls.MAX_URI_LENGTH:
        raise ValueError('URI exceeds maximum length')
    for char in uri:
        if char not in cls.ALLOWED_URI_CHARS:
            raise ValueError('URI contains invalid character %r' % bytes([
                char]))


@staticmethod
def _get_significance_code(p_value):
    """
        Significance codes:
            ‘***’ if <= 0.001
            ‘**’  if <= 0.01
            ‘*’   if <= 0.05
            ‘.’   if <= 0.1
            else ‘ ’
        :param p_value: p-value to convert
        :return: code
        """
    if p_value <= 0.001:
        return '***'
    elif p_value <= 0.01:
        return '**'
    elif p_value <= 0.05:
        return '*'
    elif p_value <= 0.1:
        return '.'
    else:
        return ''


def freq_by_extremums(xdata, sample_rate):
    """ Calculate frequency of oscillating signal by extremums.

    Parameters
    ----------
    xdata: array_like
        Values of input signals.
    sample_rate: float
        Sampling frequency (Hz).

    Returns
    -------
    : float
        Frequency.
    """
    T = len(xdata) / sample_rate
    n_max = 0
    n_min = 0
    for x_p, x_c, x_n in zip(xdata[:-2], xdata[1:-1], xdata[2:]):
        if x_p < x_c and x_c >= x_n:
            n_max += 1
        if x_p > x_c and x_c <= x_n:
            n_min += 1
    n = (n_max + n_min) / 2
    return n / T


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


def 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 domain_verification_add_domain_success(cls, val):
    """
        Create an instance of this class set to the
        ``domain_verification_add_domain_success`` tag with value ``val``.

        :param DomainVerificationAddDomainSuccessType val:
        :rtype: EventType
        """
    return cls('domain_verification_add_domain_success', val)


def _gapfind(wcc):
    """
    finds the largest gap in vector wcc, modulo 1
    """
    wcc = sorted(wcc)
    gapsize = 0
    gappos = 0
    N = len(wcc)
    for i, (w1, w2) in enumerate(zip(wcc, wcc[1:])):
        temp = w2 - w1
        if temp > gapsize:
            gapsize = temp
            gappos = i
    temp = wcc[0] - wcc[-1] + 1
    if temp > gapsize:
        gapsize = temp
        gappos = N - 1
    return (wcc[gappos] + gapsize / 2) % 1, gapsize


def short_instance_profile(instance_profile=None):
    """
    @type instance_profile: dict
    """
    if instance_profile and instance_profile.get('Arn'):
        return instance_profile.get('Arn')