def histogram(values, mode=0, bin_function=None):
    """Return a list of (value, count) pairs, summarizing the input values.
    Sorted by increasing value, or if mode=1, by decreasing count.
    If bin_function is given, map it over values first."""
    if bin_function:
        values = map(bin_function, values)
    bins = {}
    for val in values:
        bins[val] = bins.get(val, 0) + 1
    if mode:
        return sorted(list(bins.items()), key=lambda x: (x[1], x[0]),
            reverse=True)
    return sorted(bins.items())


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 _concat_csv(csv_file_list, output_file):
    """
    Helper function for concat_csv
    """
    import pandas as pd
    input_dfs = list(map(lambda x: pd.read_csv(x, header=[0], index_col=[0]
        ), csv_file_list))
    result_df = pd.concat(input_dfs, axis=0, sort=False)
    result_df.to_csv(output_file)
    return result_df


@staticmethod
def set_collapsed(block, val):
    """
        Sets the fold trigger state (collapsed or expanded).

        :param block: The block to modify
        :param val: The new trigger state (True=collapsed, False=expanded)
        """
    if block is None:
        return
    state = block.userState()
    if state == -1:
        state = 0
    state &= 2013265919
    state |= int(val) << 27
    block.setUserState(state)


def dialect_compare(dialect1, dialect2):
    """
    Compares two dialects.
    """
    orig = set(dialect1.items())
    new = set(dialect2.items())
    return dict(added=dict(list(new.difference(orig))), removed=dict(list(
        orig.difference(new))))


@staticmethod
def deep_copy_set(sol_set):
    """
        Deep copy an solution set

        :param sol_set: solution set
        :return: copied solution set
        """
    result_set = []
    for sol in sol_set:
        result_set.append(sol.deep_copy())
    return result_set


@classmethod
def add(cls, wrd):
    """ Add an adjective """
    cls.ADJECTIVES.add(wrd)


def manage_setTypePolicies(policy_map):
    """Set the policy_mapping for all types from a dict of
        content_type : policy list mappings {content_type: [policy1, policy2]}
        """


def to_kwh(joules):
    """ Converts from watts used in a timeframe (in seconds) to kwh """
    watt_hours = joules / 3600
    return watt_hours / 1000


@staticmethod
def isTie(state):
    """
		True if the given state finishes the game without a winner

		:param state:  Game state to evaluate (GameState)
		:raises NotImplementedError: if child does not override this function
		"""
    raise NotImplementedError


@classmethod
def log_error(cls, *args, **kwargs):
    """ Write error message into log """
    pass


def yesno(prompt):
    """Returns True if user answers 'y' """
    prompt += ' [y/n]'
    a = ''
    while a not in ['y', 'n']:
        a = input(prompt).lower()
    return a == 'y'


def brush_colors_flip():
    """Toggle foreground and background brush colors

    """
    pass


@classmethod
def dump(cls, data, encoding='ascii'):
    '\n        Convert str to appropriate format for "UserComment".\n\n        :param data: Like u"foobar"\n        :param str encoding: "ascii", "jis", or "unicode"\n        :return: b"ASCII\x00\x00\x00foobar"\n        :rtype: bytes\n        :raises: ValueError if the encoding is unsupported.\n        '
    if encoding not in cls.ENCODINGS:
        raise ValueError('encoding {!r} must be one of {!r}'.format(
            encoding, cls.ENCODINGS))
    prefix = {cls.ASCII: cls._ASCII_PREFIX, cls.JIS: cls._JIS_PREFIX, cls.
        UNICODE: cls._UNICODE_PREFIX}[encoding]
    internal_encoding = {cls.UNICODE: cls._UNICODE, cls.JIS: cls._JIS}.get(
        encoding, encoding)
    return prefix + data.encode(internal_encoding, errors='replace')


@staticmethod
def max_none(a, b):
    """A max() version that discards None values."""
    if a is None:
        return b
    if b is None:
        return a
    return max(a, b)


def get_center_position_ver(canvas_width, canvas_height, image_h_in):
    """
    Get the correct position for an image to center it vertically
    """
    _canvas_mid = int(canvas_height / 2)
    _image_in_mid = int(image_h_in / 2)
    return _canvas_mid - _image_in_mid


@staticmethod
def _label_encoder(X, Y, sample_weight):
    """
        Convert input to proper format to be used by sklearn logistic regression.
        Basically do nothing for the discrete case.
        This function overrides parent class.
        Parameters
        ----------
        X : design matrix of shape (n_samples, n_features), 2d
        Y : response matrix of shape (n_samples, )
        sample_weight: sample weight vector of shape (n_samples, )
        Returns
        -------
        X_transformed : design matrix of shape (n_samples, n_features), 2d
        Y_transformed : response matrix of shape (n_samples, )
        sample_weight_transformed: sample weight vector of shape (n_samples, )
        """
    if Y.ndim == 2 and Y.shape[1] == 1:
        Y = Y.reshape(-1)
    return X, Y, sample_weight


def components_from_total(total_mass, mass_ratio):
    """
    Calculate the component black hole masses from the total mass
    of the system and the mass ratio.
    """
    m1 = total_mass / (mass_ratio + 1)
    m2 = total_mass - m1
    return m1, m2


def strings_differ(string1, string2, compare_digest=compare_digest):
    """Check whether two strings differ while avoiding timing attacks.

    This function returns True if the given strings differ and False
    if they are equal.  It's careful not to leak information about *where*
    they differ as a result of its running time, which can be very important
    to avoid certain timing-related crypto attacks:

        http://seb.dbzteam.org/crypto/python-oauth-timing-hmac.pdf

    .. versionchanged:: 1.6
       Support :func:`hmac.compare_digest` if it is available (Python 2.7.7+
       and Python 3.3+).

    """
    len_eq = len(string1) == len(string2)
    if len_eq:
        invalid_bits = 0
        left = string1
    else:
        invalid_bits = 1
        left = string2
    right = string2
    if compare_digest is not None:
        invalid_bits += not compare_digest(left, right)
    else:
        for a, b in zip(left, right):
            invalid_bits += a != b
    return invalid_bits != 0


@classmethod
def all(cls, *args, **kwargs):
    """
        Return a list of instances of backend type
        """
    return list(cls.iterator(*args, **kwargs))


def last_player(played_cards, players):
    """
    Who played the last card?
    :param played_cards:
    :param players:
    :return: The players name
    """
    if len(played_cards) == 0:
        return None
    return players[(len(played_cards) - 1) % len(players)]


def bisect_right(a, x, lo=0, hi=None):
    """Return the index where to insert item x in list a, assuming a is sorted.

    The return value i is such that all e in a[:i] have e <= x, and all e in
    a[i:] have e > x.  So if x already appears in the list, a.insert(x) will
    insert just after the rightmost x already there.

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


@classmethod
def unregister_optimiser(klass, optimiser):
    """Unregister an InterObject optimiser."""
    klass._optimisers.remove(optimiser)


def hms_string(sec_elapsed):
    """Utility to get the hour:minute:seceonds for an
       elapsed period in seconds"""
    h = int(sec_elapsed / (60 * 60))
    m = int(sec_elapsed % (60 * 60) / 60)
    s = sec_elapsed % 60
    return '%02d:%02d:%02d' % (h, m, s)


def backend(*ka):
    """
    Backend for setting all comments to spam.
    """
    return True


def flatten_list(items, seqtypes=(list, tuple), in_place=True):
    """Flatten an irregular sequence.

    Works generally but may be slower than it could
    be if you can make assumptions about your list.

    `Source`__

    __ https://stackoverflow.com/a/10824086

    Parameters
    ----------
    items : iterable
        The irregular sequence to flatten.
    seqtypes : iterable of types (optional)
        Types to flatten. Default is (list, tuple).
    in_place : boolean (optional)
        Toggle in_place flattening. Default is True.

    Returns
    -------
    list
        Flattened list.

    Examples
    --------
    >>> l = [[[1, 2, 3], [4, 5]], 6]
    >>> wt.kit.flatten_list(l)
    [1, 2, 3, 4, 5, 6]
    """
    if not in_place:
        items = items[:]
    for i, _ in enumerate(items):
        while i < len(items) and isinstance(items[i], seqtypes):
            items[i:i + 1] = items[i]
    return items


def complete_layer_upload(registryId=None, repositoryName=None, uploadId=
    None, layerDigests=None):
    """
    Inform Amazon ECR that the image layer upload for a specified registry, repository name, and upload ID, has completed. You can optionally provide a sha256 digest of the image layer for data validation purposes.
    See also: AWS API Documentation

    :example: response = client.complete_layer_upload(
        registryId='string',
        repositoryName='string',
        uploadId='string',
        layerDigests=[
            'string',
        ]
    )

    :type registryId: string
    :param registryId: The AWS account ID associated with the registry to which to upload layers. If you do not specify a registry, the default registry is assumed.

    :type repositoryName: string
    :param repositoryName: [REQUIRED]
            The name of the repository to associate with the image layer.

    :type uploadId: string
    :param uploadId: [REQUIRED]
            The upload ID from a previous InitiateLayerUpload operation to associate with the image layer.

    :type layerDigests: list
    :param layerDigests: [REQUIRED]
            The sha256 digest of the image layer.
            (string) --

    :rtype: dict
    :return: {
        'registryId': 'string',
        'repositoryName': 'string',
        'uploadId': 'string',
        'layerDigest': 'string'
    }

    """
    pass


@staticmethod
def fix_url_encode(url) ->str:
    """
        Change brackets back to normal brackets since SMAX API
        refuses to accept properly URL encoded string
        :param url: Encoded url to fix
        :return: fixed URL
        """
    return str(url).replace('%28', '(').replace('%2C', ',').replace('%29', ')')


def check_type_and_values_of_specification_dict(specification_dict,
    unique_alternatives):
    """
    Verifies that the values of specification_dict have the correct type, have
    the correct structure, and have valid values (i.e. are actually in the set
    of possible alternatives). Will raise various errors if / when appropriate.

    Parameters
    ----------
    specification_dict : OrderedDict.
        Keys are a proper subset of the columns in `long_form_df`. Values are
        either a list or a single string, `"all_diff"` or `"all_same"`. If a
        list, the elements should be:

            - single objects that are within the alternative ID column of
              `long_form_df`
            - lists of objects that are within the alternative ID column of
              `long_form_df`. For each single object in the list, a unique
              column will be created (i.e. there will be a unique coefficient
              for that variable in the corresponding utility equation of the
              corresponding alternative). For lists within the
              `specification_dict` values, a single column will be created for
              all the alternatives within iterable (i.e. there will be one
              common coefficient for the variables in the iterable).
    unique_alternatives : 1D ndarray.
        Should contain the possible alternative id's for this dataset.

    Returns
    -------
    None.
    """
    for key in specification_dict:
        specification = specification_dict[key]
        if isinstance(specification, str):
            if specification not in ['all_same', 'all_diff']:
                msg = "specification_dict[{}] not in ['all_same', 'all_diff']"
                raise ValueError(msg.format(key))
        elif isinstance(specification, list):
            for group in specification:
                group_is_list = isinstance(group, list)
                if group_is_list:
                    for group_item in group:
                        if isinstance(group_item, list):
                            msg = 'Wrong structure for specification_dict[{}]'
                            msg_2 = ' Values can be a list of lists of ints,'
                            msg_3 = ' not lists of lists of lists of ints.'
                            total_msg = msg.format(key) + msg_2 + msg_3
                            raise ValueError(total_msg)
                        elif group_item not in unique_alternatives:
                            msg_1 = '{} in {} in specification_dict[{}]'
                            msg_2 = ' is not in long_format[alt_id_col]'
                            total_msg = msg_1.format(group_item, group, key
                                ) + msg_2
                            raise ValueError(total_msg)
                elif group not in unique_alternatives:
                    msg_1 = '{} in specification_dict[{}]'
                    msg_2 = ' is not in long_format[alt_id_col]'
                    raise ValueError(msg_1.format(group, key) + msg_2)
        else:
            msg = "specification_dict[{}] must be 'all_same', 'all_diff', or"
            msg_2 = ' a list.'
            raise TypeError(msg.format(key) + msg_2)
    return None


def get_hr_val(choices, db_val):
    """
    Get the human readable value for the DB value from a choice tuple.

    Args:
        choices (tuple): The choice tuple given in the model.
        db_val: The respective DB value.

    Returns:
        The matching human readable value.
    """
    for pair in choices:
        if pair[0] == db_val:
            return pair[1]
    return None


def info():
    """Return upgrade recipe information."""
    return 'Fixes foreign key relationship.'


def fill_grid(span: int=1, offset: int=0, use_interp_simple: bool=False):
    """Fill grid from two loops

    :param span: Span, Number of sides (zero disables)
    :type span: int
    :param offset: Offset, Number of sides (zero disables)
    :type offset: int
    :param use_interp_simple: Simple Blending
    :type use_interp_simple: bool
    """
    pass


def listToFile(inList, fileName, extension=None):
    """Converts a list of file names into a file that can be used in iraf with the @ syntax.

    Returns the file name of the list file, with @ prefix added already.

    """
    listFile = open(fileName, 'w')
    for inFile in inList:
        if extension == None:
            listFile.write(inFile + '\n')
        else:
            listFile.write(inFile + extension + '\n')
    listFile.close()
    return '@' + fileName


def calc_cn_values(m, sigma_veff):
    """
    CN parameter from CPT, Eq 2.15a
    """
    c_n = (100 / sigma_veff) ** m
    if c_n > 1.7:
        c_n = 1.7
    return c_n


def is_kernelspec_model(spec_dict):
    """Returns True if spec_dict is already in proper form.  This will occur when using a gateway."""
    return (isinstance(spec_dict, dict) and 'name' in spec_dict and 'spec' in
        spec_dict and 'resources' in spec_dict)


@classmethod
def from_uri(cls, uri):
    """
        from_uri class method create a class instance from url

        >> from gcspath import PureGCSPath
        >> PureGCSPath.from_url('gs://<bucket>/')
        << PureGCSPath('/<bucket>')
        """
    if not uri.startswith('gs://'):
        raise ValueError('...')
    return cls(uri[4:])


def isGlobalDBS(dbs):
    """Is this the global dbs"""
    try:
        from urlparse import urlparse
        url = urlparse(dbs.dbs.getServerUrl())
        if url.hostname.startswith('cmsweb.cern.ch') and url.path.startswith(
            '/dbs/prod/global'):
            return True
        info = dbs.dbs.getServerInfo()
        if info and info.get('InstanceName') == 'GLOBAL':
            return True
        return False
    except Exception:
        dbs.dbs.serverinfo()
        url = dbs.dbs.url
        if url.find('/global') != -1:
            return True
        else:
            return False


def _load_class(cls, d):
    """
    Loads additional properties into class `cls`.
    """
    for k, v in d.items():
        if isinstance(k, tuple):
            typ, k = k
            if typ == 'property':
                v = property(*v)
            elif typ == 'staticmethod':
                v = staticmethod(v)
            elif typ == 'classmethod':
                v = classmethod(v)
        setattr(cls, k, v)
    return cls


def psi_Ca_MgOH_Cl_HMW84(T, P):
    """c-c'-a: calcium magnesium-hydroxide chloride [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def get_all_app(isdsAppliance, check_mode=False, force=False):
    """
    Retrieving all application interfaces
    :rtype: (str, dict)
    """
    return isdsAppliance.invoke_get('Retrieving all application interfaces',
        '/application_interfaces')


def permutation_to_cosine(permutation, flip):
    """Get mhd direction cosine for this dimension permutation"""
    dir_cosine = [0, 0, 0, 0, 0, 0, 0, 0, 0]
    dir_cosine[permutation[0] * 3] = -1 if flip[0] else 1
    dir_cosine[permutation[1] * 3 + 1] = -1 if flip[1] else 1
    dir_cosine[permutation[2] * 3 + 2] = -1 if flip[2] else 1
    return dir_cosine


def add_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    Setting = apps.get_model('settings', 'Setting')
    key = ''
    try:
        key = 'MANAGER_PRODUCT_ID'
        Setting.objects.get(key=key)
    except Exception:
        Product = apps.get_model('products', 'Product')
        ContentType = apps.get_model('contenttypes', 'ContentType')
        product = Product.objects.create(price_fabric=1, title=
            'محصول مدیریتی', is_show_only_for_super_user=True,
            aparnik_bon_return_value=1, maximum_use_aparnik_bon_value=1,
            aparnik_bon_return_expire_value=0)
        new_ct = ContentType.objects.get_for_model(Product)
        Product.objects.filter(polymorphic_ctype__isnull=True).update(
            polymorphic_ctype=new_ct)
        Setting.objects.create(title='آی دی محصول مدیریتی', key=key, value=
            str(product.id), value_type='i', is_show=False,
            is_variable_in_home=False)


def bookmark_add():
    """Add a bookmark for the selected/active directory

    """
    pass


def get_build_os_arch(conanfile):
    """ Returns the value for the 'os' and 'arch' settings for the build context """
    if hasattr(conanfile, 'settings_build'):
        return conanfile.settings_build.get_safe('os'
            ), conanfile.settings_build.get_safe('arch')
    else:
        return conanfile.settings.get_safe('os_build'
            ), conanfile.settings.get_safe('arch_build')


def _build_projection_expression(clean_table_keys):
    """Given cleaned up keys, this will return a projection expression for
    the dynamodb lookup.

    Args:
        clean_table_keys (dict): keys without the data types attached

    Returns:
        str: A projection expression for the dynamodb lookup.
    """
    projection_expression = ''
    for key in clean_table_keys[:-1]:
        projection_expression += '{},'.format(key)
    projection_expression += clean_table_keys[-1]
    return projection_expression


@classmethod
def from_filename(cls, filename):
    """Read the struct from a file given its path."""
    with open(str(filename)) as f:
        string = f.read()
    return cls.from_string(string)


def decode_prop(prop):
    """ Decode a prop string.

    Parameters
    ----------
    prop : bytestring

    Returns
    -------
    string
    """
    encoding = 'utf-16-be' if b'\x00' in prop else 'utf-8'
    return prop.decode(encoding)


def _add_cstar_arguments_without_command(parser):
    """Argument parsing for case when cstar is called without specifying a command to run"""
    parser.add_argument('--max-job-age', default=7, type=int, help=
        'Maximum age in days of a job to resume')


def calculate_rotational_inertia_forces(vehicle_mass, inertial_factor,
    accelerations):
    """
    Calculate rotational inertia forces [N].

    :param vehicle_mass:
        Vehicle mass [kg].
    :type vehicle_mass: float

    :param inertial_factor:
        Factor that considers the rotational inertia [%].
    :type inertial_factor: float

    :param accelerations:
        Acceleration vector [m/s2].
    :type accelerations: numpy.array | float

    :return:
        Rotational inertia forces [N].
    :rtype: numpy.array | float
    """
    return vehicle_mass * inertial_factor * accelerations / 100


@classmethod
def createActiveMask(cls, range_string):
    """
        Will create a BoolVector instance with the values from @range_string.

        The range_string input should be of the type "1,3-5,9,17",
        i.e. integer values separated by commas, and dashes to
        represent ranges. If the input string contains ANY invalid
        characters the returned active list will be empty:

           "1,4-7,10"  =>  {F,T,F,F,T,T,T,T,F,F,T}
           "1,4-7,10X" =>  {}

        The empty list will evaluate to false
        @rtype: BoolVector
        """
    return cls._create_active_mask(range_string)


def _formatter_class(name, value):
    """Format the "klass" variable and value on class methods.
    """
    __mname = value.__module__
    if __mname != '__main__':
        return "%s = <type '%s.%s'>" % (name, __mname, value.__name__)
    else:
        return "%s = <type '%s'>" % (name, value.__name__)


def getNewZoom(current, move, xmax, ymax, ymin=0):
    """
        Get new zoom location (x, and y ranges) by given current zoom, move vector and x,y maximum ranges
        :param current: current zoom location
        :param move: moving vector
        :param xmax: maximum x
        :param ymax: maximum y
        :param ymin: minimum y
        :return:
        """
    x1 = current[0][0] + move[0]
    x2 = current[0][1] + move[0]
    if x1 < 0:
        x1 = 0
        x2 = current[0][1] - current[0][0]
    if x2 >= xmax:
        x2 = xmax - 1
        x1 = x2 - (current[0][1] - current[0][0])
    y1 = current[1][0] + move[1]
    y2 = current[1][1] + move[1]
    if y1 < ymin:
        y1 = ymin
        y2 = y1 + (current[1][1] - current[1][0])
    if y2 > ymax:
        y2 = ymax
        y1 = y2 - (current[1][1] - current[1][0])
    return [(x1, x2), (y1, y2)]


def is_bullish_engolfing(body, open, close):
    """ Se existir engolfo de alta retorna True."""
    if body[1] > 0 and body[0] < 0:
        if open[1] <= close[0] and close[1] >= open[0]:
            return True
    return False


def transform_attribute(attribute_list):
    """
    Transforms tag attributes.

    kwargs
        - name: String
        - value: String
    """
    updated_attribute_list = []
    for attribute_parameters in attribute_list:
        updated_attribute_list.append({'Name': attribute_parameters.get(
            'name'), 'Value': attribute_parameters.get('value')})
    return updated_attribute_list


def pre_upgrade():
    """Pre-upgrade checks."""
    pass


def format_value(v):
    """
    Formats a value to be included in a string.

    @param      v           a string
    @return                 a string
    """
    if isinstance(v, str):
        return "'{0}'".format(v.replace("'", "\\'"))
    else:
        return '{0}'.format(v)


def first(x):
    """Return the first member of a list."""
    try:
        x = x.to_series()
    except AttributeError:
        pass
    return list(x)[0]


def _thread_run_user_function(user_function, result_queue, work_items, args,
    **kwargs):
    """ This is run by each thread. The work is processed and results are put into a queue. """
    for item in work_items:
        result = user_function(item, *args, **kwargs)
        result_queue.put(result)
        del item


def vect(v1, v2):
    """Yields the vector product of `v1` and `v2`."""
    x1, y1, z1 = v1
    x2, y2, z2 = v2
    result = y1 * z2 - z1 * y2, x2 * z1 - x1 * z2, x1 * y2 - y1 * x2
    return result


def setOutgoingInterface(addr):
    """
        Set interface for outgoing multicast packets.

        Returns Deferred of success.
        """


def _chunk_write(chunk, local_file, progress):
    """Write a chunk to file and update the progress bar"""
    local_file.write(chunk)
    progress.update_with_increment_value(len(chunk))


def refresh_nameplates():
    """
        Refresh the nameplates list.

        This asks the server for the set of currently-active nameplates
        (either from calls to ``allocate_code()`` or referenced by active
        wormhole clients).  It updates the set available to
        ``get_nameplate_completions()``.

        :return: None
        """


def get(cls, name, default=None):
    """Returns instance by name."""
    return cls.instances.get(name, default)


def ch2h(ch, e):
    """Transform from *h* index value to *w* count value, using the
    *e.css('ch')* (column height) as column measure."""
    if ch is None:
        h = 0
    else:
        gh = e.gh
        h = ch * (e.css('ch', 0) + gh) - gh
    return h


@staticmethod
def sanity_check_categorical(df):
    """Sanity check for 'dimensionality explosion' on categorical types
        Args:
            df (dataframe): The dataframe to check the categorical columns
        Returns:
            None
        """
    for column in df.select_dtypes(include='category').columns:
        num_unique = df[column].nunique()
        if num_unique > 20:
            print('WARNING: {:s} will expand into {:d} dimensions...'.
                format(column, num_unique))


def set_scene_frames():
    """Set scene’s start and end frame to match clip’s start frame and length

    """
    pass


def add_servers_config(conn, config):
    """
    Add the activated remote servers stored on the repository database to a
    given configuration JSON.
    """
    if 'servers' not in config:
        config['servers'] = {}
    cur = conn.cursor()
    cur.execute(
        """
                SELECT id, hostname, port, username, password, dbname,
                    frequency
                FROM public.powa_servers s
                WHERE s.id > 0
                AND s.frequency > 0
                ORDER BY id
            """
        )
    for row in cur:
        parms = {}
        parms['host'] = row[1]
        parms['port'] = row[2]
        parms['user'] = row[3]
        if row[4] is not None:
            parms['password'] = row[4]
        parms['dbname'] = row[5]
        key = row[1] + ':' + str(row[2])
        config['servers'][key] = {}
        config['servers'][key]['dsn'] = parms
        config['servers'][key]['frequency'] = row[6]
        config['servers'][key]['srvid'] = row[0]
    conn.commit()
    return config


def sorted_names(names):
    """
    Sort a list of names but keep the word 'default' first if it's there.
    """
    names = list(names)
    have_default = False
    if 'default' in names:
        names.remove('default')
        have_default = True
    sorted_names = sorted(names)
    if have_default:
        sorted_names = ['default'] + sorted_names
    return sorted_names


def guessAperFromLocn(life_adj, aperypos):
    """Infer which aperture was in use from the aperture position.

    Parameters
    ----------
    life_adj: int or "N/A"
        Integer code for the "lifetime position," or "N/A" if the LIFE_ADJ
        keyword was not found in the header.

    aperypos: float or "N/A"
        Location (in steps) of the aperture block, or "N/A" if the keyword
        was not found in the header.

    Returns
    -------
    aperture: str or None
        An educated guess as to which aperture was in use, either "PSA" or
        "BOA".  None will be returned if the input arguments were not
        sufficient for determining the aperture.
    """
    if life_adj == 1:
        if 116.0 < aperypos and aperypos < 136.0:
            aperture = 'PSA'
        elif -163.0 < aperypos and aperypos < -143.0:
            aperture = 'BOA'
        else:
            aperture = None
    elif life_adj == 2:
        if 52.0 < aperypos and aperypos < 72.0:
            aperture = 'PSA'
        elif -227.0 < aperypos and aperypos < -207.0:
            aperture = 'BOA'
        else:
            aperture = None
    else:
        aperture = None
    return aperture


def _augment_exception(exc, version, arch=''):
    """
    Add details to the exception message to help guide the user
    as to what action will resolve it.
    """
    message = exc.args[0]
    if 'vcvarsall' in message.lower() or 'visual c' in message.lower():
        tmpl = 'Microsoft Visual C++ {version:0.1f} is required.'
        message = tmpl.format(**locals())
        msdownload = 'www.microsoft.com/download/details.aspx?id=%d'
        if version == 9.0:
            if arch.lower().find('ia64') > -1:
                message += ' Get it with "Microsoft Windows SDK 7.0": '
                message += msdownload % 3138
            else:
                message += ' Get it from http://aka.ms/vcpython27'
        elif version == 10.0:
            message += ' Get it with "Microsoft Windows SDK 7.1": '
            message += msdownload % 8279
        elif version >= 14.0:
            message += (
                ' Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools'
                )
    exc.args = message,


def wrapb(parent, child):
    """Return the child node as a string, wrapped in brackets if its precedence
    is higher than the parent node.
    """
    if child.prec > parent.prec:
        return '[{}]'.format(child)
    else:
        return str(child)


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


def get_index(col, index, default=None):
    """Get the col[index] or default if index is out of bounds"""
    if abs(index) < len(col):
        return default
    return col[index]


def chunks(lst, chunk_size):
    """Chunk a list into specified chunk sizes."""
    for i in range(0, len(lst), chunk_size):
        yield lst[i:i + chunk_size]


@classmethod
def create(cls, name):
    """Create a provider based on the provider name.

        Parameters
        ----------
        name : str
            Name of the provider (eg. UCSC, Ensembl, ...)

        Returns
        -------
        provider : Provider instance
            Provider instance.
        """
    try:
        return cls._providers[name.lower()]()
    except KeyError:
        raise Exception('Unknown provider')


@staticmethod
def max(tensor):
    """The max value in a tensor.

        Parameters
        ----------
        tensor : tensor

        Returns
        -------
        scalar
        """
    raise NotImplementedError


def get_excluded_params(schema):
    """
    Get all params excluded in this schema,
    if "only" is provided in schema instance,
    consider all not included params as excluded.
    :param schema: instance or cls schema
    :return: set of excluded params
    """
    if isinstance(schema, type):
        return set()
    exclude = set()
    only = set()
    if getattr(schema, 'exclude', ()):
        exclude = set(getattr(schema, 'exclude', ()))
    if getattr(schema, 'only', ()):
        only = set(getattr(schema, 'only', ()))
    if only:
        for field in schema._declared_fields:
            if field not in only:
                exclude.add(str(field))
    return exclude


@classmethod
def from_module(cls, module):
    """
            Create an instance of SettingsContainer with values based
            on the one in the passed module.
        """
    settings = cls()
    settings.update_with_module(module)
    return settings


@staticmethod
def extensions():
    """Return accepted extensions for this loader"""
    return ('bmp', 'dpx', 'exr', 'gif', 'ico', 'jpeg', 'jpg2000', 'jpg',
        'jls', 'pam', 'pbm', 'pcx', 'pgm', 'pgmyuv', 'pic', 'png', 'ppm',
        'ptx', 'sgi', 'ras', 'tga', 'tiff', 'webp', 'xbm', 'xface', 'xwd')


@staticmethod
def to_bytes(something, encoding='utf8'):
    """
        cast string to bytes() like object, but for python2 support it's bytearray copy
        """
    if isinstance(something, bytes):
        return something
    if isinstance(something, str):
        return something.encode(encoding)
    elif isinstance(something, bytearray):
        return bytes(something)
    else:
        raise TypeError('Not a string or bytes like object')


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

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

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


def p_catalog_string(t):
    """catalog : CATALOG STRING"""
    t[0] = 'catalog', t[2]


def _handle_string(val):
    """
    Replaces Comments: and any newline found.

    Input is a cell of type 'string'.
    """
    return val.replace('Comments: ', '').replace('\r\n', ' ')


def setRecursionLimit(limit):
    """ Sets the recursion limit """
    global RECURSION_LIMIT
    RECURSION_LIMIT = limit


@staticmethod
def columns():
    """
        Return static columns names
        """
    return ['date_time', 'trade_id', 'trade_price', 'trade_volume',
        'trade_side']


def get_url_csl_item_zotero(url):
    """
    Use Zotero's translation-server to generate a CSL Item for the specified URL.
    """
    from manubot.cite.zotero import export_as_csl, web_query
    zotero_data = web_query(url)
    csl_data = export_as_csl(zotero_data)
    csl_item, = csl_data
    return csl_item


def html_of_unit(quant):
    """
	Returns HTML reperesentation of the unit of a quantity

	Examples
	--------
	>>> print(html_of_unit(2*quantities.m**2))
	m2
	"""
    return quant.dimensionality.html


@classmethod
def _constructor(cls, mapping, configuration):
    """
        A standardized constructor.
        """
    sequence_type, default_factory, pass_key = configuration
    return cls(default_factory, mapping, sequence_type=sequence_type,
        pass_key=pass_key)


def isolation_isg(x):
    """
    Isolation index IS

    ...

    Arguments
    ---------
    x       : array
              N x k array containing N rows (one per neighborhood) and k columns
              (one per cultural group)
    Returns
    -------
    a       : array
              Array with ISg indices for the k groups
    """
    ws = x * 1.0 / x.sum(axis=0)
    pgapa = (x.T * 1.0 / x.sum(axis=1)).T
    pgp = x.sum(axis=0) * 1.0 / x.sum()
    return (ws * pgapa / pgp).sum(axis=0)


def mountpoints_list(*args):
    """Service Layer to get mountpoint list"""
    mountpoints_list = []
    for instance in args:
        mountpoints_list.append(instance.get_mountPoint_instances())
    return mountpoints_list


def golden_ratio(figwidth=5):
    """Return the figure size (width, height) following the golden ratio given the width figwidth (default = 5)"""
    Phi = 1.61803
    a = figwidth / Phi
    return [figwidth, a]


def one_level_dict(res):
    """ Transforms nested dict to dictionary only one level deep """
    configs = []
    roots = []
    iters = []
    energies = []
    waves = []
    ints = []
    for config in res:
        for root in res[config]:
            for iteration in res[config][root]['peaks']:
                data = res[config][root]['peaks'][iteration]
                for val in data:
                    energy, wave, intensity = val
                    configs.append(config)
                    roots.append(root)
                    iters.append(iteration)
                    energies.append(energy)
                    waves.append(wave)
                    ints.append(intensity)
    output = {}
    output['Config'] = configs
    output['Root'] = roots
    output['Iteration'] = iters
    output['Transition Energies (eV)'] = energies
    output['Wavelength (nm)'] = waves
    output['Intensity (au)'] = ints
    return output


@classmethod
def get_by_id(cls, context, template_id):
    """Find a deploy template based on its integer ID.

        :param context: security context. NOTE: This should only
                        be used internally by the indirection_api.
                        Unfortunately, RPC requires context as the first
                        argument, even though we don't use it.
                        A context should be set when instantiating the
                        object, e.g.: DeployTemplate(context).
        :param template_id: The ID of a deploy template.
        :raises: DeployTemplateNotFound if the deploy template no longer
            appears in the database.
        :returns: a :class:`DeployTemplate` object.
        """
    db_template = cls.dbapi.get_deploy_template_by_id(template_id)
    template = cls._from_db_object(context, cls(), db_template)
    return template


def _custom_startswith(test_string, bytes_prefix, unicode_prefix):
    """
    Given a string that might be a bytestring or a Unicode string,
    return True if it starts with the appropriate prefix.
    """
    if isinstance(test_string, bytes):
        return test_string.startswith(bytes_prefix)
    else:
        return test_string.startswith(unicode_prefix)


def findv(ol, cond_func, cond_func_args=[]):
    """
        #mapv     i不作为map_func参数,共享相同的f,共享相同的o
        #         NOT take index as a param for map_func
        #         share common other_args
        #         share common cond_func
        #         common_func(value,*common_args)

    """
    rslt = []
    for i in range(ol.__len__()):
        cond = cond_func(ol[i], *cond_func_args)
        if cond:
            rslt.append((i, ol[i]))
        else:
            pass
    return rslt


def lerp(value, start, end, minimum=0.0, maximum=1.0):
    """
    Linear Interpolation between two points
    """
    value = float(value)
    start = float(start)
    end = float(end)
    return minimum + ((1.0 - value) * start + value * end) * maximum


def report_command_parser(parent_parser, configuration, **kwargs):
    """sets up the argument parser for the report command"""
    parser = parent_parser.add_parser('report', description=
        'Generate a report about modules and versions deployed in the puppet environments.'
        , help='generate a report about modules and versions')
    filter_group = parser.add_argument_group('filter options')
    filter_group.add_argument('-e', '--env', '--environment',
        '--environments', nargs='*', type=str, dest='environments', metavar
        ='PATTERN', help=
        'only report modules in environments matching any PATTERN. If the first supplied PATTERN is !, only report modules in environments NOT matching any PATTERN. PATTERN is a case-sensitive glob(7)-style pattern.'
        )
    filter_group.add_argument('-m', '--mod', '--module', '--modules', nargs
        ='*', type=str, dest='modules', help=
        'only report modules matching any PATTERN. If the first supplied PATTERN is !, only report modules NOT matching any PATTERN. PATTERN is a case-sensitive glob(7)-style pattern.'
        )
    display_group = parser.add_argument_group('display options')
    display_group.add_argument('-c', '--compare', dest='compare', action=
        'store_true', help=
        'compare mode will only show modules that differ between environments.'
        )
    version_check_group = display_group.add_mutually_exclusive_group()
    version_check_group.add_argument('--version-check', dest=
        'version_check', action='store_true', help=
        'disable check for latest version (forge modules) or latest git tag (git modules). The information is cached for subsequent runs. (default: %s)'
         % str(configuration.version_check))
    version_check_group.add_argument('--no-version-check', dest=
        'version_check', action='store_false', help=
        'disable check for latest version (forge modules) or latest git tag (git modules). (default: %s)'
         % str(not configuration.version_check))
    wrap_group = display_group.add_mutually_exclusive_group()
    wrap_group.add_argument('--wrap', dest='wrap', action='store_true',
        help='enable wrapping of long lines. (default: %s)' % str(
        configuration.wrap))
    wrap_group.add_argument('--no-wrap', dest='wrap', action='store_false',
        help='disable wrapping of long lines. (default: %s)' % str(not
        configuration.wrap))
    parser.set_defaults(version_check=configuration.version_check, wrap=
        configuration.wrap)
    return parser


def unmatched(match):
    """Return unmatched part of re.Match object."""
    start, end = match.span(0)
    return match.string[:start] + match.string[end:]


def is_healthy():
    """Return a boolean, True if the file/dir is fully healthy, False if
        it is damaged in any way. Non-distributed LIT files always return
        True."""


def is_clique(G, clique_nodes):
    """Determines whether the given nodes form a clique.

    A clique is a subset of nodes of an undirected graph such that every two
    distinct nodes in the clique are adjacent.

    Parameters
    ----------
    G : NetworkX graph
       The graph on which to check the clique nodes.

    clique_nodes : list
       List of nodes that form a clique, as
       determined by the given sampler.

    Returns
    -------
    is_clique : bool
        True if clique_nodes forms a clique.

    Example
    -------
    This example checks two sets of nodes, both derived from a
    single Chimera unit cell, for an independent set. The first set is
    the horizontal tile's nodes; the second has nodes from the horizontal and
    verical tiles.

    >>> import dwave_networkx as dnx
    >>> G = dnx.chimera_graph(1, 1, 4)
    >>> dnx.is_clique(G, [0, 1, 2, 3])
    False
    >>> dnx.is_clique(G, [0, 4])
    True
    """
    for x in clique_nodes:
        for y in clique_nodes:
            if x != y:
                if not G.has_edge(x, y):
                    return False
    return True


@classmethod
def parse(cls, buff, byteorder='big'):
    """Parse data from a file-like object and return a tag instance."""


def p_arglist_star2_1(p):
    """arglist_star2 : argument COMMA"""
    p[0] = [p[1]]


def _RIPPER_growphase_prune_metric_cn(cn, rule, pos_pruneset_idx,
    neg_pruneset_idx):
    """RIPPER/IREP* prune metric.
    Returns the prune value of a candidate Rule.

    Cohen's formula is (p-n) / (p+n).
    Unclear from the paper how they handle divzero (where p+n=0), so I Laplaced it.
    Weka's solution was to modify the formula to (p+1)/(p+n+2), but the (non-NaN) values I got appeared closer to those of the original formula.
    """
    p = len(cn.rule_covers(rule, pos_pruneset_idx))
    n = len(cn.rule_covers(rule, neg_pruneset_idx))
    return (p - n + 1) / (p + n + 1)


def indicate_last(items):
    """
    iterate through list and indicate which item is the last, intended to
    assist tree displays of hierarchical content.

    :return: yielding (<bool>, <item>) where bool is True only on last entry
    :rtype: generator
    """
    last_index = len(items) - 1
    for i, item in enumerate(items):
        yield i == last_index, item


@staticmethod
def get_hms_from_sec(sec):
    """
        Returns a string of hours:minutes:seconds from the seconds given.

        @param sec: seconds
        @param return: h:mm:ss as string
        """
    assert sec.__class__ == int
    seconds = sec % 60
    minutes = sec // 60 % 60
    hours = sec // (60 * 60)
    return str(hours) + ':' + str(minutes).zfill(2) + ':' + str(seconds).zfill(
        2)


def _firstvarmatch(string, prefix) ->bool:
    """See if first var is exactly prefix."""
    return string[1:1 + len(prefix)] == prefix


def convert_time(sec):
    """ Convert format of time from seconds to h min sec.

    :param sec: Number of seconds
    :type sec: int
    """
    hours = int(sec / 3600.0)
    minutes = int((sec - hours * 3600) / 60.0)
    seconds = sec - hours * 3600 - minutes * 60
    return hours, minutes, seconds


def scale_clear(clear_delta: bool=False):
    """Clear the object’s scale

    :param clear_delta: Clear Delta, Clear delta scale in addition to clearing the normal scale transform
    :type clear_delta: bool
    """
    pass


def batch(data, batch_size, batch_size_fn=None):
    """Yield elements from data in chunks of batch_size."""
    if batch_size_fn is None:

        def batch_size_fn(new, count, sofar):
            return count
    minibatch, size_so_far = [], 0
    for ex in data:
        minibatch.append(ex)
        size_so_far = batch_size_fn(ex, len(minibatch), size_so_far)
        if size_so_far == batch_size:
            yield minibatch
            minibatch, size_so_far = [], 0
        elif size_so_far > batch_size:
            yield minibatch[:-1]
            minibatch, size_so_far = minibatch[-1:], batch_size_fn(ex, 1, 0)
    if minibatch:
        yield minibatch


def read_html_for_injection(path):
    """ Open an HTML file at the given path and return the contents
    as a string.  If the file does not exist, we raise an exception.
    """
    with open(path) as file:
        return file.read()


def forward_selection(variables, train_model, score_model, verbose=True):
    """ Variable selection using forward selection

    Input:
        variables: complete list of variables to consider in model building
        train_model: function that returns a fitted model for a given set of variables
        score_model: function that returns the score of a model; better models have lower scores

    Returns:
        (best_model, best_variables)
    """
    best_variables = []
    best_model = train_model(best_variables)
    best_score = score_model(best_model, best_variables)
    if verbose:
        print('Variables: ' + ', '.join(variables))
        print('Start: score={:.2f}, constant'.format(best_score))
    while True:
        step = [(best_score, None, best_model)]
        for addVar in variables:
            if addVar in best_variables:
                continue
            step_var = list(best_variables)
            step_var.append(addVar)
            step_model = train_model(step_var)
            step_score = score_model(step_model, step_var)
            step.append((step_score, addVar, step_model))
        step.sort(key=lambda x: x[0])
        best_score, added_step, best_model = step[0]
        if verbose:
            print('Step: score={:.2f}, add {}'.format(best_score, added_step))
        if added_step is None:
            break
        best_variables.append(added_step)
    return best_model, best_variables


@staticmethod
def ldap_to_django_username(username):
    """convert ldap username to django username"""
    return username


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

    The storage type of ``elemwise_sub`` output depends on storage types of inputs

       - elemwise_sub(row_sparse, row_sparse) = row_sparse
       - elemwise_sub(csr, csr) = csr
       - elemwise_sub(default, csr) = default
       - elemwise_sub(csr, default) = default
       - elemwise_sub(default, rsp) = default
       - elemwise_sub(rsp, default) = default
       - otherwise, ``elemwise_sub`` generates output with default storage

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

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

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


def post_messages(base, queue_name, messages):
    """Utility function that posts message(s) to Zaqar queue."""
    res = base.messaging_client.post_messages(queue_name, {'messages':
        messages})
    if res['status'] != 201:
        msg = 'Failed in posting messages to Zaqar queue %s' % queue_name
        raise Exception(msg)


def find_end_of_continued_line(lines, start_line: int):
    """Find the last line of a line explicitly extended using backslashes.

    Uses 0-indexed line numbers.
    """
    end_line = start_line
    while lines[end_line].endswith('\\\n'):
        end_line += 1
        if end_line >= len(lines):
            break
    return end_line


@staticmethod
def _transform_session_persistence(persistence):
    """Transforms session persistence into an object that will

            be processed by the templating system
        """
    return {'type': persistence.type, 'persistence_timeout': persistence.
        persistence_timeout, 'persistence_granularity': persistence.
        persistence_granularity}


def validate_values(validation_func, dic):
    """
    Validate each value in ``dic`` by passing it through ``func``.
    Raise a ``ValueError`` if ``validation_func`` does not return ``True``.
    """
    for value_name, value in dic.items():
        if not validation_func(value):
            raise ValueError('{} can not be {}'.format(value_name, value))


def _node_parse_command_and_opt(**opts_dict):
    """Return 'command' and 'command_opt' from **opts_dict.

    Find which command has a non null attribute and returns it.

    >>> _node_parse_command_and_opt(firmware_path='/tmp/test',
    ...                             profile_name=None,
    ...                             profile_path=None,
    ...                             command='with_argument')
    ('flash', '/tmp/test')

    >>> _node_parse_command_and_opt(firmware_path=None,
    ...                             profile_name='consumption',
    ...                             profile_path=None,
    ...                             command='with_argument')
    ('profile', 'consumption')

    >>> _node_parse_command_and_opt(firmware_path=None,
    ...                             profile_name=None,
    ...                             profile_path='/tmp/prof.json',
    ...                             command='with_argument')
    ('profile-load', '/tmp/prof.json')

    # Case where the command is not managed
    >>> _node_parse_command_and_opt(firmware_path=None,
    ...                             profile_name=None,
    ...                             profile_path=None,
    ...                             command='with_argument')
    Traceback (most recent call last):
    ...
    ValueError: Unknown command
    """
    commands_arguments = {'flash': 'firmware_path', 'profile':
        'profile_name', 'profile-load': 'profile_path'}
    for command, argname in commands_arguments.items():
        cmd_opt = opts_dict.get(argname, None)
        if cmd_opt is not None:
            return command, cmd_opt
    raise ValueError('Unknown command')


@staticmethod
def write_gff(genome, output_file):
    """
        Writes a gff file for a Genome object

        Parameters
        ----------
        genome 			- Genome object
        output_file 	- string. file name to output results to.
        """
    with open(output_file, 'w') as out_io:
        for sequence in genome.ordered_sequences():
            contig_id = '_'.join(sequence.seqname.split('_')[:-1])
            features = ['seq_id=%s' % sequence.seqname, 'prodigal_id=%s' %
                sequence.prod_id, 'partial=%s' % sequence.partial,
                'start_type=%s' % sequence.starttype, 'rbs_motif=%s' %
                sequence.rbs_motif, 'rbs_spacer=%s' % sequence.rbs_spacer,
                'gc=%s' % sequence.gc]
            if len(sequence.all_annotations()) > 0:
                features.append('annotations=%s' % ','.join(sequence.
                    all_annotations()))
            else:
                features.append('annotations=hypothetical_protein')
            line = [contig_id, 'prodigal', 'CDS', sequence.startpos,
                sequence.finishpos, '.', '-' if sequence.direction == '-1' else
                '+', '0', ';'.join(features)]
            out_io.write('\t'.join(line) + '\n')


@classmethod
def _binary_search_intervals(cls, intervals, index):
    """
        Binary search for the interval containing index,
        assuming there is such an interval.
        This function should never return ``None``.
        """
    start = 0
    end = len(intervals) - 1
    while start <= end:
        middle_index = start + (end - start) // 2
        middle = intervals[middle_index]
        if middle[0] <= index and index < middle[1]:
            return middle
        elif middle[0] > index:
            end = middle_index - 1
        else:
            start = middle_index + 1
    return None


def nts(buffer):
    """
    Null Terminated String
    Get the portion of bytestring buffer up to a null character.
    """
    result, null, rest = buffer.partition('\x00')
    return result


def to_tornado_future(asyncio_future):
    """Convert an `asyncio.Future` to a `tornado.concurrent.Future`.

    .. versionadded:: 4.1

    .. deprecated:: 5.0
       Tornado ``Futures`` have been merged with `asyncio.Future`,
       so this method is now a no-op.
    """
    return asyncio_future


def active_index_set(mode: str='', index: int=0):
    """Set active sculpt/paint brush from it’s number

    :param mode: Mode, Paint mode to set brush for
    :type mode: str
    :param index: Number, Brush number
    :type index: int
    """
    pass


def _sign(number):
    """
    Get sign of the given number

    :param number:
    :type number: int

    :return: -1, 0, 1
    :rtype: int
    """
    if number > 0:
        return 1
    if number < 0:
        return -1
    return 0


def tsplit(string, delimiters):
    """Behaves str.split but supports tuples of delimiters."""
    delimiters = tuple(delimiters)
    if len(delimiters) < 1:
        return [string]
    final_delimiter = delimiters[0]
    for i in delimiters[1:]:
        string = string.replace(i, final_delimiter)
    return string.split(final_delimiter)


def p_declaration_1(t):
    """declaration : type_specifier ID"""
    t[1].id = t[2]
    t[0] = t[1]


def _is_descriptor(obj):
    """Returns True if obj is a descriptor, False otherwise."""
    return hasattr(obj, '__get__') or hasattr(obj, '__set__') or hasattr(obj,
        '__delete__')


@staticmethod
def value_format(data):
    """Returns a string"""
    info = data.get('format_name', None)
    return info, info or 'null'


def deactivate():
    """Reset the hasher function to the real CRC32 function."""
    global _old
    import memcache
    memcache.serverHashFunction, _old = _old, None


def _compute_tick_multiplier(interval: float) ->int:
    """
    The tick multiplier is the order of magnitude by which the ``interval`` has to
    be multiplied such that the interval is a number >= 1.

    The tick multiplier simplifies the math to determine the sub slot count
    when the ``Clock``'s tick interval is fractional. The idea is to scale the
    sub slot value such that we can just look at the integer part of this value.
    """
    multiplier = 0
    while interval < 1:
        multiplier += 1
        interval *= 10
    return 10 ** multiplier


@staticmethod
def flatten_dim(dim):
    """Given a `dim` for a single index that may be divided between
        sectors, return a flattened dim, that has just the total dimension of
        the index.
        """
    try:
        return sum(dim)
    except TypeError:
        return dim


def Pbar2dbar(Pbar):
    """Convert pressure from bar to dbar."""
    return Pbar * 10.0


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


def replace_line_block(lines, block, index_start, index_end):
    """Replace a block of lines between two line indices with a new set of lines.

    :param lines: list of lines representing the whole file
    :param block: list of lines representing the new block that should be inserted after old block is removed
    :param index_start: start of the block to be removed
    :param index_end: end of the block to be removed
    :return: list of lines with block of lines replaced
    """
    lines = lines[:index_start] + lines[index_end:]
    lines[index_start:index_start] = block
    return lines


def terminate(context, code, detail):
    """abort to serve this request and throw grpc error"""
    context.abort(code, detail)


def build_operation(id, path, args, command='set', table='block'):
    """
    Data updates sent to the submitTransaction endpoint consist of a sequence of "operations". This is a helper
    function that constructs one of these operations.
    """
    if isinstance(path, str):
        path = path.split('.')
    return {'id': id, 'path': path, 'args': args, 'command': command,
        'table': table}


def get_message_type_from_message(message: str) ->str:
    """Parses the message_type from the message."""
    return message.split(' ')[2].replace('\n', '')


def isoformat(dt):
    """Return iso-formatted timestamp

    Like .isoformat(), but uses Z for UTC instead of +00:00
    """
    return dt.isoformat().replace('+00:00', 'Z')


def get_ssl_certificate():
    """In case of SSL traffic, return SSL certifacte."""


def dec2bin(n, p=1):
    """Convert a decimal value ``n`` to an array of bits (MSB first).
    Optionally, pad the overall size to ``p`` bits."""
    assert n >= 0
    if type(n) is not int:
        n = int(n)
    retval = []
    while n > 0:
        retval.append(n & 1)
        n >>= 1
    if p > 0:
        retval.extend([0] * (p - len(retval)))
    retval.reverse()
    return retval


def directly_covered_by_adding_face(last_covered_intervals, face, q, f):
    """
    Computes incrementally new covered_intervals by adding a new face.
    Consider only directly covered and symmetry reflection regarding f.

    EXAMPLES::

        sage: from cutgeneratingfunctionology.igp import *
        sage: last_covered_intervals = [set([0,2]), set([3,4])]
        sage: face = (1, 1, 1)
        sage: directly_covered_by_adding_face(last_covered_intervals, face, 5, 3)
        [{0, 2}, {1, 3, 4}]
    """
    covered_intervals = []
    x, y, w = face
    z = (x + y + w) % q
    newly_covered = set([x, y, z, (f - x - 1) % q, (f - y - 1) % q, (f - z -
        1) % q])
    for component in last_covered_intervals:
        if component & newly_covered:
            newly_covered.update(component)
        else:
            covered_intervals.append(component)
    covered_intervals.append(newly_covered)
    return covered_intervals


def merge_parameter_lists(*parameter_definitions):
    """
    Merge multiple lists of parameters into a single list.  If there are any
    duplicate definitions, the last write wins.
    """
    merged_parameters = {}
    for parameter_list in parameter_definitions:
        for parameter in parameter_list:
            key = parameter['name'], parameter['in']
            merged_parameters[key] = parameter
    return merged_parameters.values()


def compute_embedding_size(n_categories):
    """
    Applies a standard formula to choose the number of feature embeddings
    to use in a given embedding layers.

    n_categories is the number of unique categories in a column.
    """
    val = min(600, round(1.6 * n_categories ** 0.56))
    return int(val)


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

        :param UserSelectorArg val:
        :rtype: UserAddResult
        """
    return cls('placeholder_user', val)


def pt2mm(value):
    """Converts given value in points to millimeters.

    Args:
        value (int): value in points.

    Returns:
        (float): value, in millimeters.
    """
    return value * 0.352777778


def discomfort_index(ta, rh):
    """Calculate discomfort index (DI) from air temperature and relative
    humidity.

    Discomfort Index is derived from original work carried out by Eral C. Thom
    [1] which defined discomfort index based on dry-bulb and wet-bulb
    temperature. It is the human-perceived increase in air temperature due to
    humidity increase.

    Note:
        [1]  Thom, E.C. (1959) "The Discomfort Index". Weatherwise, 12, 57-61.

    Args:
        ta: Air temperature [C]
        rh: Relative humidity  [%]

    Returns:
        di -- Discomfort index [C]
    """
    di = ta - (0.55 - 0.0055 * rh) * (ta - 14.5)
    return di


def filter_on_case_size(df, case_id_glue='case:concept:name', min_case_size
    =2, max_case_size=None):
    """
    Filter a dataframe keeping only traces with at least the specified number of events

    Parameters
    -----------
    df
        Dataframe
    case_id_glue
        Case ID column in the CSV
    min_case_size
        Minimum size of a case
    max_case_size
        Maximum case size

    Returns
    -----------
    df
        Filtered dataframe
    """
    element_group_size = df[case_id_glue].groupby(df[case_id_glue]).transform(
        'size')
    if max_case_size:
        return df[min_case_size <= element_group_size <= max_case_size]
    return df[element_group_size >= min_case_size]


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


def compute_polarisation_factors(args):
    """
    From Kabsch 1988 J. Appl. Cryst. 21 619

    DIVIDE the intensities by:
    <sin2 psi> = (1 - 2p) [ 1 - (n.S/|S|^2) ] + p { 1 + [S.S_0/(|S||S_0|)^2]^2}

    p = degree of polarisation (sync = 1, tube = 0.5 , mono + tube in between)
        or "probability of finding electric field vector in plane having
            normal, n"
    S = scattered vector
    S_0 = incident vector
    n = normal to polarisation plane, typically perpendicular to S_0

    In ImageD11 we normally expect to find:
    x axis along the beam
    z axis being up, and parallel to the normal n mentioned above
    """
    n = [0, 0, 1]


def gen_ordered_list(list_items):
    """Generates a numbered list.

    Args:
     list_items (list of strings): The items to be listed.

    Returns:
      The markdown formatted list.

    """
    md_str = ''
    for i, text in enumerate(list_items):
        md_str += '{}. {}\n'.format(i + 1, text)
    return md_str


@classmethod
def from_json(cls, _json, dataset, client_api):
    """
        Build a Recipe entity object from a json

        :param _json: _json response from host
        :param dataset: recipe's dataset
        :param client_api: client_api
        :return: Recipe object
        """
    return cls(client_api=client_api, dataset=dataset, id=_json['id'],
        creator=_json.get('creator', None), url=_json.get('url', None),
        title=_json.get('title', None), project_ids=_json.get('projectIds',
        None), description=_json.get('description', None), ontologyIds=
        _json.get('ontologyIds', None), instructions=_json.get(
        'instructions', None), ui_settings=_json.get('uiSettings', None),
        metadata=_json.get('metadata', None), examples=_json.get('examples',
        None), customActions=_json.get('customActions', None))


def zone_current_temperature(zone):
    """
    Get current temperature for this zone
    """
    return zone['currenttemperature']


def check_settings(settings, required):
    """Check that required simulation settings are actually given.

    This method will look for required settings in the given
    `settings`. If one or more keys from the given `required` list of
    strings are not found, this method will return False. Otherwise
    if will return True. Typically, and exception should be raised if
    False is returned, this is handled outside the method in case
    someone wants to add some magic handling of missing settings.

    Parameters
    ----------
    settings : dict
        This dict contains the given settings
    required : list of strings
        This list contains the settings that are required and which
        we will check the presence of.

    Returns
    -------
    result : boolean
        True if all required settings are present, False otherwise.
    not_found : list of strings
        There are the required settings we did not find.
    """
    result = True
    not_found = []
    for setting in required:
        if setting not in settings:
            result = False
            not_found.append(setting)
    return result, not_found


@staticmethod
def get_stats_from_ping_data(stats):
    """
        >>> data = ['statistics', '---\\n5', 'packets', 'transmitted,', '5']
        >>> data += ['received,', '0%', 'packet', 'loss,', 'time', '4001ms\\nrtt']
        >>> data += ['min/avg/max/mdev','=', '79.832/86.519/88.649/3.367', 'ms']
        >>> Pinger.get_stats_from_ping_data(data)
        [79.832, 86.519, 88.649, 3.367, 5.0]

        Return stats from ping output data.
        :param stats:
        :return:
        """
    out = []
    for i, x in enumerate(reversed(stats[:])):
        data = str(x).split('/')
        for d in data:
            try:
                out.append(float(d))
            except ValueError:
                continue
    return out


@classmethod
def name_joiner(cls, *names: str) ->str:
    """
        Join words to form a model name. Uses in different places so override WORDS_SEPARATOR to change it globally.
        """
    return cls.WORDS_SEPARATOR.join(names)


def gpib_control_atn(library, session, mode):
    """Specifies the state of the ATN line and the local active controller state.

    Corresponds to viGpibControlATN function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param mode: Specifies the state of the ATN line and optionally the local active controller state.
                 (Constants.GPIB_ATN*)
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viGpibControlATN(session, mode)


def erange(start, step, end=None):
    """ Returns the range with both ends includede """
    if end is None:
        return range(start, step + 1)
    return range(start, end + 1, step)


def get_body_world_transform(robot, body_name, use_theoretical_model=True):
    """
    @brief Get the transform from world frame to body frame for a given body.

    @details It is assumed that update_quantities has been called.

    @param  robot           The jiminy robot
    @param  body_name       The name of the body
    @return transform       Object representing the transform

    @pre body_name must be the name of a body existing in model.
    """
    if use_theoretical_model:
        pnc_model = robot.pinocchio_model_th
        pnc_data = robot.pinocchio_data_th
    else:
        pnc_model = robot.pinocchio_model
        pnc_data = robot.pinocchio_data
    return pnc_data.oMf[pnc_model.getFrameId(body_name)]


def clear():
    """ Clear all values from the dictionary """


def join_tracks():
    """Join selected tracks

    """
    pass


def p_language_block(t):
    """language_block : LANGUAGE NUMBER START_BLOCK cd_text_items END_BLOCK"""
    from audiotools.toc import CDTextLanguage
    t[0] = CDTextLanguage(language_id=t[2], text_pairs=t[4])


def gradients(loss, variables):
    """Returns the gradients of `variables` w.r.t. `loss`.

    # Arguments
        loss: Scalar tensor to minimize.
        variables: List of variables.

    # Returns
        A gradients tensor.
    """
    raise NotImplementedError(
        'MXNet Backend: Gradients operator is not supported yet.')


def OGLCleanUp():
    """not implemented???"""
    pass


def transpose_axes(data, axes, asaxes='CTZYX'):
    """Return data with its axes permuted to match specified axes.

    A view is returned if possible.

    >>> transpose_axes(numpy.zeros((2, 3, 4, 5)), 'TYXC', asaxes='CTZYX').shape
    (5, 2, 1, 3, 4)

    """
    for ax in axes:
        if ax not in asaxes:
            raise ValueError('unknown axis %s' % ax)
    shape = data.shape
    for ax in reversed(asaxes):
        if ax not in axes:
            axes = ax + axes
            shape = (1,) + shape
    data = data.reshape(shape)
    data = data.transpose([axes.index(ax) for ax in asaxes])
    return data


def format_signed(feature, formatter=None, **kwargs):
    """
    Format unhashed feature with sign.

    >>> format_signed({'name': 'foo', 'sign': 1})
    'foo'
    >>> format_signed({'name': 'foo', 'sign': -1})
    '(-)foo'
    >>> format_signed({'name': ' foo', 'sign': -1}, lambda x: '"{}"'.format(x))
    '(-)" foo"'
    """
    txt = '' if feature['sign'] > 0 else '(-)'
    name = feature['name']
    if formatter is not None:
        name = formatter(name, **kwargs)
    return '{}{}'.format(txt, name)


def enableFaulthandler():
    """ Enable faulthandler for all threads.

    If the faulthandler package is available, this function disables and then
    re-enables fault handling for all threads (this is necessary to ensure any
    new threads are handled correctly), and returns True.

    If faulthandler is not available, then returns False.
    """
    try:
        import faulthandler
        faulthandler.disable()
        faulthandler.enable(all_threads=True)
        return True
    except ImportError:
        return False


def get(isdsAppliance, check_mode=False, force=False):
    """
    Get current configured server type
    """
    return isdsAppliance.invoke_get('Retrieving Server Type',
        '/servertype_object')


@classmethod
def set_cursor(cls, widget, cursor_name='parent'):
    """ Set the cursor named cursor_name'.

        Args:
            widget (:class:`~Gtk.Widget`): The widget triggering the cursor change, used to retrieve a Gdk.Window
            cursor_name (`str`): Name of the cursor to be set
        """
    try:
        cursor = cls._cursors[cursor_name]
    except KeyError:
        cls._populate_cursors()
        cursor = cls._cursors[cursor_name]
    widget.get_window().set_cursor(cursor)


@staticmethod
def check(*args, **kwargs):
    """ it's not a real modeladmin, so we need this attribute in DEBUG. """
    return ()


def name_for(*keys):
    """
    Concatenate a metric name.

    """
    return '.'.join(keys)


def _passthrough_scorer(estimator, *args, **kwargs):
    """Function that wraps estimator.score"""
    return estimator.score(*args, **kwargs)


def top_n_peaks(spectrum, N):
    """
    Takes the most-intense N peaks of the given scan, and discards the rest.
    """
    N = int(N) if N else 0
    return sorted(spectrum, key=lambda x: x[1], reverse=True)[:int(N)]


def reset_globals():
    """For async unit test consistency."""
    global _SERVICE_AUTH
    _SERVICE_AUTH = None


def zsum(s, *args, **kwargs):
    """
    pandas 0.21.0 changes sum() behavior so that the result of applying sum
    over an empty DataFrame is NaN.

    Meant to be set as pd.Series.zsum = zsum.
    """
    return 0 if s.empty else s.sum(*args, **kwargs)


def create_resource(restApiId=None, parentId=None, pathPart=None):
    """
    Creates a  Resource resource.
    See also: AWS API Documentation

    :example: response = client.create_resource(
        restApiId='string',
        parentId='string',
        pathPart='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The identifier of the RestApi for the resource.

    :type parentId: string
    :param parentId: [REQUIRED]
            The parent resource's identifier.

    :type pathPart: string
    :param pathPart: [REQUIRED]
            The last path segment for this resource.

    :rtype: dict
    :return: {
        'id': 'string',
        'parentId': 'string',
        'pathPart': 'string',
        'path': 'string',
        'resourceMethods': {
            'string': {
                'httpMethod': 'string',
                'authorizationType': 'string',
                'authorizerId': 'string',
                'apiKeyRequired': True|False,
                'requestValidatorId': 'string',
                'operationName': 'string',
                'requestParameters': {
                    'string': True|False
                },
                'requestModels': {
                    'string': 'string'
                },
                'methodResponses': {
                    'string': {
                        'statusCode': 'string',
                        'responseParameters': {
                            'string': True|False
                        },
                        'responseModels': {
                            'string': 'string'
                        }
                    }
                },
                'methodIntegration': {
                    'type': 'HTTP'|'AWS'|'MOCK'|'HTTP_PROXY'|'AWS_PROXY',
                    'httpMethod': 'string',
                    'uri': 'string',
                    'credentials': 'string',
                    'requestParameters': {
                        'string': 'string'
                    },
                    'requestTemplates': {
                        'string': 'string'
                    },
                    'passthroughBehavior': 'string',
                    'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT',
                    'cacheNamespace': 'string',
                    'cacheKeyParameters': [
                        'string',
                    ],
                    'integrationResponses': {
                        'string': {
                            'statusCode': 'string',
                            'selectionPattern': 'string',
                            'responseParameters': {
                                'string': 'string'
                            },
                            'responseTemplates': {
                                'string': 'string'
                            },
                            'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT'
                        }
                    }
                }
            }
        }
    }

    :returns:
    (string) --
    (boolean) --

    """
    pass


def _is_unique_msg(dialect, msg):
    """
        easier unit testing this way
    """
    if dialect == 'postgresql':
        if 'duplicate key value violates unique constraint' in msg:
            return True
    elif dialect == 'mssql':
        if 'Cannot insert duplicate key' in msg:
            return True
    elif dialect == 'sqlite':
        if ('is not unique' in msg or 'are not unique' in msg or
            'UNIQUE constraint failed' in msg):
            return True
    else:
        raise ValueError('is_unique_exc() does not yet support dialect: %s' %
            dialect)
    return False


def text_cut():
    """Cut selected text to clipboard

    """
    pass


def soundclip_add():
    """Add a strip for controlling when speaker plays its sound clip

    """
    pass


def view_frame():
    """Reset viewable area to show range around current frame

    """
    pass


def set_org_processor(request):
    """
    Simple context processor that automatically sets 'org' on the context if it
    is present in the request.
    """
    if getattr(request, 'org', None):
        org = request.org
        pattern_bg = org.backgrounds.filter(is_active=True, background_type='P'
            )
        pattern_bg = pattern_bg.order_by('-pk').first()
        banner_bg = org.backgrounds.filter(is_active=True, background_type='B')
        banner_bg = banner_bg.order_by('-pk').first()
        return dict(org=org, pattern_bg=pattern_bg, banner_bg=banner_bg)
    else:
        return dict()


def check_comp(comp=None):
    """
    Checks if the given competition url is properly formatted
    """
    if comp == None:
        return None
    if comp.endswith('/'):
        comp = comp[:-1]
    if comp.startswith('/'):
        pass
    else:
        comp = '/' + comp
    return comp


def _iso8601(dt):
    """Turn a datetime object into an ISO8601 formatted date.

    Example::

        fields._iso8601(datetime(2012, 1, 1, 0, 0)) => "2012-01-01T00:00:00"

    :param dt: The datetime to transform
    :type dt: datetime
    :return: A ISO 8601 formatted date string
    """
    return dt.isoformat()


def init():
    """Initialize strategy module."""
    pass


def validate(command, args):
    """
        Validates arguments of the wrapped command before its execution.

        The interceptor can use this method to intercept and alter validation of the command arguments.
        Otherwise it shall just delegate the call to the wrapped command.

        :param command: intercepted ICommand

        :param args: command arguments

        :return: a list of validation results.
        """
    raise NotImplementedError('Method from interface definition')


@classmethod
def convert_to_xml(cls, value):
    """
        Keep alpha hex numerals all uppercase just for consistency.
        """
    return '%02X%02X%02X' % value


@classmethod
def parse_term_vectors(cls, lst, path=''):
    """Transform a solr list to dict

        Turns [a, x, b, y, c, z ...] into {a: x, b: y, c: z ...}
        If the values are lists themselves, this is done recursively
        """
    dct = dict()
    for i in range(0, len(lst), 2):
        k = lst[i]
        v = lst[i + 1]
        if path != '.warnings' and isinstance(v, list):
            v = cls.parse_term_vectors(v, path + '.' + k)
        dct[k] = v
    return dct


def linexand(listoflists, columnlist, valuelist):
    """
Returns the rows of a list of lists where col (from columnlist) = val
(from valuelist) for EVERY pair of values (columnlist[i],valuelists[i]).
len(columnlist) must equal len(valuelist).

Usage:   linexand (listoflists,columnlist,valuelist)
Returns: the rows of listoflists where columnlist[i]=valuelist[i] for ALL i
"""
    if type(columnlist) not in [list, tuple]:
        columnlist = [columnlist]
    if type(valuelist) not in [list, tuple]:
        valuelist = [valuelist]
    criterion = ''
    for i in range(len(columnlist)):
        if isinstance(valuelist[i], str):
            critval = "'" + valuelist[i] + "'"
        else:
            critval = str(valuelist[i])
        criterion = criterion + ' x[' + str(columnlist[i]
            ) + ']==' + critval + ' and'
    criterion = criterion[0:-3]
    function = 'filter(lambda x: ' + criterion + ',listoflists)'
    lines = eval(function)
    return lines


def InputPort(dynamic, name, environment, queueSizeSamples=1,
    queueSizeSeconds=None):
    """
    Creates an InputPortInterface instance with an actual implementation attached. Will be dynamically implemented by
    the nexxT framework. This is done to prevent having implementation details in the class

    Note: import this function with 'from next.interface import InputPort'.

    :param dynamic: boolean whether this is a dynamic input port
    :param name: the name of the port
    :param environment: the FilterEnvironment instance
    :param queueSizeSamples: the size of the queue in samples
    :param queueSizeSeconds: the size of the queue in seconds
    :return: an InputPort instance (actually an InputPortImpl instance)
    """
    raise NotImplementedError()


def project_opened(project):
    """This function is called after opening the project"""


def constraints_copy():
    """Copy constraints to other selected objects

    """
    pass


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

        :param AllowDownloadDisabledType val:
        :rtype: EventType
        """
    return cls('allow_download_disabled', val)


@classmethod
def get_attrs_processor_param(cls):
    """ Get param for attrs processor.

    :return: Dict.
    """
    return {}


def newdims(img=None, resize=1, dims=None):
    """Returns new dimensions of an image array based on resize value"""
    if dims is None:
        if img is None:
            print('No img or dims provided..')
            return
        else:
            dims = img.shape[1], img.shape[0]
    width = int(dims[0] * resize)
    height = int(dims[1] * resize)
    return width, height


def _one_weight(n_one, n_zero, a, alpha):
    """Get the weight of the ones."""
    weight = a * (n_one / n_zero) ** -alpha
    return weight


def encode_byte(value):
    """Encode a byte type."""
    return bytearray([value])


def kind(o):
    """
    returns a suitable table name for an object based on the object class
    """
    n = []
    for c in o.__class__.__name__:
        if c.isalpha() or c == '_':
            if c.isupper() and len(n):
                n.append('_')
            n.append(c.lower())
    return ''.join(n)


def compare(original, tested=''):
    """Compare two lines together, paying attention to the different
    possibilities to end lines.

    >>> compare(None)
    False
    >>> compare('\\n')
    True
    >>> compare('\\r\\n')
    True
    >>> compare('foo\\r\\n')
    False
    >>> compare(None, 'foo')
    False
    >>> compare('foo', 'bar')
    False
    >>> compare('foo', 'foo')
    False
    >>> compare('foo\\n', 'foo')
    True
    >>> compare('foo\\r\\n', 'foo')
    True
    >>> compare('foo\\t\\n', 'foo')
    False
    """
    if original and original.startswith(tested):
        if original[len(tested):] in ('', '\r', '\n', '\r\n'):
            return True
    return False


def dissolve_degenerate(threshold: float=0.0001):
    """Dissolve zero area faces and zero length edges

    :param threshold: Merge Distance, Minimum distance between elements to merge
    :type threshold: float
    """
    pass


def error_proba(phred):
    """
    Compute error proba from phred score

    params: phred int()
    return: proba double()
    """
    return 10 ** (-phred / 10)


def write_bed_file(bed_default_dict, output_file):
    """Write default dict to a bed file
    :param bed_default_dict: default dict created from aggregate_methylbeds
    :param output_file: path to output file
    """
    with open(output_file, 'w') as fh:
        for chromosome, strand_dict in bed_default_dict.items():
            for strand, start_dict in strand_dict.items():
                for start, coverage_list in start_dict.items():
                    coverage_total = 0
                    percentage_total = 0
                    max_percentage = 0
                    for x in coverage_list:
                        coverage_total += x[1]
                        percentage_total += x[1] * x[2]
                        max_percentage += x[1] * 100
                    color = x[0]
                    if max_percentage != 0:
                        percentage = int(percentage_total / max_percentage *
                            100)
                        print('\t'.join([chromosome, start, str(int(start) +
                            1), '.', str(coverage_total), strand, start,
                            str(int(start) + 1), color, str(coverage_total),
                            str(percentage)]), file=fh)


def p_break_stmt(p):
    """break_stmt : BREAK"""
    p[0] = ['BREAK']


def run_many(cursor, stmt, items):
    """Execute a statement repeatedly.  Items should be a list of tuples.

        stmt should use '%s' parameter format (not %(name)s).
        """


def name2pin(name: str) ->int:
    """Convert pin name to number"""
    if not isinstance(name, str):
        raise TypeError('name must be a string')
    if len(name) < 3:
        raise ValueError('invalid name format')
    name = name.upper()
    if name[0] != 'P':
        raise ValueError('invalid name format')
    ports = 'ABCDEFGHIJKL'
    port_idx = ports.find(name[1])
    if port_idx < 0:
        raise ValueError('port name out of range')
    return int(port_idx * 32 + int(name[2:]))


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

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

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


def get_i(i, d_vals):
    """
    if (x, y) return y if x == i
    if y return y
    """
    ds = []
    for j in d_vals:
        if type(j) == tuple and j[0] == i:
            ds.append(j[1])
        elif type(j) != tuple:
            ds.append(j)
    return ds


def _data_path_to(data_dir_path, builtin_assets, asset_filename):
    """
    The path to a builtin asset in the ./data folder on this machine.

    Parameters
    ----------
    asset_filename : `str`
        The filename (with extension) of a file builtin to Menpo. The full
        set of allowed names is given by :func:`ls_builtin_assets()`

    Returns
    -------
    data_path : `pathlib.Path`
        The path to a given asset in the ./data folder

    Raises
    ------
    ValueError
        If the asset_filename doesn't exist in the `data` folder.
    """
    asset_path = data_dir_path() / asset_filename
    if not asset_path.is_file():
        raise ValueError('{} is not a builtin asset: {}'.format(
            asset_filename, builtin_assets()))
    return asset_path


def walk_links_for_node(node, callback, direction, obj=None):
    """
    Walks the each link from the given node. Raising a StopIteration will terminate the
    traversal.

    :type node: treestruct.Node
    :type callback: (treestruct.Node, treestruct.Node, object) -> ()
    :type direction: int
    :type obj: Any
    :return: Returns `obj` (or None if no `obj` is supplied).
    :rtype: Any
    """
    try:
        visited = set()
        queue = [node]
        while queue:
            node = queue.pop(0)
            if node in visited:
                continue
            visited.add(node)
            for connected_node in node.direction(direction):
                callback(node, connected_node, obj)
                queue.append(connected_node)
    except StopIteration:
        pass
    return obj


def _tzoffset2iso8601zone(seconds):
    """Takes an offset, such as from _tzoffset(), and returns an ISO 8601
       compliant zone specification. Please note that the result of
       _tzoffset() is the negative of what time.localzone and time.altzone is.
    """
    return '%+03d:%02d' % divmod(seconds // 60, 60)


@classmethod
def is_binary_payload(cls) ->bool:
    """True if payload is not JSON."""
    return True


def get_data_format_and_size(data, data_type):
    """
    Internal function to convert data_type to the corresponding struct.pack format string
    as per https://docs.python.org/2/library/struct.html#format-characters

    Function contributed by awm102 on GitHub.  Amy moved this to DroneSensorParser to be
    more general, edited a bit to fit within the drone sensor parser as well.

    :param data: the data that will be packed. Not actually used here unless the data_type is string, then
                 it is used to calculate the data size.
    :param data_type: a string representing the data type
    :return: a tuple of a string representing the struct.pack format for the data type and an int representing
             the number of bytes
    """
    if data_type == 'u8' or data_type == 'enum':
        format_char = '<B'
        data_size = 1
    elif data_type == 'i8':
        format_char = '<b'
        data_size = 1
    elif data_type == 'u16':
        format_char = '<H'
        data_size = 2
    elif data_type == 'i16':
        format_char = '<h'
        data_size = 2
    elif data_type == 'u32':
        format_char = '<I'
        data_size = 4
    elif data_type == 'i32':
        format_char = '<i'
        data_size = 4
    elif data_type == 'u64':
        format_char = '<Q'
        data_size = 8
    elif data_type == 'i64':
        format_char = '<q'
        data_size = 8
    elif data_type == 'float':
        format_char = '<f'
        data_size = 4
    elif data_type == 'double':
        format_char = '<d'
        data_size = 8
    elif data_type == 'string':
        format_char = '<s'
        data_size = len(data)
    else:
        format_char = ''
        data_size = 0
    return format_char, data_size


def R0(h, k, L, A):
    """ Resistance between ambient and first node // applies to end node as well

	Parameters
	----------
	h : float or (m,) np.array
		covection resistance [W/(m2K)]

	k : float or (m,) np.array
		material thermal conductivity [W/(mK)]

	L : float or (m,) np.array
		thickness of the sample [m]

	A : float or (m,) np.array
		sample area perpendicular to the direction of heat transfer [m2]

	Returns
	-------
	R : float or (m,) np.array
		heat transfer resistance [K/W]

	Example use
	-----------
	>>> XXX
	"""
    return L / (2 * k * A) + 1 / (h * A)


def multiplyList(items):
    """
	Returns the ordered product of the given items.
	"""
    f = items[0]
    for g in items[1:]:
        f = f * g
    return f


@classmethod
def from_server_socket(cls, server, **kwargs):
    """Return a session for the next connection to the given socket."""
    client, _ = server.accept()
    return cls(client, ownsock=True, **kwargs)


@classmethod
def register_default_value_parsers(cls, config):
    """
         This method will register available parsers the parses value of frontmatter to callables.
        """
    for key, _callable in cls.default_value_parsers_map().items():
        config.register_frontmatter_value_parser(key, _callable)


@staticmethod
def detach_all(lun):
    """Detaches a `UnityLun` from all hosts.

        :param lun: `UnityLun` object
        """
    lun.update()
    lun.detach_from(host=None)


def parse_expansion(expansion_div) ->str:
    """Parse the expansion name"""
    second_a = expansion_div.findAll('a')[1].text
    return second_a


def first_leaf(nested_dict):
    """
    On the assumption that all the leaves of a nested dictionary (tree) structure are in some way equivalent,
    this is a quick method of returning the first such leaf without knowing the specific keys used
    to construct the nested dict.
    """
    partial_dict = nested_dict
    while True:
        try:
            partial_dict = partial_dict[list(partial_dict.keys())[0]]
        except AttributeError:
            try:
                partial_dict = list(partial_dict)
            except TypeError:
                return partial_dict
            else:
                partial_dict = partial_dict[0]


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 __index(*inputs):
    """build an index iterator for the given inputs"""
    NJOBS = len(inputs[0])
    return iter(range(NJOBS))


def reveal(select: bool=True):
    """Reveal all bones hidden in Edit Mode

    :param select: Select
    :type select: bool
    """
    pass


def verifyMIC(ctx, message, token, return_bool=False):
    """
    Verifies a Message's MIC

    This method verifies that the message matches the given message integrity
    code (token).

    .. note::

       This method does not throw an error on GSS_S_DUPLICATE_TOKEN,
       which simply indicates that the token was valid and contained
       the correct MIC for the message, but had already be processed.
       Instead, it simply returns that the MIC was valid, since this
       is not really an error.

    :param ctx: the current security context
    :param bytes message: the message in question
    :param bytes token: the MIC token for the message in question
    :param bool return_bool: see return value explanation
    :returns: this depends on the value of return_bool.
              If False, the QoP used to generate the MIC is returned
              if the verification is successfull, and and error is raised
              otherwise.  If True, a tuple is returned containing whether
              or not the MIC was valid, the QoP used, the major result code,
              and the minor result code (which can be interpreted with
              :func:`gssapi.base.status_utils.displayStatus`)
    :rtype: int or (bool, int, int, int)
    :except GSSError: if there is an error and return_bool
                      is set to False
    """


def get_upload_playlist_id(channel_id):
    """Given a channel_id, returns the user uploaded playlist id."""
    playlist_id = 'UU' + channel_id[2:]
    return playlist_id


def refresh():
    """Refresh object from file on disk (reload)."""


@staticmethod
def _sanityCheckProtocolVersions(other):
    """Check if set protocol version are sane"""
    if other.minVersion > other.maxVersion:
        raise ValueError('Versions set incorrectly')
    if other.minVersion not in ((3, 0), (3, 1), (3, 2), (3, 3)):
        raise ValueError('minVersion set incorrectly')
    if other.maxVersion not in ((3, 0), (3, 1), (3, 2), (3, 3)):
        raise ValueError('maxVersion set incorrectly')


def mult3(v, d):
    """Multiplies a 3D vector to a scalar"""
    return [v[0] * d, v[1] * d, v[2] * d]


@staticmethod
def _decrease_pool_count(pool_list, pool, count=1):
    """Decrement pool's size by count.

        If pool becomes empty, remove pool from pool_list.
        """
    if pool['count'] > count:
        pool['count'] -= count
        count = 0
    else:
        count -= pool['count']
        pool_list.remove(pool)
    return count


@classmethod
def enable_unaudited_hdwallet_features(cls):
    """
        Use this flag to enable unaudited HD Wallet features.
        """
    cls._use_unaudited_hdwallet_features = True


def _evaluate_gear_box_torque_in(min_engine_on_speed, gear_box_torque,
    gear_box_speed_in, gear_box_speed_out, gear_box_efficiency_parameters):
    """
    Calculates torque required according to the temperature profile [N*m].
    """
    tgb, es, ws = gear_box_torque, gear_box_speed_in, gear_box_speed_out
    par = gear_box_efficiency_parameters
    if tgb < 0 < es and ws > 0:
        return (par['gbp01'] * tgb - par['gbp10'] * ws - par['gbp00']
            ) * ws / es
    elif es > min_engine_on_speed and ws > min_engine_on_speed:
        return (tgb - par['gbp10'] * es - par['gbp00']) / par['gbp01']
    return 0


@classmethod
def set_lock(cls, lock):
    """Set the global lock."""
    cls._lock = lock


def release_data(key, state, delete=True):
    """ Remove data from temporary storage

    See Also
        finish_task
    """
    if key in state['waiting_data']:
        assert not state['waiting_data'][key]
        del state['waiting_data'][key]
    state['released'].add(key)
    if delete:
        del state['cache'][key]


def check_win(board, player1, player2):
    """
	returns status of current board: 1-> won, 2-> draw, 0-> game undecided
	if game won, return value is [1,who_won]
	"""
    returned_val = ['', '']
    if board[0] == board[1] == board[2] and board[0] in [player1, player2]:
        returned_val = [1, board[0]]
    elif board[3] == board[4] == board[5] and board[3] in [player1, player2]:
        returned_val = [1, board[3]]
    elif board[6] == board[7] == board[8] and board[6] in [player1, player2]:
        returned_val = [1, board[6]]
    elif board[0] == board[3] == board[6] and board[0] in [player1, player2]:
        returned_val = [1, board[0]]
    elif board[1] == board[4] == board[7] and board[1] in [player1, player2]:
        returned_val = [1, board[1]]
    elif board[2] == board[5] == board[8] and board[2] in [player1, player2]:
        returned_val = [1, board[2]]
    elif board[0] == board[4] == board[8] and board[0] in [player1, player2]:
        returned_val = [1, board[0]]
    elif board[2] == board[4] == board[6] and board[2] in [player1, player2]:
        returned_val = [1, board[2]]
    elif '-' in board:
        returned_val = [0, board[0]]
    else:
        returned_val = [2, board[0]]
    return returned_val


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


def mask_headers(headers, masks):
    """
    filters any headers (a dictionary) with key that matches those in the
    masks (a list)
    This have a sideeffect, so please make a deepcopy before using.
    """
    if headers is None:
        return headers
    if masks is None:
        return headers
    for member in masks:
        headers.pop(member, None)
    return headers


def get_bytes_for_unpacked_spike_vector(slices):
    """Compute the number of bytes necessary to store the unpacked spike vector
    for the given ranges of neurons.
    """
    words = 0
    for neurons in slices:
        n_neurons = neurons.stop - neurons.start
        words += n_neurons // 32
        words += 1 if n_neurons % 32 else 0
    return words * 4


def fractional_slice(first, last, skip, n):
    """
    Return a slice assuming `first` or `last` are fractions of `n`,
    the length of the iterable, if `first` or `last` are in (0,1)
    """
    if first is not None:
        if first > 0 and first < 1:
            first = int(first * n)
        else:
            first = int(first)
    if last is not None:
        if last > 0 and last < 1:
            last = int(last * n)
        else:
            last = int(last)
    return slice(first, last, skip)


def read_phonopy_dat_file(filename):
    """
    read .dat file from phonopy
    for reading yaml see self.read_phonopy_data()
    should be probably combined

    freq - frequency in THz
    tot - total energy for freq
    """
    dos = {'tot': [], 'freq': []}
    with open(filename, 'r') as f:
        f.readline()
        for line in f:
            val = line.split()
            dos['freq'].append(float(val[0]))
            dos['tot'].append(float(val[1]))
    return dos


def stop(ctx):
    """Stops PostgreSQL."""
    ctx.sudo('service postgresql stop')


def i2le_padded(number: int, length: int) ->bytes:
    """
    Convert int to little endian (LE) bytes with specified length

    Args:
        number: int value to convert to LE bytes
        length: length of resulting bytes
    Returns:
        LE-encoded number with fixed length
    """
    return number.to_bytes(length, 'little')