def generate_config(platforms, browsers_settings):
    """
    Generation config for parametrize tests by platforms, browsers and screen resolutions.

    :param platforms: Dict with platforms settings.
    :param browsers_settings: Browsers for each platform.
    :returns: Generator for list of dictionaries.
    """
    configs = []
    for base, params in browsers_settings.items():
        browsers, resolutions = params
        for browser in browsers:
            new_config = platforms[base].copy()
            new_config.update(browser)
            if resolutions:
                for resolution in resolutions:
                    new_config = new_config.copy()
                    new_config['resolution'] = '%sx%s' % resolution
                    configs.append(new_config)
            else:
                configs.append(new_config)
    return configs


@classmethod
def get_or_create(cls, keystore_dir):
    """Gets or creates the AccountUtils object so it loads lazily."""
    if cls.singleton is None or cls.singleton.keystore_dir != keystore_dir:
        cls.singleton = cls(keystore_dir=keystore_dir)
    return cls.singleton


def classify(text):
    """
    Return str indicating sentiment of given text representing
    Black Speech/Orkish.
    """
    return 'neg'


def get_charge_event_id(charge, charge_item=None):
    """
    Returns a formatted id for a charge (or a charge_item
    on that charge) that can be used as `event_id` in a `Transaction`.
    """
    substr = 'cha_%d/' % charge.id
    if charge_item:
        substr += '%d/' % charge_item.id
    return substr


@staticmethod
def source_to_code(data, path='<string>'):
    """Compile 'data' into a code object.

        The 'data' argument can be anything that compile() can handle. The'path'
        argument should be where the data was retrieved (when applicable)."""
    return compile(data, path, 'exec', dont_inherit=True)


def immediate(function):
    """    Function decorator used to tag Forth methods that will be executed
    immediately even when in compile mode.
    """
    function.forth_immediate = True
    return function


def CompareBigEndian(c1, c2):
    """
    Loosely matches CompareBigEndian() from eccryptoverify.cpp
    Compares two arrays of bytes, and returns a negative value if the first is
    less than the second, 0 if they're equal, and a positive value if the
    first is greater than the second.
    """
    c1 = list(c1)
    c2 = list(c2)
    while len(c1) > len(c2):
        if c1.pop(0) > 0:
            return 1
    while len(c2) > len(c1):
        if c2.pop(0) > 0:
            return -1
    while len(c1) > 0:
        diff = c1.pop(0) - c2.pop(0)
        if diff != 0:
            return diff
    return 0


def is_webcolor(name):
    """
    Checks if ``name`` is a valid web color

    :param name: the color value
    :type name:  ``str``

    :return: True if name is a valid web color
    :rtype:  ``bool``
    """
    if name[0] != '#' or len(name) != 7:
        return False
    try:
        red = int(name[1:3], 16)
        green = int(name[3:5], 16)
        blue = int(name[5:7], 16)
        return True
    except:
        pass
    return False


def _fill_missing_dims(dims_ntraces, ntraces, dim_names, dim_lens):
    """Make a new dimension (if necessary) for unaccounted traces."""
    if dims_ntraces < ntraces:
        dim_names.insert(0, 'Traces')
        dim_lens.insert(0, int(ntraces / dims_ntraces))


def b2mb(num):
    """ convert Bs to MBs and round down """
    return int(num / 2 ** 20)


def identity(chip):
    """Determine the identity of a chip.

    Args:
        chip (dict): A chip

    Returns:
        tuple: Tuple of the chip identity field
    """
    return tuple([chip['x'], chip['y'], chip['ubid'], chip['acquired']])


def get_response_error(response):
    """
    Transform a Response object into a friendlier string.

    Args:
        response (requests.Response): A Requests reponse object to parse for
                                      some kind of error.
    Returns:
        str: A string representation of the URL response.
    """
    return '{} {}: {}'.format(response.status_code, response.reason,
        response.text)


def color_to_plane_bits(color, depth):
    """returns the bits for a given pixel in a list, lowest to highest plane"""
    result = [0] * depth
    for bit in range(depth):
        if color & 1 << bit != 0:
            result[bit] = 1
    return result


def word_nucleus(word):
    """
    Find the nucleus for a word in Pinyin.

    The basic rule for finding the nucleus of a word in Pinyin is that if
    the word contains A / E / OU, then we know the answer automatically.
    If none of those are present, then just find the last vowel. This
    function returns the nucleus character.

    """
    if 'a' in word:
        return 'a'
    elif 'A' in word:
        return 'A'
    elif 'e' in word:
        return 'e'
    elif 'E' in word:
        return 'E'
    elif 'ou' in word or 'oU' in word:
        return 'o'
    elif 'OU' in word or 'Ou' in word:
        return 'O'
    for i in range(len(word) - 1, -1, -1):
        if word[i] in 'aeiouüvAEIOUÜV':
            return word[i]
    return None


@classmethod
def user_exists(cls, *args, **kwargs):
    """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        """
    if 'username' in kwargs:
        kwargs[cls.username_field()] = kwargs.pop('username')
    return cls.user_model().objects.filter(*args, **kwargs).count() > 0


def code_object(fn):
    """Get the code object from a function."""
    try:
        return fn.func_code
    except AttributeError:
        return fn.__code__


def evalt(t):
    """ Evaluate tuple if unevaluated

    >>> from kanren.util import evalt
    >>> add = lambda x, y: x + y
    >>> evalt((add, 2, 3))
    5
    >>> evalt(add(2, 3))
    5
    """
    if isinstance(t, tuple) and len(t) >= 1 and callable(t[0]):
        return t[0](*t[1:])
    else:
        return t


def get_row_prim(me, rid):
    """get_row_prim with transparent index mapping."""
    rid = me._rowmap.map(rid)
    if rid:
        return me._get_row_prim(rid)


def contfrac_rat(n, d):
    """
    Returns the simple continued fraction of the rational number n/d.
    Note the similarity to Euclid's algorithm.
    Input:
        num -- integer
        den -- positive integer coprime to num
    Output: sequence of integers
    Examples:
    >>> list(contfrac_rat(3, 2))
    [1, 2]
    >>> list(contfrac_rat(103993, 33102))
    [3, 7, 15, 1, 292]
    >>> list(contfrac_rat(*list(convergents((1,2,2,2,2,2,2,2,2,2)))[-1]))
    [1, 2, 2, 2, 2, 2, 2, 2, 2, 2]
    >>> list(convergents(contfrac_rat(103993, 33102)))[-1]
    (103993, 33102)
    """
    while d != 0:
        yield n // d
        n, d = d, n % d


def getResults(name, query, maxDepth, filter, queryFactory):
    """return results for search if available, and None if not

        Returning a non-None value means that this search index claims the
        search.  No other search indexes will be consulted, and the given
        results are believed to be accurate.
        """


def category_and_ancestors(category):
    """Generate a list of strings: a category and all its ancestors.

    >>> for c in category_and_ancestors('Expenses.Travel.PyCon'):
    ...     c
    ...
    'Expenses.Travel.PyCon'
    'Expenses.Travel'
    'Expenses'

    """
    i = category.rfind('.')
    while i != -1:
        yield category
        category = category[:i]
        i = category.rfind('.')
    yield category


def delete_folder(folder):
    """
	Deletes a folder if it exists.
	"""
    import shutil
    shutil.rmtree(folder, ignore_errors=True)
    return


@classmethod
def has_archiving(cls):
    """Returns whether it supports archiving items on the fetch process.

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


def find_best_match(path, prefixes):
    """Find the Ingredient that shares the longest prefix with path."""
    path_parts = path.split('.')
    for p in prefixes:
        if len(p) <= len(path_parts) and p == path_parts[:len(p)]:
            return '.'.join(p), '.'.join(path_parts[len(p):])
    return '', path


def polygon_area(points_list, precision=100):
    """Calculate area of an arbitrary polygon using an algorithm from the web.

    Return the area of the polygon as a positive float.

    Arguments:
    points_list -- list of point tuples [(x0, y0), (x1, y1), (x2, y2), ...]
                   (Unclosed polygons will be closed automatically.
    precision -- Internal arithmetic precision (integer arithmetic).

    >>> polygon_area([(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 0), (0, 0)])
    3.0

    Credits:
    Area of a General Polygon by David Chandler
    http://www.davidchandler.com/AreaOfAGeneralPolygon.pdf

    """
    for i in range(len(points_list)):
        points_list[i] = int(points_list[i][0] * precision), int(
            points_list[i][1] * precision)
    if points_list[-1] != points_list[0]:
        points_list.append(points_list[0])
    area = 0
    for i in range(len(points_list) - 1):
        x_i, y_i = points_list[i]
        x_i_plus_1, y_i_plus_1 = points_list[i + 1]
        area = area + x_i_plus_1 * y_i - y_i_plus_1 * x_i
    area = abs(area / 2)
    area = float(area) / precision ** 2
    return area


def load_handlers(name):
    """Load the (URL pattern, handler) tuples for each component."""
    mod = __import__(name, fromlist=['default_handlers'])
    return mod.default_handlers


def set_dtype(value, dtype):
    """Converts the value to the given dtype."""
    if dtype == 'float':
        value = float(value)
    elif dtype == 'int':
        value = int(value)
    elif dtype == 'str':
        value = value
    return value


def remove_duplicates(seq, idfun=None):
    """ removes duplicates from a list, order preserving, as found in
    http://www.peterbe.com/plog/uniqifiers-benchmark
    """
    if idfun is None:

        def idfun(x):
            return x
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        if marker in seen:
            continue
        seen[marker] = 1
        result.append(item)
    return result


def vowels(input_string):
    """
	To count the number of vowels in a string
	"""
    count = 0
    for i in input_string:
        if (i == 'a' or i == 'e' or i == 'i' or i == 'o' or i == 'u' or i ==
            'A' or i == 'E' or i == 'I' or i == 'O' or i == 'U'):
            count = count + 1
    return count


def add_numbers(number1, number2):
    """
	Method to return the addition of the two numbers.
	Arguments:
		number1 : ['int']
		number2 : ['int']
	"""
    return number1 + number2


def _add_header(fig, txt):
    """Add header text to mpl Figure"""
    fig.text(0, 0, txt, fontsize=8, color='black', ha='left', va='bottom')


@classmethod
def from_image_ref(cls, context, image_api, image_ref):
    """Create instance from glance image

        :param context: the request context
        :param image_api: the glance client API
        :param image_ref: the glance image identifier

        Creates a new object instance, initializing from the
        properties associated with a glance image

        :returns: an ImageMeta instance
        """
    image_meta = image_api.get(context, image_ref)
    image = cls.from_dict(image_meta)
    setattr(image, 'id', image_ref)
    return image


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 append_verbosity_argument(cmd, verbosity):
    """
    Just in case we want to modify how many v's we use, centralise this here.
    """
    return cmd + ' -vvvv' if verbosity else cmd


def options(opt):
    """
	Add the ``--with-diab-bindir`` command-line options.
	"""
    opt.add_option('--with-diab-bindir', type='string', dest='diabbindir',
        help='Specify alternate diab bin folder', default='')


def start(request):
    """
    Start Registration view with login and lost password function
    """
    pass


def transform_cols_from_library(df, scaler_library, inverse=False, columns=[]):
    """Accepts a df and a scaler_library that was transformed using make_scaler_library.
    Inverse tansforms listed columns (if columns =[] then all columns)
    Returns a dataframe with all columns of original df."""
    df_out = df.copy()
    if len(columns) == 0:
        columns = df.columns
    for col in columns:
        scaler = scaler_library[col]
        if hasattr(scaler, 'data_range_') == False:
            raise Exception(f'The scaler for {col} is not fitted.')
        if inverse == False:
            scaled_col = scaler.transform(df[col].values.reshape(-1, 1))
        elif inverse == True:
            scaled_col = scaler.inverse_transform(df[col].values.reshape(-1, 1)
                )
        df_out[col] = scaled_col.ravel()
    return df_out


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

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

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

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

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

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

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


@classmethod
def all_objects(cls, queryset, user, request):
    """
        Returns all objects for this model.
        """
    return queryset


def dgl_csr_neighbor_non_uniform_sample(*seed_arrays, **kwargs):
    """This operator samples sub-graph from a csr graph via an
    non-uniform probability. The operator is designed for DGL.

    The operator outputs four sets of NDArrays to represent the sampled results
    (the number of NDArrays in each set is the same as the number of seed NDArrays):
    1) a set of 1D NDArrays containing the sampled vertices, 2) a set of CSRNDArrays representing
    the sampled edges, 3) a set of 1D NDArrays with the probability that vertices are sampled,
    4) a set of 1D NDArrays indicating the layer where a vertex is sampled.
    The first set of 1D NDArrays have a length of max_num_vertices+1. The last element in an NDArray
    indicate the acutal number of vertices in a subgraph. The third and fourth set of NDArrays have a length
    of max_num_vertices, and the valid number of vertices is the same as the ones in the first set.

    Example:

       .. code:: python

      shape = (5, 5)
      prob = mx.nd.array([0.9, 0.8, 0.2, 0.4, 0.1], dtype=np.float32)
      data_np = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20], dtype=np.int64)
      indices_np = np.array([1,2,3,4,0,2,3,4,0,1,3,4,0,1,2,4,0,1,2,3], dtype=np.int64)
      indptr_np = np.array([0,4,8,12,16,20], dtype=np.int64)
      a = mx.nd.sparse.csr_matrix((data_np, indices_np, indptr_np), shape=shape)
      seed = mx.nd.array([0,1,2,3,4], dtype=np.int64)
      out = mx.nd.contrib.dgl_csr_neighbor_non_uniform_sample(a, prob, seed, num_args=3, num_hops=1, num_neighbor=2, max_num_vertices=5)

      out[0]
      [0 1 2 3 4 5]
      <NDArray 6 @cpu(0)>

      out[1].asnumpy()
      array([[ 0,  1,  2,  0,  0],
             [ 5,  0,  6,  0,  0],
             [ 9, 10,  0,  0,  0],
             [13, 14,  0,  0,  0],
             [ 0, 18, 19,  0,  0]])

      out[2]
      [0.9 0.8 0.2 0.4 0.1]
      <NDArray 5 @cpu(0)>

      out[3]
      [0 0 0 0 0]
      <NDArray 5 @cpu(0)>

    Defined in src/operator/contrib/dgl_graph.cc:L883

    Parameters
    ----------
    csr_matrix : NDArray
        csr matrix
    probability : NDArray
        probability vector
    seed_arrays : NDArray[]
        seed vertices
    num_hops : long, optional, default=1
        Number of hops.
    num_neighbor : long, optional, default=2
        Number of neighbor.
    max_num_vertices : long, optional, default=100
        Max number of vertices.

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

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


@classmethod
def strptime(cls, date_string, format):
    """string, format -> new datetime parsed from a string (like time.strptime())."""
    import _strptime
    return _strptime._strptime_datetime(cls, date_string, format)


def external_edit(filepath: str=''):
    """Edit image in an external application

    :param filepath: filepath
    :type filepath: str
    """
    pass


def description(maxchars=1024):
    """Get the description (from metadata) of this reference.
        """


def __bool__():
    """Test whether there are any annotations

        Must be identical to __nonzero__()
        """


def quota_parse(quota_dict):
    """
    Parse the output of ``SESConnection.get_send_quota()`` to just the results.
    """
    return quota_dict['GetSendQuotaResponse']['GetSendQuotaResult']


def print_url(title, url):
    """Pretty-print a URL on the terminal."""
    import click
    click.secho('  %s: ' % title, nl=False, fg='blue')
    click.secho(url, bold=True)


def create_search_group(recordset=None, field=None, values=None,
    criteria_operator='EqualTo'):
    """
    Create a Coalesce search group/filter object (the value of "group" in a
    `Coalesce search request object
    <https://github.com/InCadence/coalesce/wiki/REST-API#search-query-data-format>`_)
    that combines all entered values for a given field, either including or
    excluding (depending on the value of "criteria_operator") all records
    matching any of the supplied values.

    :param recordset:  the (:class:`str`) recordset of the field to be
        search on
    :param field:  the (:class:`str`) field to be searched on
    :param values:  a :class:`list` or list-like of values to search for.
        The values themselves should be of simple, JSON-serializable types
        (e.g., strings, numbers, Boolean).
    :param criteria_operator:  "EqualTo", if the search is to *include*
        a record matching *any* element of "values", or "NotEqualTo", if
        the search is to *exclude all* records matching *any* element of
        "values".

    :returns:  a Coalesce search group as a :class:`dict`, or ``None`` if
        "values" is empty

    """
    if not isinstance(recordset, str):
        raise TypeError('Please supply a recordset as a string.')
    if not isinstance(field, str):
        raise TypeError('Please supply a field to search on, as a string.')
    values_error_msg = ('Please supply a list or list-like of values to ' +
        'search for.')
    if not values:
        raise TypeError(values_error_msg)
    elif isinstance(values, str):
        raise TypeError(values_error_msg)
    else:
        try:
            values[0]
        except:
            raise TypeError(values_error_msg)
    if criteria_operator == 'EqualTo':
        group_operator = 'OR'
    elif criteria_operator == 'NotEqualTo':
        group_operator = 'AND'
    else:
        raise ValueError('The value of "criteria_operator" must be either ' +
            '"EqualTo" or "NotEqualTo".')
    criteria = []
    for value in values:
        criteria_set = {'recordset': recordset, 'field': field, 'operator':
            criteria_operator, 'value': value, 'matchCase': False}
        criteria.append(criteria_set)
    if len(criteria) > 0:
        group = {'operator': group_operator, 'criteria': criteria}
    else:
        group = None
    return group


def do_remove(logger, software_url, computer_id, local):
    """
    Request deletion of Software Release
    'software_url' from computer 'computer_id'.
    """
    logger.info('Requesting deletion of %s Software Release...', software_url)
    if software_url in local:
        software_url = local[software_url]
    local['slap'].registerSupply().supply(software_release=software_url,
        computer_guid=computer_id, state='destroyed')
    logger.info('Done.')


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

    """
    pass


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 add_object_to_grouping(item: object, grouping: dict, group_name: str
    ) ->dict:
    """Add item to grouping with group name.

    :param item: item to add to grouping
    :type item: object
    :param grouping: previously grouped items
    :type grouping: dict
    :param group_name: group to append to
    :type group_name: str
    :return: grouped items
    :rtype: dict
    """
    group = grouping.get(group_name, [])
    group.append(item)
    grouping[group_name] = group
    return grouping


def printPairedDellyTransApp(FH, tabCount, mergedTumorBam,
    mergedTumorBamIndex, mergedNormalBam, mergedNormalBamIndex):
    """ Still need to determine how translocations are handled

    Have to run TRA on the bam in its entirety """
    tabs = tabCount * '\t'
    Str = tabs + '### Delly\n' + tabs + """# dellyAnalysisTypes does not need to be defined in this loop
""" + tabs + 'string traAnalysis = "TRA";\n' + tabs + """file dellyTransVcf <single_file_mapper; file=strcat(outDir,"/",patient.patient,".",traAnalysis,".delly.vcf")>;
""" + tabs + """file dellyTransVcfLog <single_file_mapper; file=strcat(outDir,"/",patient.patient,".",traAnalysis,".delly.log")>;
""" + tabs + '(dellyTransVcfLog,dellyTransVcf) = DellyPaired (' + mergedTumorBam + ',' + mergedTumorBamIndex + ',' + mergedNormalBam + ',' + mergedNormalBamIndex + """,patient.patient,outDir,traAnalysis);

""" + tabs + '# Add translocation vcf to contig vcfs\n' + tabs + """DellyPairedContigVcfs << dellyTransVcf;

"""
    FH.write(Str)
    return


def gen_layer_circle(radius, sort_key, fill_color, fill_opacity,
    stroke_color, stroke_width):
    """
    Build a Mapbox GL Style layer for circle.
    """
    return {'type': 'circle', 'layout': {'circle-sort-key': ['-', sort_key]
        }, 'paint': {'circle-radius': radius, 'circle-color': fill_color,
        'circle-opacity': fill_opacity, 'circle-stroke-color': stroke_color,
        'circle-stroke-width': stroke_width}}


@staticmethod
def all_tasks(_):
    """
        Check if a task is launchable

        :param assr_info: dictionary containing procstatus for the assessor
                          (not used)
        :return: True to take all assessor
        """
    return True


@staticmethod
def put_archive(container, archive):
    """
        Inserts the given tar archive into the container.

        :param container: The container to put the archive in
        :type container: Container
        :param archive: The archive, that is copied into the container
        :type archive: bytes
        """
    container.put_archive('/', archive)


@staticmethod
def get_default_search_space(estimator, task):
    """Create a dictionary of default parameters if the user didnt provide parameters.

        Inputs

        estimator: string value
            A string value that determines the estimator: 'mlp','xgboost','svm', or 'gbdt'

        task: string value
            A string value that determines the task under consideration: 'regression' or 'binary classification'

        Returns

        params: Dictionary
            A dictionary that contains default parameters to be used.

        """
    if estimator == 'xgboost':
        if task == 'binary classification':
            params = {'learning_rate': [0.1, 0.3, 2], 'max_depth': [1, 10,
                0], 'n_estimators': [2, 70, 0], 'subsample': [0.7, 1, 2]}
        else:
            params = {'objective': ['reg:linear', 'reg:tweedie',
                'reg:gamma'], 'learning_rate': [0.1, 0.3, 2], 'max_depth':
                [1, 10, 0], 'n_estimators': [2, 70, 0], 'subsample': [0.7,
                1, 2]}
    elif estimator == 'gbdt':
        if task == 'binary classification':
            params = {'learning_rate': [0.1, 0.3, 2], 'max_depth': [1, 10,
                0], 'n_estimators': [2, 70, 0], 'subsample': [0.7, 1, 2]}
        else:
            params = {'objective': ['tweedie', 'regression'],
                'learning_rate': [0.1, 0.3, 2], 'max_depth': [1, 10, 0],
                'n_estimators': [2, 70, 0], 'subsample': [0.7, 1, 2]}
    elif estimator == 'svm':
        params = {'kernel': ['linear', 'rbf', 'poly'], 'gamma': [0.1, 10, 1
            ], 'C': [0.1, 10, 1], 'degree': [0, 6, 0]}
    elif estimator == 'mlp':
        params = {'optimizer': ['RMSprop', 'adam', 'sgd', 'adamax', 'nadam',
            'adadelta'], 'learning_rate': [0.1, 0.3, 2], 'neurons': [1, 40,
            0], 'hiddenactivation': ['relu', 'sigmoid', 'tanh'],
            'activation': ['relu', 'sigmoid', 'tanh']}
    return params


@classmethod
def maptag(cls, tag, fn):
    """
        Map (override) tag => I{class} mapping.
        @param tag: An xsd tag name.
        @type tag: str
        @param fn: A function or class.
        @type fn: fn|class.
        """
    cls.tags[tag] = fn


def on_error(ws, error):
    """Load on getting an error."""
    print(error)


def getCompoundedStylesheet(widget):
    """
    This will return the entire stylesheet which is affecting this widget.
    The resulting stylesheet will be the widgets stylesheet, and the
    stylesheet of all its parents.

    The order is such that the widgets style is last, and the root level
    widgets style is first - meaning you can apply the returned stylesheet
    to create the exact same result.

    :param widget: Widget to read the style from
    :type widget: QWidget

    :return: stylesheet data
    :rtype: str
    """
    all_data = [widget.styleSheet()]
    while widget.parentWidget():
        widget = widget.parentWidget()
        all_data.append('' or widget.styleSheet())
    all_data.reverse()
    all_data = '\n'.join(all_data)
    return all_data


def paste():
    """Undocumented contribute <https://developer.blender.org/T51061>

    """
    pass


def keyEvent(a):
    """Create key for an event

    :param a: First event
    """
    a = a['DTSTART'].dt
    if getattr(a, 'date', None):
        a_date = a.date()
        a = a.hour, a.minute
    else:
        a_date = a
        a = 0, 0
    return a_date, a


def move_point_num(point, ipoint, to_clust, from_clust, cl_attr_sum, membership
    ):
    """Move point between clusters, numerical attributes."""
    membership[to_clust, ipoint] = 1
    membership[from_clust, ipoint] = 0
    for iattr, curattr in enumerate(point):
        cl_attr_sum[to_clust][iattr] += curattr
        cl_attr_sum[from_clust][iattr] -= curattr
    return cl_attr_sum, membership


def reshape(input, shape):
    """Reshape the tensor.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    shape : tuple of int
        The new shape.

    Returns
    -------
    Tensor
        The reshaped tensor.
    """
    pass


def shape_calculator_lightgbm_concat(operator):
    """
    Shape calculator for operator *LightGBMConcat*.
    """
    pass


def get_GeoArrayPosition_from_boxImYX(boxImYX):
    """Return row_start,row_end,col_start,col_end and assumes boxImYX as [UL_YX,UR_YX,LR_YX,LL_YX)."""
    rS, cS = boxImYX[0]
    rE, cE = boxImYX[2]
    return rS, rE - 1, cS, cE - 1


def _is_tempo_or_prob(line: dict) ->bool:
    """
    Returns True if report type is TEMPO or non-null probability
    """
    return line.get('type') == 'TEMPO' or line.get('probability') is not None


def get_metafield(doc, metafield):
    """For fields like _parent and _routing es1.x requires you to request them
    in 'fields', and they're returned as such. ES2.x always returns them but
    at the root document level (like _id). This function copes with both.
    """
    return doc.get(metafield, doc.get('fields', {}).get(metafield))


def flatten_tuples(iterable):
    """
    Flatten an iterable containing several tuples, into a single tuple.

    Sum all tuples, which "extends" them, with empty tuple as start value.

    """
    return sum(iterable, ())


def xref_of_instr(instr):
    """ Return xref for branch instruction """
    return int.from_bytes(instr.operand, byteorder='little', signed=True
        ) + instr.offset_end - 2


@classmethod
def alloc(cls, vm, size):
    """Returns an allocated page of size @size if cls.allocator is set.
        Raises ValueError otherwise.
        """
    if cls.allocator is None:
        raise ValueError(
            'Cannot provide None address to MemType() if%s.set_allocator has not been called.'
             % __name__)
    return cls.allocator(vm, size)


def leaders_to_right(iterable):
    """
     Leaders-to-right in the iterable is defined as if an element in the iterable
     is greater than all other elements to it's right side
    :param iterable: It should be of either list or tuple types containing numbers
    :return: list of tuples containing leader element and its index

        Eg: leaders_to_right({5, 6, 7, 3, 6]) gives [(7, 2) (6, 4)]
            Here the elements at the indexes 2, 4 are greater than all the elements to its right
    """
    if type(iterable) == list or type(iterable) == tuple:
        pass
    else:
        raise TypeError('Iterable should be of either list or tuple')
    for item in iterable:
        if not isinstance(item, int):
            raise ValueError('Only numbers are accepted in the iterable')
    leaders_list = []
    if len(iterable) > 0:
        leaders_list.append((iterable[-1], len(iterable) - 1))
    for i in range(len(iterable) - 2, -1, -1):
        if iterable[i] >= leaders_list[-1][0]:
            leaders_list.append((iterable[i], i))
    return list(reversed(leaders_list))


def get_x_bits(num, max_bits, num_bits, right_bits=True):
    """ ensure the correct number of bits and pull the upper x bits """
    bits = bin(num).lstrip('0b')
    bits = bits.zfill(max_bits)
    if right_bits:
        return int(bits[-num_bits:], 2)
    return int(bits[:num_bits], 2)


@classmethod
def provided_by(cls, instance):
    u"""Check that object is an instance of class that implements interface.
        """
    return cls.implemented_by(instance.__class__)


@staticmethod
def event_time_high():
    """ Provides the mask needed to decode the Event Time High from Word 2 """
    return 65535, 0


def list_application_revisions(applicationName=None, sortBy=None, sortOrder
    =None, s3Bucket=None, s3KeyPrefix=None, deployed=None, nextToken=None):
    """
    Lists information about revisions for an application.
    See also: AWS API Documentation

    :example: response = client.list_application_revisions(
        applicationName='string',
        sortBy='registerTime'|'firstUsedTime'|'lastUsedTime',
        sortOrder='ascending'|'descending',
        s3Bucket='string',
        s3KeyPrefix='string',
        deployed='include'|'exclude'|'ignore',
        nextToken='string'
    )

    :type applicationName: string
    :param applicationName: [REQUIRED]
            The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.

    :type sortBy: string
    :param sortBy: The column name to use to sort the list results:
            registerTime: Sort by the time the revisions were registered with AWS CodeDeploy.
            firstUsedTime: Sort by the time the revisions were first used in a deployment.
            lastUsedTime: Sort by the time the revisions were last used in a deployment.
            If not specified or set to null, the results will be returned in an arbitrary order.

    :type sortOrder: string
    :param sortOrder: The order in which to sort the list results:
            ascending: ascending order.
            descending: descending order.
            If not specified, the results will be sorted in ascending order.
            If set to null, the results will be sorted in an arbitrary order.

    :type s3Bucket: string
    :param s3Bucket: An Amazon S3 bucket name to limit the search for revisions.
            If set to null, all of the user's buckets will be searched.

    :type s3KeyPrefix: string
    :param s3KeyPrefix: A key prefix for the set of Amazon S3 objects to limit the search for revisions.

    :type deployed: string
    :param deployed: Whether to list revisions based on whether the revision is the target revision of an deployment group:
            include: List revisions that are target revisions of a deployment group.
            exclude: Do not list revisions that are target revisions of a deployment group.
            ignore: List all revisions.

    :type nextToken: string
    :param nextToken: An identifier returned from the previous list application revisions call. It can be used to return the next set of applications in the list.

    :rtype: dict
    :return: {
        'revisions': [
            {
                'revisionType': 'S3'|'GitHub',
                's3Location': {
                    'bucket': 'string',
                    'key': 'string',
                    'bundleType': 'tar'|'tgz'|'zip',
                    'version': 'string',
                    'eTag': 'string'
                },
                'gitHubLocation': {
                    'repository': 'string',
                    'commitId': 'string'
                }
            },
        ],
        'nextToken': 'string'
    }

    :returns:
    S3: An application revision stored in Amazon S3.
    GitHub: An application revision stored in GitHub.

    """
    pass


def ipopo_state_to_str(state):
    """
    Converts the state of a component instance to its string representation

    :param state: The state of an iPOPO component
    :return: A string representation of the state
    """
    ipopo_states = {(0): 'INVALID', (1): 'VALID', (2): 'KILLED', (3):
        'VALIDATING', (4): 'ERRONEOUS'}
    return ipopo_states.get(state, 'Unknown state ({0})'.format(state))


def download_ftp_file(path, outdir):
    """Given a link starting with ftp://, use wget to download file."""
    import os
    run_cmd = 'wget -P ' + outdir + ' ' + path
    os.system(run_cmd)


def __new__(mcs, name, bases, attrs, **kwargs):
    """Creates Bonfig class type

        """
    attrs['__fields__'] = set()
    attrs['__store_attrs__'] = set()
    return super().__new__(mcs, name, bases, attrs, **kwargs)


def ID(b):
    """Identity function"""
    return b


@staticmethod
def conv_equa(list_surface):
    """Method converting a list of if of surface and return a tuple with
        the informations of the volume EQUA T4"""
    minus_surfs = []
    plus_surfs = []
    seen = set()
    for elt in list_surface:
        assert isinstance(elt, int)
        if elt in seen:
            continue
        seen.add(elt)
        if elt < 0:
            minus_surfs.append(-elt)
        elif elt > 0:
            plus_surfs.append(elt)
    return plus_surfs, minus_surfs


def duck_type_collection(specimen, default=None):
    """Given an instance or class, guess if it is or is acting as one of
    the basic collection types: list, set and dict.  If the __emulates__
    property is present, return that preferentially.
    """
    if hasattr(specimen, '__emulates__'):
        if specimen.__emulates__ is not None and issubclass(specimen.
            __emulates__, set):
            return set
        else:
            return specimen.__emulates__
    isa = isinstance(specimen, type) and issubclass or isinstance
    if isa(specimen, list):
        return list
    elif isa(specimen, set):
        return set
    elif isa(specimen, dict):
        return dict
    if hasattr(specimen, 'append'):
        return list
    elif hasattr(specimen, 'add'):
        return set
    elif hasattr(specimen, 'set'):
        return dict
    else:
        return default


def Content_type(st) ->str:
    """
        get filename and decide content-type header
        st == req.url
    """
    extra = ''
    st = st.split('.')[-1]
    if st in {'html', 'css', 'txt', 'csv', 'xml', 'js', 'json', 'php', 'md'}:
        type_1 = 'text'
        if st == 'js':
            type_2 = 'javascript'
        elif st == 'md':
            type_2 = 'markdown'
        elif st == 'html':
            type_2 = st
            extra = '; charset=utf-8'
        else:
            type_2 = st
    elif st in {'jpg', 'jpeg', 'png', 'gif', 'tiff'}:
        type_1 = 'image'
        type_2 = st
    elif st in {'mkv', 'avi', 'mp4'}:
        type_1 = 'video'
        if st in {'mp4', 'avi'}:
            type_2 = st
        else:
            type_2 = 'webm'
    else:
        return {'Content-type': 'text/plain'}
    return {'Content-type': '{}/{}{}'.format(type_1, type_2, extra)}


def open_python_file(filename):
    """Open a read-only Python file taking proper care of its encoding.

    In Python 3, we would like all files to be opened with utf-8 encoding.
    However, some author like to specify PEP263 headers in their source files
    with their own encodings. In that case, we should respect the author's
    encoding.
    """
    import tokenize
    if hasattr(tokenize, 'open'):
        return tokenize.open(filename)
    else:
        return open(filename, 'r')


def nfc_encode(string):
    """
    把包含直接信息的字符串转成nfc模块可识别的数组
    """
    if len(string) > 16:
        return None
    else:
        result = []
        for i in range(len(string)):
            result.append(ord(string[i]))
        return result


def remove_vcard_groups(lines, group):
    """
    Remove groups from vCard. RFC 2426 pages 28, 29.

    @param lines: List of unfolded vCard lines
    @param group: Name of group
    @return: Lines without groups and dot separator
    """
    if group:
        for index in range(len(lines)):
            lines[index] = lines[index][len(group):]
    return lines


def validate_non_negative_array(x):
    """Validate array elements are non-negative."""
    assert (x >= 0).all(), 'Expecting array of non-negative elements.'


@staticmethod
def _split_header_values(request, header_name):
    """Convert a comma-separated header value into a list of values."""
    values = []
    if header_name in request.headers:
        for value in request.headers[header_name].rsplit(','):
            value = value.strip()
            if value:
                values.append(value)
    return values


def theta_K_Na_PK74(T, P):
    """c-c': potassium sodium [PK74]."""
    theta = -0.012
    valid = T == 298.15
    return theta, valid


@classmethod
def get_view_set(cls):
    """returns the view_set defined in the model Meta or the LDPViewSet class"""
    view_set = getattr(cls._meta, 'view_set', getattr(cls.Meta, 'view_set',
        None))
    if view_set is None:
        from djangoldp.views import LDPViewSet
        view_set = LDPViewSet
    return view_set


def is_text(data):
    """Check if data is text instance"""
    return isinstance(data, str)


def __call__(func, retries=0, sleep=None, site_names=(), side_effect_free=
    False, root_folder_name='nti.dataserver'):
    """
        Runs the function given in `func` in a transaction and application local
        site manager (defaulting to the current site manager).

        :param function func: A function of zero parameters to run. If
            it has a docstring, that will be used as the transactions
            note. A transaction will be begun before this function
            executes, and committed after the function completes. This
            function may be rerun if retries are requested, so it
            should be prepared for that.

        :keyword int retries: The number of times to retry the
            transaction and execution of `func` if
            :class:`transaction.interfaces.TransientError` is raised
            when committing. Defaults to zero (so the job runs once).
            If you specify None, an implementation-specific
            number of retries will be used.

        :keyword float sleep: If not none, then the greenlet running
            this function will sleep for this long between retry
            attempts.

        :keyword site_names: DEPRECATED. Sequence of strings giving the
            virtual host names to use. If you do not provide this argument,
            then the currently installed site will be maintained when
            the transaction is run. NOTE: The implementation of this
            may maintain either the site names or the actual site
            object.

        :keyword bool side_effect_free: If true (not the default), then
            the function is assummed to have no side effects that need
            to be committed; the transaction runner is free to abort/rollback
            or commit the transaction at its leisure.

        :keyword str root_folder_name: This names the folder that can be found in the
            root of the ZODB that will serve as the starting point to look for the
            persistent named site.

        :return: The value returned by the first successful invocation of `func`.
        """


def update_attributes(obj, **kwargs):
    """Update object with provided properties."""
    for k, v in kwargs.items():
        k = k.split('.') if '.' in k else k.split('__')
        o = obj
        for name in k[:-1]:
            o = getattr(o, name)
        getattr(o, k[-1])
        setattr(o, k[-1], v)


def space_indentation(s):
    """The number of leading spaces in a string

    :param str s: input string

    :rtype: int
    :return: number of leading spaces
    """
    return len(s) - len(s.lstrip(' '))


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

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


def parse(instructions):
    """Return a dict with indices of matching brackets."""
    jumps = {}
    try:
        stack = []
        for i, instruction in enumerate(instructions):
            if instruction == '[':
                stack.append(i)
            elif instruction == ']':
                j = stack.pop()
                jumps[i], jumps[j] = j, i
    except IndexError:
        raise SyntaxError(f'unbalanced brackets at position {i}')
    else:
        return jumps


def customdata_custom_splitnormals_add():
    """Add a custom split normals layer, if none exists yet

    """
    pass


def _script_command_options(opts):
    """Extract `command` and `options` from argparse 'opts'."""
    if opts.run_script_site is not None:
        command = 'run'
        options = opts.run_script_site
    elif opts.kill_sites is not None:
        command = 'kill'
        options = opts.kill_sites
    elif opts.status_sites is not None:
        command = 'status'
        options = opts.status_sites
    else:
        raise ValueError('Unknown request')
    return command, options


def pattern(regex):
    """
    Return the raw string pattern of a Regex instance.
    """
    return regex.pattern


def print_phylip(source_dict):
    """Print phylip-formatted string from {taxon: seq} dict."""
    taxa_list = list(source_dict.keys())
    no_taxa = len(taxa_list)
    pad_longest_name = len(max(taxa_list, key=len)) + 3
    seq_length = len(next(iter(source_dict.values())))
    header = str(len(source_dict)) + ' ' + str(seq_length)
    phylip_string = header + '\n'
    for taxon, seq in sorted(source_dict.items()):
        taxon = taxon.replace(' ', '_').strip("'")
        phylip_string += taxon.ljust(pad_longest_name, ' ') + seq + '\n'
    return phylip_string


def carbon_to_miles(kg_carbon):
    """
    8.89 × 10-3 metric tons CO2/gallon gasoline ×
    1/22.0 miles per gallon car/truck average ×
    1 CO2, CH4, and N2O/0.988 CO2 = 4.09 x 10-4 metric tons CO2E/mile

    Source: EPA
    """
    return 4.09 * 10 ** -7 * kg_carbon


def find_offset_list(edge: int) ->list:
    """
    Get the offset for all rows to be used to identify the neighbor cells.

    Parameters
    ----------
    edge: int
        The edge size of the hexagonal grid.

    Returns
    -------
    offset: list
        A list of offsets for the entire hexagonal grids.
    """
    k = 0
    counter_index = 0
    offset = []
    for i in range(0, edge * 2 - 2):
        if i < edge - 1:
            k = edge + i
            offset.append(k)
        else:
            offset.append(k - counter_index)
            counter_index = counter_index + 1
    return offset


@staticmethod
def shutdown(wait=True):
    """Shutting down a SynchronousExecutor does nothing"""
    pass


def crosscorrelation(x, y, lag=None, verbose=True):
    """Compute lead-lag correlations between 2 time series.

    <x>,<y>: 1-D time series.
    <lag>: lag option, could take different forms of <lag>:
          if 0 or None, compute ordinary correlation and p-value;
          if positive integer, compute lagged correlation with lag
          upto <lag>;
          if negative integer, compute lead correlation with lead
          upto <-lag>;
          if pass in an list or tuple or array of integers, compute
          lead/lag correlations at different leads/lags.

    Note: when talking about lead/lag, uses <y> as a reference.
    Therefore positive lag means <x> lags <y> by <lag>, computation is
    done by shifting <x> to the left hand side by <lag> with respect to
    <y>.
    Similarly negative lag means <x> leads <y> by <lag>, computation is
    done by shifting <x> to the right hand side by <lag> with respect to
    <y>.

    Return <result>: a (n*2) array, with 1st column the correlation
    coefficients, 2nd column correpsonding p values.

    Currently only works for 1-D arrays.
    """
    import numpy
    from scipy.stats import pearsonr
    if len(x) != len(y):
        raise 'Input variables of different lengths.'
    if numpy.isscalar(lag):
        if abs(lag) >= len(x):
            raise 'Maximum lag equal or larger than array.'
        if lag < 0:
            lag = -numpy.arange(abs(lag) + 1)
        elif lag == 0:
            lag = [0]
        else:
            lag = numpy.arange(lag + 1)
    elif lag is None:
        lag = [0]
    else:
        lag = numpy.asarray(lag)
    result = []
    if verbose:
        print
        '\n#<lagcorr>: Computing lagged-correlations at lags:', lag
    for ii in lag:
        if ii < 0:
            result.append(pearsonr(x[:ii], y[-ii:]))
        elif ii == 0:
            result.append(pearsonr(x, y))
        elif ii > 0:
            result.append(pearsonr(x[ii:], y[:-ii]))
    result = numpy.asarray(result)
    return result


def slide_marker(offset: float=(0.0, 0.0)):
    """Slide marker areas

    :param offset: Offset, Offset in floating point units, 1.0 is the width and height of the image
    :type offset: float
    """
    pass


def get_taurus_parser(parser=None):
    """ Returns a :class:`optparse.OptionParser` initialized with a
    :class:`optparse.OptionGroup` containning some taurus options.
    If a parser is given as parameter then it uses this parser instead of
    creating a new one.

    :param parser: an option parser or None (default) to create a new parser
    :type parser: :class:`optparse.OptionParser`
    :return: an option parser or the given parser if it is not None
    :rtype: :class:`optparse.OptionParser`"""
    import optparse
    if parser is None:
        parser = optparse.OptionParser()
    g = parser.get_option_group('--taurus-log-level')
    if g is None:
        group = optparse.OptionGroup(parser, 'Taurus Options',
            'Basic options present in any taurus application')
        help_tauruslog = (
            'taurus log level. Allowed values are (case insensitive): critical, error, warning/warn, info, debug, trace'
            )
        help_tangohost = (
            'Tango host name (either HOST:PORT or a Taurus URI, e.g. tango://foo:1234)'
            )
        help_tauruspolling = 'taurus global polling period in milliseconds'
        help_taurusserial = (
            'taurus serialization mode. Allowed values are (case insensitive): serial, concurrent (default)'
            )
        help_rcport = 'enables remote debugging using the given port'
        help_formatter = 'Override the default formatter'
        group.add_option('--taurus-log-level', dest='taurus_log_level',
            metavar='LEVEL', help=help_tauruslog, type='str', default='info')
        group.add_option('--taurus-polling-period', dest=
            'taurus_polling_period', metavar='MILLISEC', help=
            help_tauruspolling, type='int', default=None)
        group.add_option('--taurus-serialization-mode', dest=
            'taurus_serialization_mode', metavar='SERIAL', help=
            help_taurusserial, type='str', default='Concurrent')
        group.add_option('--tango-host', dest='tango_host', metavar=
            'TANGO_HOST', help=help_tangohost, type='str', default=None)
        group.add_option('--remote-console-port', dest=
            'remote_console_port', metavar='PORT', help=help_rcport, type=
            'int', default=None)
        group.add_option('--default-formatter', dest='default_formatter',
            metavar='FORMATTER', help=help_formatter, type='str', default=None)
        parser.add_option_group(group)
    return parser


def sanitize_identifier(name):
    """
    Makes name a Python identifier by replacing all nonsafe characters with '_'
    """
    new_name = list(name)
    for i, c in enumerate(list(name)):
        if i == 0 and not (c.isalpha() or c == '_'):
            new_name[i] = '_'
        if i > 0 and not (c.isalnum() or c == '_'):
            new_name[i] = '_'
    return ''.join(new_name)


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

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

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


def checkPermission(permission, object):
    """Check whether the security context allows the given permission on
        the given object.

        Arguments:

        permission -- A permission name

        object -- The object being accessed according to the permission
        """


def star_grep(cluster, logdir, cmdline, *args):
    """Scan (not real grep) for string matches in stdout"""
    pattern = cmdline[6:].encode(cluster.defaults['character_encoding'])
    for host in cluster:
        job = cluster.last_result.get(host)
        if job:
            res = job.result
            for line_number, line in enumerate(res.stdout.split(b'\n'), 1):
                if pattern in line:
                    print('%s [%d]: %s' % (host, line_number, line.rstrip()
                        .decode(cluster.defaults['character_encoding'],
                        'replace')))
            for line_number, line in enumerate(res.stderr.split(b'\n'), 1):
                if pattern in line:
                    print('%s [%d/stderr]: %s' % (host, line_number, line.
                        rstrip().decode(cluster.defaults[
                        'character_encoding'], 'replace')))


def get(label_id):
    """Returns a dict with the label information for the label
        with ID ``label_id``.

        Example:

        {'label_id': 'label-id',
         'title': 'Label Title',
         'color': '#FF0000'}
        """


def encode_lat(lat: float) ->str:
    """
    Encode Latitude in DDMMSS format.
    """
    lat_dir = 'N' if lat > 0 else 'S'
    lat_abs = abs(lat)
    lat_deg = int(lat_abs)
    lat_min = lat_abs % 1 * 60
    return '%02i%05.2f' % (lat_deg, lat_min)


def gameweek(gw='current'):
    """Return information about a Gameweek, defaults to current Gameweek"""
    pass


def bold(s):
    """
    Return the given string (``s``) surrounded by the ANSI escape codes to
    print it in bold.
    :param s: string to console format as bold
    :type s: str
    :returns: s surrounded by ANSI color escapes for green text
    :rtype: str
    """
    return '\x1b[1m' + s + '\x1b[0m'


def vscode_path(path: str) ->str:
    """VSCode will only recognize source locations if the path contains a slash; add "./" to plain file names."""
    if '/' in path or '<' in path or '>' in path:
        return path
    return './' + path


def display_ville(villes, screen, bv, pygame):
    """
    Dessine les villes à l'écran.
    """
    color = 255, 0, 0
    color2 = 0, 255, 0
    for v in villes:
        pygame.draw.circle(screen, color, (int(v[0]), int(v[1])), 5)
    v = villes[bv]
    pygame.draw.circle(screen, color2, (int(v[0]), int(v[1])), 5)


def _labels_to_state(scan_label, compscan_label):
    """Use scan and compscan labels to derive basic state of antenna."""
    if not scan_label or scan_label == 'slew':
        return 'slew'
    if scan_label == 'cal':
        return 'track'
    return 'track' if compscan_label == 'track' else 'scan'


def knife_project(cut_through: bool=False):
    """Use other objects outlines & boundaries to project knife cuts

    :param cut_through: Cut through, Cut through all faces, not just visible ones
    :type cut_through: bool
    """
    pass


def get_storage_path_from_infos(infos):
    """ path is stored behind name= """
    file_infos = infos.split(';')
    return file_infos[1].split('name=')[-1]


def normalize_global_config_param(key):
    """Normalize a global config key. Does not check validity of the key.

    :param str key: User-supplied global config key
    :return: The normalized key formatted as an attribute of :class:`.LDAP`
    :rtype: str
    """
    key = key.upper()
    if not key.startswith('DEFAULT_'):
        key = 'DEFAULT_' + key
    return key


def to_digital(d, num):
    """
    进制转换，从10进制转到指定机制
    :param d:
    :param num:
    :return:
    """
    if not isinstance(num, int) or not 1 < num < 10:
        raise ValueError('digital num must between 1 and 10')
    d = int(d)
    result = []
    x = d % num
    d = d - x
    result.append(str(x))
    while d > 0:
        d = d // num
        x = d % num
        d = d - x
        result.append(str(x))
    return ''.join(result[::-1])


def abbr_week_month_day_str(adatetime):
    """
    Return a string consists of abbreviated weekday, abbreviated month,
    date with no leading zero, and without a year
    e.g., Mon, Jun 2. No punctuation is shown for
    the abbreviated weekday and month.
    """
    return '{} {:d}'.format(adatetime.strftime('%a, %b'), adatetime.day)


def key(text):
    """Return a collation key for the given text.
        """


def create_django_request_object(roles, query_string, method, user_id=None,
    body=None, http_host=None):
    """Create a Django HTTPRequest object using JWT for auth.

    Args:
        roles: roles used to cosntruct the JWT for authorization.
        qeuery_string: a query string like `?user=1`
        method: A http verb like 'get'.
        user_id: The id of the user making the request, used in the JWT.
        body: Data passed to the request.
        http_host: The DNS name of the requestor.

    Returns:
        HttpRequest object.
    """
    from django.http import HttpRequest, QueryDict
    from zc_common.jwt_auth.utils import jwt_encode_handler
    if not http_host:
        http_host = 'local.zerocater.com'
    jwt_payload = {'roles': roles}
    if user_id:
        jwt_payload['id'] = user_id
    request = HttpRequest()
    request.encoding = 'utf-8'
    request.GET = QueryDict(query_string)
    request.query_params = QueryDict(query_string)
    request._read_started = False
    if body:
        request.raw_body = body
    request.method = method.upper()
    request.META = {'HTTP_AUTHORIZATION': 'JWT {}'.format(
        jwt_encode_handler(jwt_payload)), 'QUERY_STRING': query_string,
        'HTTP_HOST': http_host, 'CONTENT_TYPE': 'application/vnd.api+json',
        'CONTENT_LENGTH': '99999'}
    return request


def get_example_rules_bubble():
    """an example in .bubble format"""
    example = """
>>> is the separator for rule configurations

only lines containing two,three,for,five or six '>>>' are parsed as rules
everthing else is ignored and can be used as comments

like to transform this:
 {
            "in": "Hello, Pulling in Hello:0"
 },
to:
 {
            "out": "Hello, Pulling in Hello:0"
 },

with a rule function, see [[rule_functions]].

you just have to create this rule
>>>in>>>replace_hello_with_goodbye>>>out>>>

>>>in,'1','10','2'>>>slicing>>>slice_1_10_2>>>
>>>in,'3' >>>slicing>>>slice_3>>>
>>>in,'4','8' >>>slicing>>>slice_4-8>>>
>>>'42',in>>>in>>>.we have found the answer>>>
>>>.we have found the answer:"what's the question?">>> >>>answer_found>>>

this is not a rule, but rules can be represent like this
>i> >f> >o> >d> >n> >>>
i=input
f=function
o=output
d=depend
n=name
for more on writing rules, [[rule_definitions]]
"""
    return example


def _store_s_exons(subexon_df, seq, subexon, gene, s_exon_id):
    """
    Store s-exon information in subexon_df.

    s_exon_id is the ID of the orthologous exonic region (s-exon) created as
    Cluster_ColCluster.
    """
    seq = seq.replace('-', '')
    length = len(seq)
    query = (subexon_df['SubexonIndex'] == subexon) & (subexon_df['GeneID'] ==
        gene)
    value = subexon_df.loc[query, 'S_exons'].unique()[0]
    if '_' in value:
        subexon_df.loc[query, 'S_exons'] += '/{}'.format(s_exon_id)
        subexon_df.loc[query, 'S_exon_Lengths'] += '/{}'.format(length)
        subexon_df.loc[query, 'S_exon_Sequences'] += '/{}'.format(seq)
    else:
        subexon_df.loc[query, 'S_exons'] = s_exon_id
        subexon_df.loc[query, 'S_exon_Lengths'] = str(length)
        subexon_df.loc[query, 'S_exon_Sequences'] = seq


@staticmethod
def update_controller(controller_widget, control_name, control_instance, *
    args, **kwarg):
    """ Update one element of the controller.

        At the end the controller trait value with the name 'control_name'
        will match the controller widget user parameters defined in
        'control_instance'.

        Parameters
        ----------
        controller_widget: ControllerWidget (mandatory)
            a controller widget that contains the controller we want to update
        control_name: str(mandatory)
            the name of the controller widget control we want to synchronize
            with the controller
        control_instance: QFrame (mandatory)
            the instance of the controller widget control we want to
            synchronize with the controller
        """
    control_instance.controller_widget.update_controller()


def paste():
    """Paste the material settings and nodes

    """
    pass


@classmethod
def get_transactions(cls, address):
    """Gets the ID of all transactions related to an address.

        :param address: The address in question.
        :type address: ``str``
        :raises ConnectionError: If all API services fail.
        :rtype: ``list`` of ``str``
        """
    for api_call in cls.GET_TRANSACTIONS_MAIN:
        try:
            return api_call(address)
        except cls.IGNORED_ERRORS:
            pass
    raise ConnectionError('All APIs are unreachable.')


@classmethod
def retrieve(cls, id):
    """Makes create request for an object."""
    return cls.request(method='get', path=[id])


def primitive_nurbs_surface_sphere_add(radius: float=1.0, view_align: bool=
    False, enter_editmode: bool=False, location: float=(0.0, 0.0, 0.0),
    rotation: float=(0.0, 0.0, 0.0), layers: bool=(False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False, False, False, False, False)):
    """Construct a Nurbs surface Sphere

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


def detach_role_policy(iam, policy_arn, role_name):
    """
    Detach a managed policy (specified by ARN) from a role (specified by
    friendly name).
    """
    return iam.get_response('DetachRolePolicy', {'PolicyArn': policy_arn,
        'RoleName': role_name})


def escape_ntfs_invalid(name):
    """
    Escapes characters which are forbidden in NTFS, but are not in ext4.
    :param name: Path potentially containing forbidden NTFS characters.
    :return: Path with forbidden NTFS characters escaped.
    """
    prefix = ''
    if name[1] == ':':
        prefix = name[:2]
        name = name[2:]
    return prefix + name.replace('*', '#002A').replace('|', '#007C').replace(
        ':', '#003A').replace('>', '#003E').replace('<', '#003C').replace('?',
        '#003F').replace('"', '#0022')


@classmethod
def from_data(cls, data, targets=None, feature_names=None, static=True):
    """
    Converts two arrays or a sparse matrix data and its associated target array to Dataset.

    Parameters
    ----------
    data : array or scipy 2-D sparse matrix of shape [n_samples, n_features]
    targets : array of shape [n_samples], optional
    feature_names : array of shape [n_features], optional
    """
    if hasattr(data, 'todense'):
        return cls.from_matrix(data, targets, feature_names, static)
    else:
        return cls.from_array(data, targets, feature_names, static)


def p_value_list(p):
    """value_list : value_list COMMA value"""
    p[0] = p[1] + [p[3]]


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

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


def add_trace(variable, mode, callback):
    """
    Add trace to variable.

    Ensure compatibility with old and new trace method.
    mode: "read", "write", "unset" (new syntax)
    """
    try:
        return variable.trace_add(mode, callback)
    except AttributeError:
        return variable.trace(mode[0], callback)


def _pipe_segment_with_colons(align, colwidth):
    """Return a segment of a horizontal line with optional colons which
    indicate column's alignment (as in `pipe` output format)."""
    w = colwidth
    if align in ['right', 'decimal']:
        return '-' * (w - 1) + ':'
    elif align == 'center':
        return ':' + '-' * (w - 2) + ':'
    elif align == 'left':
        return ':' + '-' * (w - 1)
    else:
        return '-' * w


def clean_non_printable_char(m):
    """Strip non printable characters."""
    code = int(m.group(0)[1:], 16)
    if code < 20:
        return ''
    return m.group(0)


def cropx(image, minx, maxx):
    """ Crop image down to columns minx to maxx. """
    imagelecian = image.splitlines()
    nuvoimage = ''
    for imagelecian_item in imagelecian:
        nuvoimage += imagelecian_item[minx:maxx] + '\n'
    return nuvoimage


@staticmethod
def should_pickle(k):
    """
        Checks to see if key 'k' should be included in pickling.  Currently allows all entries in instance dictionary
        except for 'trajectory'

        :param k:
        :return:
        """
    return k not in set(['trajectory', 'calc_future'])


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv',
        'node_modules', 'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['prefer_module_from_imports'] = False
    prefs['split_imports'] = False
    prefs['pull_imports_to_top'] = True
    prefs['sort_imports_alphabetically'] = False
    prefs['type_hinting_factory'
        ] = 'rope.base.oi.type_hinting.factory.default_type_hinting_factory'


def _prep_crypto_msg(message):
    """Split the signature and certificate in the same way M2Crypto does.

    M2Crypto is dropping newlines into its signature and certificate. This
    exists purely to maintain backwards compatibility.

    Args:
        message (dict): A message with the ``signature`` and ``certificate`` keywords.
            The values of these two keys must be byte strings.

    Returns:
        dict: The same message, but with the values of ``signature`` and ``certificate``
            split every 76 characters with a newline and a final newline at the end.
    """
    signature = message['signature']
    certificate = message['certificate']
    sliced_signature, sliced_certificate = [], []
    for x in range(0, len(signature), 76):
        sliced_signature.append(signature[x:x + 76])
    for x in range(0, len(certificate), 76):
        sliced_certificate.append(certificate[x:x + 76])
    message['signature'] = u'\n'.join(sliced_signature) + u'\n'
    message['certificate'] = u'\n'.join(sliced_certificate) + u'\n'
    return message


def format_version(version, how):
    """
    Version string formatter for loosening version requirements.

    :version: [str] the version strings.
    :how: [str|bool] how to format the version.

    :returns: [str] formatted version string
    """
    _how = str(how).lower()
    allowed = 'full', 'major', 'minor', 'none'
    if _how not in allowed:
        raise ValueError('Argument `how` only accepts the following values: {}'
            .format(allowed))
    n = version.count('.')
    if n == 0 or _how == 'full':
        return version
    if n == 1:
        major, minor = version.split('.')
        subs = ''
    if n >= 2:
        major, minor, subs = version.split('.', 2)
    if _how == 'major':
        return major + '.*'
    if _how == 'minor':
        if not subs:
            return '{0}.{1}'.format(major, minor)
        return '{0}.{1}.*'.format(major, minor)
    return version


@classmethod
def tip_offset(cls, used=0):
    """
        Returns the x, y, z offset for a tip position, incremented by the
        number of tips previously used.
        """
    return cls.coordinates(cls._position_in_sequence(used))


def makeBiDirectional(d):
    """
    Helper for generating tagNameConverter
    Makes dict that maps from key to value and back
    """
    dTmp = d.copy()
    for k in d:
        dTmp[d[k]] = k
    return dTmp


def qs_to_qsl(qs):
    """Generator converting a result of ``parse_qs`` back to name-value pairs.

    .. versionadded:: 5.0
    """
    for k, vs in qs.items():
        for v in vs:
            yield k, v


def load_tsv(filename, cell_axis='row', delimiter='\t', gene_names=True,
    cell_names=True, sparse=False, **kwargs):
    """magic.io is deprecated. Please use scprep.io instead.
       Read more at http://scprep.readthedocs.io/
    """
    raise RuntimeError(
        'magic.io is deprecated. Please use scprep.io instead. Read more at http://scprep.readthedocs.io'
        , FutureWarning)


def unquote_header_value(value, is_filename=False):
    """Unquotes a header value.  (Reversal of :func:`quote_header_value`).
    This does not use the real unquoting but what browsers are actually
    using for quoting.

    :param value: the header value to unquote.
    """
    if value and value[0] == value[-1] == '"':
        value = value[1:-1]
        if not is_filename or value[:2] != '\\\\':
            return value.replace('\\\\', '\\').replace('\\"', '"')
    return value


@classmethod
def parse(cls, buf, options=None):
    """
        According to Philip, an abuf is like a TARDIS: it's bigger on the inside
        """
    error = []
    do_header = True
    do_question = True
    do_answer = True
    do_authority = True
    do_additional = True
    do_options = True
    if options and isinstance(options, dict):
        if 'DO_Header' in options and not options['DO_Header']:
            do_header = options['DO_Header']
        if 'DO_Question' in options and not options['DO_Question']:
            do_question = options['DO_Question']
        if 'DO_Answer' in options and not options['DO_Answer']:
            do_answer = options['DO_Answer']
        if 'DO_Authority' in options and not options['DO_Authority']:
            do_authority = options['DO_Authority']
        if 'DO_Additional' in options and not options['DO_Additional']:
            do_additional = options['DO_Additional']
        if 'DO_Options' in options and not options['DO_Options']:
            do_options = options['DO_Options']
    dnsres = {}
    offset = 0
    offset, hdr = cls._parse_header(buf, offset, error)
    if do_header:
        dnsres['HEADER'] = hdr
    for i in range(hdr['QDCOUNT']):
        res = cls._do_query(buf, offset, error)
        if res is None:
            e = ('additional', offset,
                '_do_query failed, additional record %d' % i)
            error.append(e)
            dnsres['ERROR'] = error
            return dnsres
        offset, qry = res
        if do_question:
            if i == 0:
                dnsres['QuestionSection'] = [qry]
            else:
                dnsres['QuestionSection'].append(qry)
    for i in range(hdr['ANCOUNT']):
        res = cls._do_rr(buf, offset, error, hdr)
        if res is None:
            e = 'additional', offset, '_do_rr failed, additional record %d' % i
            error.append(e)
            dnsres['ERROR'] = error
            return dnsres
        offset, rr = res
        if do_answer:
            if i == 0:
                dnsres['AnswerSection'] = [rr]
            else:
                dnsres['AnswerSection'].append(rr)
    for i in range(hdr['NSCOUNT']):
        res = cls._do_rr(buf, offset, error, hdr)
        if res is None:
            e = 'additional', offset, '_do_rr failed, additional record %d' % i
            error.append(e)
            dnsres['ERROR'] = error
            return dnsres
        offset, rr = res
        if do_authority:
            if i == 0:
                dnsres['AuthoritySection'] = [rr]
            else:
                dnsres['AuthoritySection'].append(rr)
    for i in range(hdr['ARCOUNT']):
        res = cls._do_rr(buf, offset, error, hdr)
        if res is None:
            e = 'additional', offset, '_do_rr failed, additional record %d' % i
            error.append(e)
            dnsres['ERROR'] = error
            return dnsres
        offset, rr = res
        if do_options:
            if 'EDNS0' in rr:
                dnsres['EDNS0'] = rr['EDNS0']
                continue
        if do_additional:
            if 'AdditionalSection' in dnsres:
                dnsres['AdditionalSection'].append(rr)
            else:
                dnsres['AdditionalSection'] = [rr]
    hdr['ReturnCode'] = cls._rcode_to_text(hdr['ReturnCode'])
    if offset < len(buf):
        e = 'end', offset, 'trailing garbage, buf size = %d' % len(buf)
        error.append(e)
        dnsres['ERROR'] = error
    return dnsres


@classmethod
def from_document(cls, document):
    """
        Load a specification from some Python objects.

        :param dict document: An object like the one that might be created by
            parsing a Swagger JSON specification string.
        """
    return cls(_behaviors={}, _pclasses={}, **document)


def to_dict(obj):
    """Convert a dictionary-like object to a dictionary.

    >>> to_dict({'key': 42})
    {'key': 42}

    >>> to_dict("key=42")
    {'key': '42'}

    >>> to_dict("key")
    {'key': None}

    >>> to_dict(None)
    {}

    """
    if isinstance(obj, dict):
        return obj
    elif isinstance(obj, str):
        text = obj.strip()
        parts = text.split('=')
        if len(parts) == 2:
            return {parts[0]: parts[1]}
        else:
            return {text: None}
    else:
        try:
            return obj.__dict__
        except AttributeError:
            return {}


def get_type(stmt):
    """Gets the immediate, top-level type of the node.
    TODO: Add get_prefixed_type method to get prefixed types.
    """
    type_obj = stmt.search_one('type')
    return getattr(type_obj, 'arg', None)


def _file_iter_range(fp, offset, bytes, maxread=1024 * 1024):
    """ Yield chunks from a range in a file. No chunk is bigger than maxread."""
    fp.seek(offset)
    while bytes > 0:
        part = fp.read(min(bytes, maxread))
        if not part:
            break
        bytes -= len(part)
        yield part


def col_isbool(df, col_name=None):
    """ Returns a list of columns that are of type 'bool'. If col_name is specified, returns
    whether the column in the DataFrame is of type 'bool' instead.
    Parameters:
    df - DataFrame
        DataFrame to check
    col_name - string, default None
        If specified, this function will True if df[col_name] is of type 'bool'
    """
    col_list = df.select_dtypes(include='bool').columns
    if col_name is None:
        return col_list
    else:
        return col_name in col_list


def trunc(s, length):
    """Truncate a string to a given length.

    The string is truncated by cutting off the last (length-4) characters
    and replacing them with ' ...'
    """
    if s and len(s) > length:
        return s[:length - 4] + ' ...'
    else:
        return s


@classmethod
def check_string(cls, label, value, non_empty=False):
    """Checks if the given value is a string."""
    if value is None:
        return None
    if not isinstance(value, str):
        if non_empty:
            raise ValueError('{0} must be a non-empty string.'.format(label))
        raise ValueError('{0} must be a string.'.format(label))
    if non_empty and not value:
        raise ValueError('{0} must be a non-empty string.'.format(label))
    return value


def is_numeric(value):
    """
    Indicate whether the specified string represents a numeric value.

    :param: a supposed string representation of a numeric value.

    :return: `True` if the specified string represents a numeric value;
        `False` otherwise.
    """
    try:
        float(value)
        return True
    except ValueError:
        return False


@classmethod
def load(cls, filename):
    """
        Load a staj file, returning an MlayerModel object
        """
    fin = open(filename, 'r')
    lines = fin.readlines()
    fin.close()
    self = cls()
    try:
        self._parse(lines)
    except:
        raise ValueError('Improper staj file')
    return self


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

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

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


@classmethod
def expected_string(cls, dialect=None, called_from=None):
    """Return the expected string for this segment."""
    return ''


@classmethod
def load(cls, context, compiled_net, batch_index):
    """Load precomputed data into nodes of `compiled_net`.

        Parameters
        ----------
        context : ComputationContext
        compiled_net : nx.DiGraph
        batch_index : int

        Returns
        -------
        net : nx.DiGraph
            Loaded net, which is the `compiled_net` that has been loaded with data that
            can depend on the batch_index.

        """
    raise NotImplementedError


def make_string_pep440_compatible(raw_str):
    """
    pep440 only allows a subset of characters in the
    version name:

    - alphanumeric
    - dots

    this will restrict the string to that set.
    """
    final_chars = []
    for r in raw_str:
        if 'a' <= r <= 'z' or 'A' <= r <= 'Z' or '0' <= r <= '9' or r == '.':
            final_chars.append(r)
    return ''.join(final_chars)


@staticmethod
def _update_dict(data, default_data, replace_data=False):
    """Update algorithm definition type dictionaries"""
    if not data:
        data = default_data.copy()
        return data
    if not isinstance(data, dict):
        raise TypeError('Value not dict type')
    if len(data) > 255:
        raise ValueError('More than 255 values defined')
    for i in data.keys():
        if not isinstance(i, int):
            raise TypeError('Index not int type')
        if i < 0 or i > 255:
            raise ValueError('Index value out of range')
    if not replace_data:
        data.update(default_data)
    return data


def le(h):
    """
	Little-endian, takes a 16b number and returns an array arrange in little
	endian or [low_byte, high_byte].
	"""
    h &= 65535
    return [h & 255, h >> 8]


@classmethod
def _from_remote_redis(cls) ->(str, str):
    """ Class Factory Method that builds the connector handlers an Amazon AWS s3 remote store."""
    _module_name = 'ds_connectors.handlers.redis_handlers'
    _handler = 'RedisPersistHandler'
    return _module_name, _handler


def chunk(n, chunksize):
    """
    Write a new chuncker here that just spits out how much to read
    so I can go:
    f.seek(0)
    for c in chunk(f.nframes, 1000):
        f.read(c)
    and not go beyond the edge of the file
    >>> list(new_chunk(10, 3))
    [3, 3, 3, 1]
    >>> sum(new_chunk(10, 3))
    10
    """
    i = 0
    while i + chunksize < n:
        yield chunksize
        i += chunksize
    yield n - i


@staticmethod
def p_ref_unit(p):
    """ref_unit : REF_UNIT IDENT"""
    p[0] = p[2]


def _check_prob_and_prob_vector(predictions):
    """
    Check that the predictionsa are either probabilities of prob-vectors.
    """
    from .._deps import numpy
    ptype = predictions.dtype
    import array
    if ptype not in [float, numpy.ndarray, array.array, int]:
        err_msg = 'Input `predictions` must be of numeric type (for binary '
        err_msg += 'classification) or array (of probability vectors) for '
        err_msg += 'multiclass classification.'
        raise TypeError(err_msg)


def _current_sc_dir(sc_dir, grid):
    """Return current direction(s) for semicoarsening.

    Semicoarsening is defined in `self.sc_dir`. Here `self.sc_dir` is checked
    with which directions can actually still be halved, and depending on that,
    an adjusted `sc_dir` is returned for this particular grid.

    Parameters
    ----------
    grid : :class:`emg3d.meshes.TensorMesh`
        Input grid.

    sc_dir : int
        Direction of semicoarsening.

    Returns
    -------
    c_sc_dir : int
        Current direction of semicoarsening.

    """
    xsc_dir = grid.nCx % 2 != 0 or grid.nCx < 3 or sc_dir == 1
    ysc_dir = grid.nCy % 2 != 0 or grid.nCy < 3 or sc_dir == 2
    zsc_dir = grid.nCz % 2 != 0 or grid.nCz < 3 or sc_dir == 3
    if xsc_dir:
        if ysc_dir:
            c_sc_dir = 6
        elif zsc_dir:
            c_sc_dir = 5
        else:
            c_sc_dir = 1
    elif ysc_dir:
        if zsc_dir:
            c_sc_dir = 4
        else:
            c_sc_dir = 2
    elif zsc_dir:
        c_sc_dir = 3
    else:
        c_sc_dir = 0
    return c_sc_dir


def rect_to_quad(Rect):
    """
    Utility method to convert a Rect to a QuadPoint
    """
    return [Rect[0], Rect[1], Rect[2], Rect[1], Rect[0], Rect[3], Rect[2],
        Rect[3]]


def _send_c_echo_rq(event):
    """Logging handler for when a C-ECHO-RQ is sent.

    **C-ECHO Request Parameters**

    | (M) Message ID
    | (M) Affected SOP Class UID

    Parameters
    ----------
    event : events.Event
        The evt.EVT_DIMSE_SENT event that occurred.
    """
    pass


def make_unique_node(graph, name):
    """ Add as much postfix-'_' to `name` as necessary to make unique name for new node in `graph`.

    Parameters
    ----------
    graph : nx.Graph
        graph, for which the node is created.
    name : str
        name of new node.

    Returns
    -------
    Resulting name. Composed from `name` and possibly several '_'-characters.
    """
    if name not in graph:
        return name
    ctr = 1
    while True:
        name_ = name + '_' * ctr
        if name_ not in graph:
            return name_
        ctr += 1


@staticmethod
def contexts_in_a_and_not_b(*, a_context, b_context):
    """Return the contexts in a and not in b."""
    to_return = {}
    for tool, context in a_context.items():
        if tool not in b_context:
            to_return[tool] = context
    return to_return


@classmethod
def get_namespace(cls, target, path):
    """Return a namespace with given target and path, create if needed."""
    path_, namespaces = cls.__get_helper(target, path)
    try:
        return namespaces[path_]
    except KeyError:
        if len(path) == 1:
            parent = {}
        else:
            parent = cls.get_namespace(target, path[:-1])
        return namespaces.setdefault(path_, cls.premake(path[-1], parent))


@classmethod
def epoch_to_dttm(cls) ->str:
    """
        SQL expression that converts epoch (seconds) to datetime that can be used in a
        query. The reference column should be denoted as `{col}` in the return
        expression, e.g. "FROM_UNIXTIME({col})"

        :return: SQL Expression
        """
    raise NotImplementedError()


def set_safe_paths(list_of_paths):
    """ Set list of safe writeable paths """
    global _SAFE_PATHS
    _SAFE_PATHS = list_of_paths


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


def search_bufr_msg_format(descriptors):
    """
    Search for common bufr message format in descriptors
    """
    common_descriptors = [309052, 309053, 309055, 309056, 309057]
    for descriptor in descriptors:
        if descriptor in common_descriptors:
            return descriptor
    return None


def entrance_beveled_orifice(Di, do, l, angle):
    """Returns loss coefficient for a beveled or chamfered orifice entrance to
    a pipe flush with the wall of a reservoir, as shown in [1]_.

    .. math::
        K = 0.0696\\left(1 - C_b\\frac{l}{d_o}\\right)\\lambda^2 + \\left(\\lambda
        -\\left(\\frac{d_o}{D_i}\\right)^2\\right)^2

    .. math::
        \\lambda = 1 + 0.622\\left[1-C_b\\left(\\frac{l}{d_o}\\right)^{\\frac{1-
        (l/d_o)^{0.25}}{2}}\\right]

    .. math::
        C_b = \\left(1 - \\frac{\\Psi}{90}\\right)\\left(\\frac{\\Psi}{90}
        \\right)^{\\frac{1}{1+l/d_o}}

    .. figure:: fittings/flush_mounted_beveled_orifice_entrance.png
       :scale: 30 %
       :alt: Beveled orifice entrace mounted straight; after [1]_

    Parameters
    ----------
    Di : float
        Inside diameter of pipe, [m]
    do : float
        Inside diameter of orifice, [m]
    l : float
        Length of bevel measured parallel to the pipe length, [m]
    angle : float
        Angle of bevel with respect to the pipe length, [degrees]

    Returns
    -------
    K : float
        Loss coefficient [-]

    Examples
    --------
    >>> entrance_beveled_orifice(Di=0.1, do=.07, l=0.003, angle=45)
    1.2987552913818574

    References
    ----------
    .. [1] Rennels, Donald C., and Hobart M. Hudson. Pipe Flow: A Practical
       and Comprehensive Guide. 1st edition. Hoboken, N.J: Wiley, 2012.
    """
    Cb = (1 - angle / 90.0) * (angle / 90.0) ** (1.0 / (1 + l / do))
    lbd = 1 + 0.622 * (1 - Cb * (l / do) ** ((1 - (l / do) ** 0.25) / 2.0))
    return 0.0696 * (1 - Cb * l / do) * lbd ** 2 + (lbd - (do / Di) ** 2) ** 2


def ExceptionToUnicode(exception):
    """
    Python 3 exception handling already deals with string error messages. Here we
    will only append the original exception message to the returned message (this is automatically done in Python 2
    since the original exception message is added into the new exception while Python 3 keeps the original exception
    as a separated attribute
    """
    messages = []
    while exception:
        messages.append(str(exception))
        exception = exception.__cause__ or exception.__context__
    return '\n'.join(messages)


def _set_int(src_dict, dst_proto, attr_name):
    """ Setter for a simple integer """
    setattr(dst_proto, attr_name, int(src_dict[attr_name]))


def where(ol, value):
    """
        ol = [0, 4, 6, 8, 10, 14]
        where(ol,-1)
        where(ol,1)
        where(ol,2)
        where(ol,3)
        where(ol,4)
        where(ol,9)
        where(ol,14)
        where(ol,17)
    """
    si = None
    ei = None
    for i in range(0, ol.__len__()):
        ele = ol[i]
        if value > ele:
            si = i
        elif value == ele:
            return i, i
        else:
            ei = i
            return si, ei
    return si, ei


def get_first_tarfile_member(tar_file):
    """
    Returns a file like object of the first member of the given tarfile.

    :param tar_file: The tarfile object to get the first member of
    :type tar_file: tarfile.TarFile

    :return: A file like object containing the data of the first member in the given tarfile

    :raise AssertionError: If the given tar file does not contain members
    """
    member = tar_file.next()
    if member is None:
        raise AssertionError('Given tarfile does not contain a member')
    return tar_file.extractfile(member)


@classmethod
def exists(cls, client, fingerprint, alias=False):
    """Determine whether an image exists.

        If `alias` is True, look up the image by its alias,
        rather than its fingerprint.
        """
    try:
        if alias:
            client.images.get_by_alias(fingerprint)
        else:
            client.images.get(fingerprint)
        return True
    except cls.NotFound:
        return False


def launch_piece_letter_to_number(letters):
    """Convert 24 upper case letter 3-letter code to integer, omitting I (eye) and O (oh) from the alphabet.

    The TLE standard is 24 upper case letter 3-letter code, omitting I (eye) and O (oh) from the alphabet,
    with no representation for zero.

    The 1st piece of a launch is denoted by 'A', and subsequent pieces 'B', 'C', 'D'... 'Z'.
    The 25th (24*1 + 1) piece would be denoted by 'AA', and subsequent pieces 'AB', 'AC'... 'AZ', 'BA', BB', 'BC',... 'ZZ'.
    The 601st (24*24 + 24 + 1) piece would be denoted by 'AAA', and subsequent pieces, 'AAB', 'AAC'... AZZ', 'BAA', 'BAB'... 'ZZZ'
    This allows for a maximum of 24^3 + 24^2 + 24 pieces, or 14424 pieces for a single launch (ZZZ)

    Receives

    """
    letters = letters.strip()
    dictionary = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7,
        'H': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13, 'P': 14, 'Q':
        15, 'R': 16, 'S': 17, 'T': 18, 'U': 19, 'V': 20, 'W': 21, 'X': 22,
        'Y': 23, 'Z': 24}
    base = len(dictionary)
    strlen = len(letters)
    if 9 <= strlen <= 11:
        letters = letters[8:].strip()
        strlen = len(letters)
    if strlen == 1:
        number = dictionary[letters]
    elif strlen == 2:
        first_number = dictionary[letters[0]]
        second_number = dictionary[letters[1]]
        number = first_number * base + second_number
    elif strlen == 3:
        first_number = dictionary[letters[0]]
        second_number = dictionary[letters[1]]
        third_number = dictionary[letters[2]]
        number = (first_number * base * base + second_number * base +
            third_number)
    else:
        return False
    return number


def getHierarchy(unique_name):
    """Returns a IHierarchy in the cube with the given unique name."""


@classmethod
def write(cls, stuff, is_error=False):
    """Writes to text log"""
    try:
        cls._actually_write(stuff, is_error)
    except AttributeError:
        cls.initialize_logger()
        cls._actually_write(stuff, is_error)


@staticmethod
def calculate_new_length(gene_split, gene_results, hit):
    """
            Function for calcualting new length if the gene is split on
            several contigs
        """
    first = 1
    for split in gene_split[hit['sbjct_header']]:
        new_start = int(gene_results[split]['sbjct_start'])
        new_end = int(gene_results[split]['sbjct_end'])
        if first == 1:
            new_length = int(gene_results[split]['HSP_length'])
            old_start = new_start
            old_end = new_end
            first = 0
            continue
        if new_start < old_start:
            new_length = new_length + (old_start - new_start)
            old_start = new_start
        if new_end > old_end:
            new_length = new_length + (new_end - old_end)
            old_end = new_end
    return new_length


def toggle(btn, tog=[0]):
    """
    a list default argument has a fixed address
    """
    tog[0] = not tog[0]
    if not tog[0]:
        return False
    else:
        return True


def unlink():
    """Unlink active font data-block

    """
    pass


def _add(lhs=None, rhs=None, out=None, name=None, **kwargs):
    """Adds arguments element-wise.

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

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

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

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

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


def get_station(seedid):
    """Station name from seed id"""
    return seedid.rsplit('.', 2)[0]


def get_defrange(def_node):
    """
    def_node:    An ast.FunctionDefinition node with start/end position annotations
                 from the asttokens library.
    """
    def_startline = def_node.first_token.start[0] - 1
    def_endline = def_node.last_token.end[0]
    defrange = [def_startline, def_endline]
    return defrange


@classmethod
def metadata(cls, sobject):
    """
        Extract the metadata from a suds object.
        @param sobject: A suds object
        @type sobject: L{Object}
        @return: The object's metadata
        @rtype: L{sudsobject.Metadata}
        """
    return sobject.__metadata__


def time(h: int, m: int, s: int) ->dict:
    """Creates the dictionary describing time with given parameters.

    :param h: Hour
    :param m: Minute
    :param s: Second
    :return: {Time: str}
    """
    t = f'{str(h).zfill(2)}:{str(m).zfill(2)}:{str(s).zfill(2)}'
    return {'Time': t}


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


def _explode_fields(model, model_json):
    """
    Handles traversing relationships if there are `__` in the JSON key
    """
    json_dict = {}
    for field in model_json.keys():
        if '__' in field:
            val = model_json[field]
            related_model_field_name = field.split('__')[0]
            RelatedModel = model._meta.get_field(related_model_field_name
                ).related_model
            related_filter = field.replace(related_model_field_name + '__', '')
            related_model = RelatedModel.objects.get(**{related_filter: val})
            json_dict[related_model_field_name] = related_model
        else:
            json_dict[field] = model_json[field]
    return json_dict


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

        :param AllowDownloadEnabledType val:
        :rtype: EventType
        """
    return cls('allow_download_enabled', val)


def normalize(x, lower, upper):
    """
    Normalize an array to a given bound interval
    """
    import numpy
    x_max = numpy.max(x)
    x_min = numpy.min(x)
    m = (upper - lower) / (x_max - x_min)
    x_norm = m * (x - x_min) + lower
    return x_norm


def index_height(index):
    """Returns the height based on the index of the crossing in an entry
    of a planar diagram; the 0th and 2nd indices are under crossings,
    and the 1st and 3rd are over crossings.

    """
    if index in (0, 2):
        return -1.0
    return 1.0


@staticmethod
def _get_my_optional_vals(results, *items):
    """
        Get results[key] if key in results, return a list.
        valid *items*: [(key, class or (cls1, cls2), default_val), ...]
            class: str, int, float, list, dict, ...
        """
    vals = []
    for key, cls, default in items:
        _val = results.get(key, default)
        if not isinstance(_val, cls):
            _val = default
        vals.append(_val)
    return vals


def copy_username(apps, schema_editor):
    """
    Copies the exercise name to the original name field
    """
    Ingredient = apps.get_model('nutrition', 'Ingredient')
    for ingredient in Ingredient.objects.all():
        if ingredient.user:
            ingredient.license_author = ingredient.user.username
        else:
            ingredient.license_author = 'wger.de'
        ingredient.save()


def get_client_ip_address(request):
    """
    @summary: get client ip address
    """
    return request.META.get('X-Forwarded-For', request.META['REMOTE_ADDR'])


def poll():
    """Called periodically to poll for projects"""


def new_instance(adapter):
    """
        Create a new instance for use in a new MVCC storage.
        """


def streaming_service_matches(video, streaming_service=None, **kwargs):
    """Whether the video matches the `streaming_service`.

    :param video: the video.
    :type video: :class:`~subliminal.video.Video`
    :param str streaming_service: the video streaming service
    :return: whether there's a match
    :rtype: bool

    """
    return (video.streaming_service and streaming_service == video.
        streaming_service)


def path_allowed(path, rules):
    """Checks whether the given rules allow visiting the given path.

    Parameters:

    path
        URL path component.
        Must not contain percent-encoded values other than `%2f` (`/`).
    rules
        Rules as returned by `lookup_robots_rules`.

    Returns:

    allowed
        `True` iff `path` is allowed by `rules`.
    """
    result = True
    longest = 0
    for allow, prefix in rules:
        if path.startswith(prefix) and len(prefix) > longest:
            result = allow
            longest = len(prefix)
    return result


def predict_state(posterior, state_transition):
    """The prior given the previous posterior density and a transition
    matrix indicating the state at the next time step.
    """
    return state_transition @ posterior


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


def delete_duplicates(seq, key=lambda x: x):
    """Remove all duplicate elements from `seq`.

    Two items ``x`` and ``y`` are considered equal (duplicates) if
    ``key(x) == key(y)``.  By default `key` is the identity function.

    Works with any sequence that supports `len`:func:,
    `~object.__getitem__`:meth:, and `addition <object.__add__>`:meth:.

    .. note:: ``seq.__getitem__`` should work properly with slices.

    The return type will be the same as that of the original sequence.

    .. versionadded:: 1.5.5

    .. versionchanged:: 1.7.4 Added the `key` argument. Clarified the
       documentation: `seq` should also implement the ``__add__`` method and
       that its ``__getitem__`` method should deal with slices.

    """
    i, done = 0, set()
    while i < len(seq):
        k = key(seq[i])
        if k not in done:
            done.add(k)
            i += 1
        else:
            seq = seq[:i] + seq[i + 1:]
    return seq


@classmethod
def get_element_type(cls):
    """
        Returns the element type for this vertex.

        @returns: str

        """
    return cls._type_name(cls.element_type)


def modifier_copy(modifier: str=''):
    """Duplicate modifier at the same position in the stack

    :param modifier: Modifier, Name of the modifier to edit
    :type modifier: str
    """
    pass


def get_period_freqstr(period):
    """Get the period `freqstr` attribute from a Period object."""
    return period.freqstr


def simple_round(fl, prec):
    """Rounds a fl to prec precision."""
    return round(fl, prec)