def convert_stubs_to_parents(asns, db):
    """Converts all stubs to parents.

    For our data, stub ASes have the same data as there parents. Because
    of this, we do not store stub data, and instead copy it from the
    parents.
    """
    list_of_asns = []
    sql = 'SELECT * FROM stubs WHERE stub_asn=%s'
    for asn in asns:
        results = db.execute(sql, [asn])
        if len(results) == 0:
            list_of_asns.append(asn)
        else:
            list_of_asns.append(results[0]['parent_asn'])
    return list_of_asns


@staticmethod
def format_time(secs):
    """ Formats a number of seconds as `minutes:seconds`.

        Returns:
            `str`: The formatted time, with 2+ digits for minutes and 2 digits for seconds.
        """
    return '{:02}:{:02}'.format(*divmod(secs, 60))


def strip_text_after_string(txt, junk):
    """ used to strip any poorly documented comments at the end of function defs """
    if junk in txt:
        return txt[:txt.find(junk)]
    else:
        return txt


def exponent(attrs, inputs, cls):
    """Elementwise exponent of input array."""
    return 'exp', attrs, inputs


def plural(singular, plural, seq):
    """Selects a singular or plural word based on the length of a sequence.

    Parameters
    ----------
    singlular : str
        The string to use when ``len(seq) == 1``.
    plural : str
        The string to use when ``len(seq) != 1``.
    seq : sequence
        The sequence to check the length of.

    Returns
    -------
    maybe_plural : str
        Either ``singlular`` or ``plural``.
    """
    if len(seq) == 1:
        return singular
    return plural


@classmethod
def httpdate(cls, dt):
    """Return a string representation of a date according to RFC 1123
        (HTTP/1.1).

        The supplied date must be in UTC.
        """
    weekday = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][dt.weekday()]
    month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
        'Oct', 'Nov', 'Dec'][dt.month - 1]
    return '%s, %02d %s %04d %02d:%02d:%02d GMT' % (weekday, dt.day, month,
        dt.year, dt.hour, dt.minute, dt.second)


def get_function_handle(method, var):
    """
    Return a function handle to a given calculation method.

    Parameters
    ----------
    method : str
        Identifier of the calculation method to return a handle to.
    var : dict
        Local variables needed in the sigma method.

    Returns
    -------
    f_handle : function
        Handle to the calculation method defined in this globals scope.

    """
    return globals()['wrap_calculate_using_' + method](var)


@classmethod
def get_aggregations_fields(cls, params):
    """ Recursively get values under the 'field' key.

        Is used to get names of fields on which aggregations should be
        performed.
        """
    fields = []
    for key, val in params.items():
        if isinstance(val, dict):
            fields += cls.get_aggregations_fields(val)
        if key == 'field':
            fields.append(val)
    return fields


def ZCache_get(ob, view_name, keywords, mtime_func, default):
    """ Fetch a cache entry for 'ob'.

        o If an object provides different views that would benefit from
          caching, it will set 'view_name', which should be treated as
          part of the cache key.  It defaults to the empty string.

        o 'keywords', if passed, will be a mapping containing keys that
          distinguish this cache entry from others even though
          'ob' and 'view_name' are the same;  the value should thus be
          part of the key for the entry.  DTMLMethods use keywords
          derived from the DTML namespace.

        o When the Cache calls 'ob.ZCacheable_getModTime',
          it should pass 'mtime_func' as an argument.  It is provided to
          allow cacheable objects to provide their own computation
          of the object's modification time.

        o If no matching entry is found, return 'default'.
        """


@staticmethod
def fix_string(string: str) ->str:
    """
        Replace ' with `.

        :param string:  The string to process.
        :return:        The processed string.
        """
    return string.replace("'", '`')


@staticmethod
def get_quota_policy(response_content):
    """Get quota policy from HTTP response."""
    quota = []
    if response_content != '':
        if 'QPS' in list(response_content.keys()):
            quota.qps = response_content['QPS']
        if 'ThroughPut' in list(response_content.keys()):
            quota.thoughPut = response_content['ThoughPut']
        return quota
    return None


def get_distance(pos1, pos2):
    """
    Given two X, Y, Z centers in format from output of get_center() function
    using standard three dimensional distance formula:

    square root (X^2 + Y^2 + Z^2)

    :param pos1: string of format 'X, Y, Z' Where X, Y, Z are numbers
    :param pos2: string of format 'X, Y, Z' Where X, Y, Z are numbers
    :return: distance as a float
    """
    _dist_0 = float(pos1.split(',')[0]) - float(pos2.split(',')[0])
    _dist_1 = float(pos1.split(',')[1]) - float(pos2.split(',')[1])
    _dist_2 = float(pos1.split(',')[2]) - float(pos2.split(',')[2])
    return (_dist_0 ** 2 + _dist_1 ** 2 + _dist_2 ** 2) ** 0.5


def save_fem(results, rootname):
    """Save dictionary of FEM results to individual HDF5 files.

    Parameters
    ----------
    results : Dictionary
        Results of FEM analysis performed on s
    rootname : str
        Root name for output files. '_FEM_Parameter.hdf5' will be appended

    Examples
    --------
    >>> import pixstem.fem_tools as femt
    >>> s = ps.dummy_data.get_fem_signal()
    >>> fem_results = s.fem_analysis(
    ...     centre_x=50,
    ...     centre_y=50,
    ...     show_progressbar=False)
    >>> femt.save_fem(fem_results,'TestData')

    """
    for i in results:
        results[i].save(rootname + '_FEM_' + i + '.hdf5')


def distribute(total, objects):
    """Generator for (count, object) tuples that distributes count evenly among
    the provided objects"""
    for index, obj in enumerate(objects):
        start = index * total // len(objects)
        stop = (index + 1) * total // len(objects)
        yield stop - start, obj


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Junction` from a :code:`junction` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Junction`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


@classmethod
def get_auto_email_field_tmpl(cls, attr_name):
    """
        Use this method to get the tmpl you need to create in order to use
        the auto-generated tmpl paths. Examples:

        >>> model = YourNotiClass
        >>> model.get_auto_email_field_tmpl('email_subject_tmpl')
        >>> model.get_auto_email_field_tmpl('email_plaintext_body_tmpl')
        >>> model.get_auto_email_field_tmpl('email_html_body_tmpl')

        """
    suffix = '%s_suffix' % attr_name
    template = '%s/templates/%s/emails/%s%s' % (cls._meta.app_label, cls.
        _meta.app_label, cls.model_tmpl_part, getattr(cls, suffix, ''))
    return template


def mergeUnitCompare(a, b):
    """
    _mergeUnitCompare_

    Compare two merge units.  They will be sorted first by run ID and then by
    lumi ID.
    """
    if a['run'] > b['run']:
        return 1
    elif a['run'] == b['run']:
        if a['lumi'] > b['lumi']:
            return 1
        elif a['lumi'] == b['lumi']:
            return 0
        else:
            return -1
    else:
        return -1


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 dictionary_from_betters(sequential_matchs, globalthreshold):
    """
    create a dictionary that you put node from ontology1 and give node from ontology2 assigned by betters.
    """
    dictionary_sq = {}
    for i in range(len(sequential_matchs)):
        if sequential_matchs[i][2] >= globalthreshold:
            dictionary_sq.update({sequential_matchs[i][0]:
                sequential_matchs[i][1]})
    return dictionary_sq


def get_terminal_title(editor):
    """
    Return the terminal title,
    e.g.: "filename.py (/directory) - Pyvim"
    """
    eb = editor.current_editor_buffer
    if eb is not None:
        return '%s - Pyvim' % (eb.location or '[New file]',)
    else:
        return 'Pyvim'


def indexOf(a, b):
    """Return the first index of b in a."""
    for i, j in enumerate(a):
        if j == b:
            return i
    else:
        raise ValueError('sequence.index(x): x not in sequence')


def clear(ring=u'_system'):
    """Clear all keys on a given ring. By default the system ring
        is cleader.  If None is used as ring id all rings are cleared.
        """


def index(x, y):
    """Convert (x, y) coordinates to tiles index."""
    return int((x + 200) // 50 + (y + 200) // 50 * 8)


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


def print_bloch_sphere_data(**kwargs):
    """
    Prints an error message.
    """
    print('print_bloch_sphere_data not available on this version.')


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

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

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

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

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

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


def IMI(df, open='Open', close='Close'):
    """
    Intraday Momentum Index
    Returns: list of floats = jhta.IMI(df, open='Open', close='Close')
    Source: https://www.fmlabs.com/reference/default.htm?url=IMI.htm
    """
    imi_list = []
    upsum = 0.0
    downsum = 0.0
    for i in range(len(df[close])):
        if df[close][i] > df[open][i]:
            upsum = upsum + (df[close][i] - df[open][i])
        else:
            downsum = downsum + (df[open][i] - df[close][i])
        imi = 100 * (upsum / (upsum + downsum))
        imi_list.append(imi)
    return imi_list


def hflip(x):
    """flip batch of images horizontally"""
    return x.flip(3)


def fixernames(ui):
    """Returns the names of [fix] config options that have suboptions"""
    names = set()
    for k, v in ui.configitems(b'fix'):
        if b':' in k:
            names.add(k.split(b':', 1)[0])
    return names


def _var_key(var):
    """Key for representing a primary variable, for looking up slots.

    In graph mode the name is derived from the var shared name.
    In eager mode the name is derived from the var unique id.
    If distribution strategy exists, get the primary variable first.

    Arguments:
        var: the variable.

    Returns:
        the unique name of the variable.
    """
    if getattr(var, '_distributed_container', None) is not None:
        var = var._distributed_container()
    if var._in_graph_mode:
        return var._shared_name
    return var._unique_id


def _convert_value(v):
    """
    Returns 0 if v is not specified, otherwise try int
    """
    if v:
        try:
            v = int(v)
            return v
        except ValueError:
            return v
    return 0


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``CanvasSettingsPanel`` is only intended to be added to
        :class:`.OrthoPanel`, :class:`.LightBoxPanel`, or
        :class:`.Scene3DPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    from fsleyes.views.lightboxpanel import LightBoxPanel
    from fsleyes.views.scene3dpanel import Scene3DPanel
    return [OrthoPanel, LightBoxPanel, Scene3DPanel]


def parameter_equality(param):
    """Function to force two model parameters to be equal in the optimization"""
    return param


def get_keras_loss(loss_name):
    """
    Fetches built in tensorflow losses

    :param loss_name: The name of the loss to fetch
    :return: A vanilla Keras loss function
    """
    from tensorflow.keras import losses
    return getattr(losses, loss_name)


def parse_lowercase_headers(headers):
    """makes the headers lower case
    :param HTTPMessage headers:
    :return dict:
    """
    response_headers = {}
    for header_pair in headers.items():
        name = header_pair[0].lower()
        value = header_pair[1]
        if name == 'set-cookie' and name in response_headers:
            response_headers[name] = '{};{}'.format(response_headers[name],
                value)
        else:
            response_headers[name] = value
    return response_headers


def user_too_big_message(user_login: str):
    """Create an user_too_big_message."""
    return {'message': f'User {user_login} has too many repositories',
        'error': 'Too big'}


def get_jvm_class(cl):
    """Builds JVM class name from Python class
    """
    return 'org.apache.{}.{}'.format(cl.__module__[2:], cl.__name__)


def binary_search(item, list):
    """
    This function is an implementation of a binary search

    Parameters:
    item, list

    Returns:
    True or False depending if the item is found or not
    """
    found = False
    counter = 0
    bottom_of_list = 0
    top_of_list = len(list) - 1
    while bottom_of_list <= top_of_list and not found:
        middle_of_list = (bottom_of_list + top_of_list) // 2
        if list[middle_of_list] == item:
            found = True
        elif item > list[middle_of_list]:
            bottom_of_list = middle_of_list + 1
        else:
            top_of_list = middle_of_list - 1
        counter += 1
    print(' Number of searches before finding the item: ' + str(counter))
    return found


@classmethod
def from_response(cls, response, attrs):
    """ Create an index from returned Dynamo data """
    proj = response['Projection']
    index = cls(proj['ProjectionType'], response['IndexName'], attrs[
        response['KeySchema'][1]['AttributeName']], proj.get(
        'NonKeyAttributes'))
    index.response = response
    return index


def arithm_expr_target(x, target):
    """ Create arithmetic expression approaching target value
    :param x: allowed constants
    :param target: target value
    :returns: string in form 'expression=value'
    :complexity: huge
    """
    n = len(x)
    expr = [{} for _ in range(1 << n)]
    for i in range(n):
        expr[1 << i] = {x[i]: str(x[i])}
    all_ = (1 << n) - 1
    for S in range(3, all_ + 1):
        if expr[S] != {}:
            continue
        for L in range(1, S):
            if L & S == L:
                R = S ^ L
                for vL in expr[L]:
                    for vR in expr[R]:
                        eL = expr[L][vL]
                        eR = expr[R][vR]
                        expr[S][vL] = eL
                        if vL > vR:
                            expr[S][vL - vR] = '(%s-%s)' % (eL, eR)
                        if L < R:
                            expr[S][vL + vR] = '(%s+%s)' % (eL, eR)
                            expr[S][vL * vR] = '(%s*%s)' % (eL, eR)
                        if vR != 0 and vL % vR == 0:
                            expr[S][vL // vR] = '(%s/%s)' % (eL, eR)
    for dist in range(target + 1):
        for sign in [-1, +1]:
            val = target + sign * dist
            if val in expr[all_]:
                return '%s=%i' % (expr[all_][val], val)
    pass


def __pickle_method__(m):
    """
    Pickling override for using pickle with instance methods.
    """
    if m.im_self is None:
        return getattr, (m.im_class, m.im_func.func_name)
    else:
        return getattr, (m.im_self, m.im_func.func_name)


def encode_content(encoding='gzip', lazy=False):
    """ Encode the content with the given encoding (only gzip and
        identity are supported)."""


@staticmethod
def bold(text):
    """Bold text converter.

        :param text: a text string.
        :type text: str
        :return: a string like this example: ``'**text**'``
        :rtype: str"""
    return '**' + text + '**'


def dict_repr_html(dictionary):
    """
    Jupyter Notebook magic repr function.
    """
    rows = ''
    s = '
{k}	{v}
'
    for k, v in dictionary.items():
        rows += s.format(k=k, v=v)
    html = '
{}
'.format(rows)
    return html


@staticmethod
def is_end_rule() ->bool:
    """Whether the rule is an end rule or not

        Returns
        ----------
        is_end : bool
            Whether the rule is an end rule or not
        """
    return False


def orf_sorter(orf):
    """Sorting function for the ORFs."

    :param orf: an ORF to sort
    :type orf: Mikado.serializers.orf.Orf
    """
    return (orf.cds_len, orf.has_start_codon and orf.has_stop_codon, orf.
        has_start_codon or orf.has_stop_codon)


@classmethod
def component_list(cls, options=None):
    """List components attached to the content view"""
    cls.command_sub = 'component list'
    return cls.execute(cls._construct_command(options), output_format='csv')


@classmethod
def list(cls, context, filters=None):
    """Return a list of ControlpathID objects."""
    if filters:
        sort_dir = filters.pop('sort_dir', 'desc')
        sort_key = filters.pop('sort_key', 'created_at')
        limit = filters.pop('limit', None)
        marker = filters.pop('marker_obj', None)
        db_cps = cls.dbapi.control_path_get_by_filters(context, filters,
            sort_dir=sort_dir, sort_key=sort_key, limit=limit, marker=marker)
    else:
        db_cps = cls.dbapi.control_path_list(context)
    obj_cp_list = cls._from_db_object_list(db_cps, context)
    return obj_cp_list


@classmethod
def get_parent_field_names(cls):
    """
        Get a list of the names of parent fields for the current model.
        """
    if cls.parent_field is None:
        return []
    return [cls.parent_field]


def _extract_user_from_git_blame_info(info):
    """As this tool is meant to be used in an enterprise setting, we assume
    that the email address of the committer uniquely identifies a given user.

    This function extracts that information.
    """
    info = info.split()
    index_of_mail = info.index('author-mail')
    email = info[index_of_mail + 1]
    index_of_at_symbol = email.index('@')
    return email[1:index_of_at_symbol]


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 split_negations(iterable, func=str):
    """"Split an iterable into negative and positive elements.

    Args:
        iterable: iterable targeted for splitting
        func: wrapper method to modify tokens

    Returns:
        Tuple containing negative and positive element tuples, respectively.
    """
    neg, pos = [], []
    for token in iterable:
        if token[0] == '-':
            if len(token) == 1:
                raise ValueError("'-' negation without a token")
            token = token[1:]
            l = neg
        else:
            l = pos
        obj = func(token)
        if obj is not None:
            l.append(obj)
    return tuple(neg), tuple(pos)


def IntbitsetCmp(x, y):
    """Compare two intbitsets."""
    if x is None or y is None:
        return False
    else:
        return x == y


def getResult(simplaceInstance, output, simulation):
    """Get a specific output of a finished simulation."""
    return simplaceInstance.getResult(output, simulation)


@staticmethod
def plural_fmt(name, cnt):
    """
        pluralize name if necessary and combine with cnt
        :param name: str name of the item type
        :param cnt: int number items of this type
        :return: str name and cnt joined
        """
    if cnt == 1:
        return '{} {}'.format(cnt, name)
    else:
        return '{} {}s'.format(cnt, name)


@staticmethod
def supportedViews():
    """Overrides :meth:`.ControlMixin.supportedViews`. The
        ``OverlayDisplayToolBar`` is only intended to be added to
        :class:`.OrthoPanel`, :class:`.LightBoxPanel`, or
        :class:`.Scene3DPanel` views.
        """
    from fsleyes.views.orthopanel import OrthoPanel
    from fsleyes.views.lightboxpanel import LightBoxPanel
    from fsleyes.views.scene3dpanel import Scene3DPanel
    return [OrthoPanel, LightBoxPanel, Scene3DPanel]


def nextFromRP(rp, N=1):
    """
    I{Transaction magic.}
    """
    try:
        if N == 1:
            result = rp.fetchone()
        else:
            result = rp.fetchmany(N)
    except:
        result = []
    if result:
        return result
    raise StopIteration


def forward_checking(csp, var, value, assignment, removals):
    """Prune neighbor values inconsistent with var=value."""
    csp.support_pruning()
    for B in csp.neighbors[var]:
        if B not in assignment:
            for b in csp.curr_domains[B][:]:
                if not csp.constraints(var, value, B, b):
                    csp.prune(B, b, removals)
            if not csp.curr_domains[B]:
                return False
    return True


def get_json_event_start(event_buffer):
    """ get the event start of an event that is different (in time)from the
        adjoining event, in XML format """
    event_start_pattern = '{"_cd":"'
    time_key_pattern = '"_time":"'
    time_end_pattern = '"'
    event_end_pattern = '"},\n'
    event_end_pattern2 = '"}[]'
    event_start = event_buffer.find(event_start_pattern)
    event_end = event_buffer.find(event_end_pattern, event_start) + len(
        event_end_pattern)
    if event_end < 0:
        event_end = event_buffer.find(event_end_pattern2, event_start) + len(
            event_end_pattern2)
    if event_end < 0:
        return -1, -1, ''
    time_start = event_buffer.find(time_key_pattern, event_start) + len(
        time_key_pattern)
    time_end = event_buffer.find(time_end_pattern, time_start + 1)
    last_time = event_buffer[time_start:time_end]
    event_start = event_end
    while event_end > 0:
        event_start = event_buffer.find(event_start_pattern, event_start + 1)
        event_end = event_buffer.find(event_end_pattern, event_start) + len(
            event_end_pattern)
        if event_end < 0:
            event_end = event_buffer.find(event_end_pattern2, event_start
                ) + len(event_end_pattern2)
        if event_end < 0:
            return -1, -1, ''
        time_start = event_buffer.find(time_key_pattern, event_start) + len(
            time_key_pattern)
        time_end = event_buffer.find(time_end_pattern, time_start + 1)
        this_time = event_buffer[time_start:time_end]
        if this_time != last_time:
            return event_start - 2, event_end, last_time
        event_start = event_end
    return -1, -1, ''


@staticmethod
def _has_data(data):
    """
        Returns True if data has any valid content.
        :param dict data: The response data as provided by self.__request
        :return bool:
        """
    return len(data.get('payload', {}).get('data', {})) > 0


@classmethod
def close(cls):
    """Close browser gracefully.
        """
    return cls.build_send_payload('close', {}), None


def coerce_entity_dict(v):
    """Coerce entity ID strings to a dictionary with key "entity"."""
    if isinstance(v, str):
        return {'entity': v}
    return v


def filled(f, d):
    """
        Check if a field exists in a dictionary, and if that field is not None or the empty string.
    """
    return f in d and d[f] is not None and d[f] != ''


@classmethod
def json_delete(cls, url, **kwargs):
    """ Helper for DELETE json request """
    return cls.json_call('DELETE', url, **kwargs)


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    Deprecated LOG.warn(), instead use LOG.warning
    https://bugs.launchpad.net/senlin/+bug/1508442

    N352
    """
    msg = 'N352: LOG.warn is deprecated, please use LOG.warning!'
    if 'LOG.warn(' in logical_line:
        yield 0, msg


def exempt_from_requirements(f):
    """
    Used to exempt a route handler from ambient requirement handling unless it
    is explicitly decorated with a requirement runner::

        @bp.route('/')
        @exempt_from_requirements
        def greeting_area():
            return "Hello!"

    To use with a class based view, apply it to the class level decorators
    attribute::

        class SomeCBV(View):
            decorators = [exempt_from_requirements]

            def get(self):
                return "Hello!"

    .. note::

        You cannot exempt individual methods of a class based view with this
        decorator, e.g. the follow will not work::

            class SomeCBV(MethodView):

                @exempt_from_requirements
                def get(self):
                    return "Hello!"

        Any permissioning applied at the blueprint level would still affect
        this route.

    :param f: The route handler to be decorated.

    .. versionadded:: 0.7.0
    """
    f.__allows_exempt__ = True
    return f


def minimal_interactive_cli_bootstrap(client):
    """
    This is something you usually implement yourself to ask your user in a nice, user-friendly way about these things.
    This is mainly included to keep examples in the documentation simple and allow you to get started quickly.
    """
    if not client.get_current_tan_mechanism():
        client.fetch_tan_mechanisms()
        mechanisms = list(client.get_tan_mechanisms().items())
        if len(mechanisms) > 1:
            print('Multiple tan mechanisms available. Which one do you prefer?'
                )
            for i, m in enumerate(mechanisms):
                print(i, 'Function {p.security_function}: {p.name}'.format(
                    p=m[1]))
            choice = input('Choice: ').strip()
            client.set_tan_mechanism(mechanisms[int(choice)][0])
    if client.is_tan_media_required() and not client.selected_tan_medium:
        print(
            "We need the name of the TAN medium, let's fetch them from the bank"
            )
        with client:
            m = client.get_tan_media()
        if len(m[1]) == 1:
            client.set_tan_medium(m[1][0])
        else:
            print('Multiple tan media available. Which one do you prefer?')
            for i, mm in enumerate(m[1]):
                print(i,
                    'Medium {p.tan_medium_name}: Phone no. {p.mobile_number_masked}, Last used {p.last_use}'
                    .format(p=mm))
            choice = input('Choice: ').strip()
            client.set_tan_medium(m[1][int(choice)])


def create_userblocks_instance(sender, instance, created, raw, **kwargs):
    """
    Create a |UserBlocks| for newly created |User|.

    .. seealso::
        :data:`~django.db.models.signals.post_save` built-in signal.
    """
    from friends.models import UserBlocks
    if created and not raw:
        UserBlocks.objects.create(user=instance)


def read_lines(file, predicate=None, encoding=None, errors=None):
    """Read and return the content of the file as a list of lines.

    Line breaks are not included in the resulting list.

    If ``predicate`` is given, it must be a callable that takes a single
    line as its argument and returns a bool. Only the lines for which
    ``True`` is returned are included in the result.

    :param file: path to file or file descriptor
    :type file: :term:`path-like object` or int
    :param predicate: predicate function
    :type predicate: callable(str)
    :param str encoding: name of the encoding
    :param str errors: error handler
    :return: list of lines
    :rtype: list(str)
    :raises OSError: on I/O failure

    .. versionchanged:: 0.6.0
       Add parameter ``errors``
    """
    result = []
    with open(file, encoding=encoding, errors=errors) as fh:
        for line in fh:
            line = line.rstrip('\n')
            if not predicate or predicate(line):
                result.append(line)
    return result


def is_ascii(some_string):
    """Check if a string only contains ascii characters"""
    try:
        some_string.encode('ascii')
    except UnicodeEncodeError:
        return False
    else:
        return True


def div_roundup(a, b):
    """ Return a/b rounded up to nearest integer,
    equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
    without possible floating point accuracy errors.
    """
    return (int(a) + int(b) - 1) // int(b)


def in_punctuation(category):
    """Category for code points that are punctuation characters.

    Args:
        category (str): Unicode general category.

    Returns:
        bool: True if `category` in set.
    """
    return category in {'Pc', 'Pd', 'Ps', 'Pe', 'Pi', 'Pf', 'Po'}


def pairwise(seq):
    """
    Pair an iterable, e.g., (1, 2, 3, 4) -> ((1, 2), (2, 3), (3, 4))
    """
    for i in range(0, len(seq) - 1):
        yield seq[i], seq[i + 1]


def _applyargs(args, f):
    """Apply arguments to a function.

    Args can be any of the following.
    arg
    (arg1, arg2, ...)
    ((arg1a, arg1b, ...), ...)
    """
    if not hasattr(args, '__iter__'):
        f(args)
    else:
        f(*args)
    return


@classmethod
def rev_parse(cls, git, revision):
    """Parse revision string."""
    start, is_range, stop = revision.partition('..')
    if not is_range:
        start, stop = None, start
    elif not stop:
        stop = 'HEAD'
    return cls(start=git.rev_parse(start) if start else None, stop=git.
        rev_parse(stop))


def get_query_class(method):
    """Get class of query strategy from its name.

    Arguments
    ---------
    method: str
        Name of the query strategy, e.g. 'max', 'uncertainty', 'random.
        A special mixed query strategy is als possible. The mix is denoted
        by an underscore: 'max_random' or 'max_uncertainty'.

    Returns
    -------
    BaseQueryModel:
        Class corresponding to the method name.
    """
    from asreview.query_strategies.cluster import ClusterQuery
    from asreview.query_strategies.max import MaxQuery
    from asreview.query_strategies.uncertainty import UncertaintyQuery
    from asreview.query_strategies.random import RandomQuery
    from asreview.query_strategies.mixed import MixedQuery
    query_models = {'cluster': ClusterQuery, 'max': MaxQuery, 'uncertainty':
        UncertaintyQuery, 'random': RandomQuery}
    try:
        return query_models[method]
    except KeyError:
        mix = method.split('_')
        if len(mix) == 2:
            return MixedQuery
        raise ValueError(f"Error: query method '{method}' is not implemented.")


def UTCSecondToLocalDatetime(utcsec, timezone='Europe/Berlin'):
    """
    Convert utc second to local datetime (specify correct local timezone with string).

    Parameters
    ----------
    utcsec: int
      Time in utc seconds (unix time).

    timezone: string
      Time zone string compatible with pytz format

    Returns
    -------
      dt: Datetime object corresponding to local time.

    Notes
    -----
    Adapted from a stackoverflow answer.

    To list all available time zones:
    >> import pytz
    >> pytz.all_timezones

    To print the returned datetime object in a certain format:
    >> from pyik.time_conversion import UTCSecondToLocalDatetime
    >> dt = UTCSecondToLocalDatetime(1484314559)
    >> dt.strftime("%d/%m/%Y, %H:%M:%S")
    """
    import pytz
    from datetime import datetime
    local_tz = pytz.timezone(timezone)
    utc_dt = datetime.utcfromtimestamp(utcsec)
    local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz)
    return local_tz.normalize(local_dt)


def _warning(msg):
    """ display is not guaranteed here, nor it being the full class, but try anyways, fallback to sys.stderr.write """
    try:
        from ansible.utils.display import Display
        Display().warning(msg)
    except Exception:
        import sys
        sys.stderr.write(' [WARNING] %s\n' % msg)


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 view_zoom_in(location: float=(0.0, 0.0)):
    """Zoom in the view

    :param location: Location, Cursor location in screen coordinates
    :type location: float
    """
    pass


@classmethod
def modify_url_for_impersonation(cls, url, impersonate_user, username):
    """
        Modify the SQL Alchemy URL object with the user to impersonate if applicable.
        :param url: SQLAlchemy URL object
        :param impersonate_user: Bool indicating if impersonation is enabled
        :param username: Effective username
        """
    if impersonate_user is not None and username is not None:
        url.username = username


def humanizeBytes(size, precision=2):
    """
    Determine the *human readable* value of bytes on 1024 base (1KB=1024B).
    """
    s = ['B ', 'KB', 'MB', 'GB', 'TB']
    x = len(s)
    p = 0
    while size > 1024 and p < x:
        p += 1
        size = size / 1024.0
    return '%.*f %s' % (precision, size, s[p])


def ungrouped_imports(editor, item):
    """ Pylint ungrouped-imports method """
    line_no = item.line_no
    return line_no, 0


def validation_code(exit_code):
    """
    Check the exit code and pass the value to
    the dictionary containing the commit information
    :param exit_code:
    :return: validation status
    """
    if exit_code == 0:
        validated = 'yes'
        badge = 'validated-brightgreen.svg'
    elif exit_code == 1:
        validated = 'no'
        badge = 'validation failed-red.svg'
    else:
        validated = 'unknown'
        badge = 'unknown%20status-yellow.svg'
    return [validated, badge]


def sum_of_cubes(a, b):
    """
    definition: func(a, b) {...}
    objective : gives you the result of the arguments  sum of cubes
                (a+b)^3 = (a+b)(a^2 - ab + b^2)
    """
    result = (a + b) * (a * a - a * b + b * b)
    return result


def calc_quarter(y, m):
    """ Calculate previous and next month """
    prev_y = y
    prev_m = m - 1
    next_y = y
    next_m = m + 1
    if m == 1:
        prev_m = 12
        prev_y = y - 1
    elif m == 12:
        next_m = 1
        next_y = y + 1
    return [(prev_y, prev_m), (y, m), (next_y, next_m)]


def update_interface_device_hostname(apps, schema_editor):
    """Update all interfaces with hostname from associated device"""
    Device = apps.get_model('nsot', 'Device')
    for dev in Device.objects.iterator():
        dev.interfaces.update(device_hostname=dev.hostname)


def _dict_native_ok(d):
    """
    This checks if a dictionary can be saved natively as HDF5 groups.

    If it can't, it will be pickled.
    """
    if len(d) >= 256:
        return False
    for k in d:
        if not isinstance(k, str):
            return False
    return True


def _gen_identifiers():
    """ Generates sequential 32-bit notification identifiers. """
    while True:
        for i in range(2 ** 32):
            yield i


def pipe(obj, func, *args, **kwargs):
    """
    Apply a function ``func`` to object ``obj`` either by passing obj as the
    first argument to the function or, in the case that the func is a tuple,
    interpret the first element of the tuple as a function and pass the obj to
    that function as a keyword argument whose key is the value of the second
    element of the tuple.

    Parameters
    ----------
    func : callable or tuple of (callable, str)
        Function to apply to this object or, alternatively, a
        ``(callable, data_keyword)`` tuple where ``data_keyword`` is a
        string indicating the keyword of `callable`` that expects the
        object.
    *args : iterable, optional
        Positional arguments passed into ``func``.
    **kwargs : dict, optional
        A dictionary of keyword arguments passed into ``func``.

    Returns
    -------
    object : the return type of ``func``.
    """
    if isinstance(func, tuple):
        func, target = func
        if target in kwargs:
            msg = f'{target} is both the pipe target and a keyword argument'
            raise ValueError(msg)
        kwargs[target] = obj
        return func(*args, **kwargs)
    else:
        return func(obj, *args, **kwargs)


def CopyImage(canvas):
    """
    Copy the MPL canvas to the wx clipboard.
    """
    import wx
    bmp = wx.BitmapDataObject()
    bmp.SetBitmap(canvas.bitmap)
    wx.TheClipboard.Open()
    wx.TheClipboard.SetData(bmp)
    wx.TheClipboard.Close()


def calculate_default_type(arg, has_default, default_value, params_help):
    """This function looks at the default value and returns the type that
       should be supplied to the parser"""
    positional = True
    arg_params = {}
    arg_name = arg
    try:
        arg_params['help'] = params_help[arg_name]
    except KeyError:
        pass
    if has_default:
        positional = False
    if default_value in (int, float):
        positional = True
    if default_value is True:
        arg_params['action'] = 'store_false'
    elif default_value is False:
        arg_params['action'] = 'store_true'
    if type(default_value) in (int, float):
        arg_params['type'] = type(default_value)
    if positional:
        if arg_name.startswith('_'):
            arg_params['nargs'] = '?'
            arg_params['default'] = None
            arg_params['metavar'] = arg_name.lstrip('_')
    else:
        arg_params['default'] = default_value
        if len(arg_name) == 1:
            arg_name = '-' + arg_name
        else:
            arg_name = '--' + arg_name
    return arg_name, arg_params


def _setPassword(password):
    """
        Modify the password on the member object
        """


def is_number(string):
    """Returns True if this string is a string representation of a number"""
    try:
        float(string)
        return True
    except ValueError:
        return False


def initialization_GMM(n_components, points_data, points_test=None,
    covariance_type='full'):
    """
    This method returns an array of k means and an array of k covariances (dim,dim)
    which will be used in order to initialize an EM algorithm

    Parameters
    ----------
    points : an array (n_points,dim)

    k : int
        the number of clusters

    Returns
    -------
    means : an array (n_components,dim)
        The initial means computed

    cov : an array (n_components,dim,dim)
        The initial covariances computed

    log_weights : an array (n_components,)
        The initial weights (log) computed

    log_assignements : an array (n_points,n_components)
        The log of the soft assignements according to GMM

    """
    from .GMM import GaussianMixture
    GM = GaussianMixture(n_components, covariance_type=covariance_type)
    GM.fit(points_data, points_test, patience=0)
    log_assignements = GM.predict_log_resp(points_data)
    return GM.means, GM.cov, GM.log_weights, log_assignements


@classmethod
def set_db(cls, db):
    """
        if you use the set_db_path method in this library then calling set_db on
        each model is unnecessary
        """
    cls.__db = db


def checkBoundsInSolution(solution):
    """ check if flux distribution 'solution' violates any of the flux bounds
        associated with its reactions

    Returns:  lbViolations, ubViolations - {reaction : flux, bound} dicts
    """
    lbViolations, ubViolations = {}, {}
    for rea in solution:
        flux = solution[rea]
        if rea not in solution.boundsDict:
            continue
        lb, ub = solution.boundsDict[rea]
        if flux < lb:
            lbViolations[rea] = flux, lb
        elif flux > ub:
            ubViolations[rea] = flux, ub
    return lbViolations, ubViolations


def byte_ord(b):
    """
    Return the integer representation of the byte string.  This supports Python
    3 byte arrays as well as standard strings.
    """
    try:
        return ord(b)
    except TypeError:
        return b


def initialize(read_only: bool):
    """
        Reset transient information to enable reusage of the transaction
        """


def sql_dequote_string(s: str) ->str:
    """Reverses sql_quote_string."""
    if len(s) < 2:
        return s
    s = s[1:-1]
    return s.replace("''", "'")


def merge_two_dicts(x, y):
    """Given two dicts, merge them into a new dict as a shallow copy."""
    z = x.copy()
    z.update(y)
    return z


def wrap_open_close(function, object, filename, mode='rb', file_handle_name
    ='_file'):
    """Wraps the objects file handle for execution of function.

    :param function: Function to be executed during file handle wrap.
    :type function: callable

    :param object: Object having the file handle.
    :type object: object

    :param filename: Filename opened.
    :type filename: string

    :param mode: Opening mode.
    :type mode: string

    :param file_handle_name: Name of the instance variable in object.
    :type file_handle_name: string

    :return: New function which being run acts as wrapped function call.
    :rtype: function

    """
    file_handle = getattr(object, file_handle_name)
    if file_handle is not None and not file_handle.closed:
        function()
        return
    new_file_handle = open(filename, mode)
    setattr(object, file_handle_name, new_file_handle)
    function()
    new_file_handle.close()


def blue_green_mirror_env(envname):
    """
    Given a blue envname, returns its green counterpart, or vice versa.
    For other envnames that aren't blue/green participants, this returns None.
    """
    if 'blue' in envname:
        return envname.replace('blue', 'green')
    elif 'green' in envname:
        return envname.replace('green', 'blue')
    else:
        return None


def grace_corner_cases():
    """
    Read these module-level examples.
    """
    pass


def get_account_linking_access_token(handler_input):
    """Return the access token in the request.

    The method retrieves the user's ``accessToken`` from the input request.
    Once a user successfully enables a skill and links their Alexa
    account to the skill, the input request will have the user's
    access token. A `None` value is returned if there is no access token
    in the input request. More information on this can be found here :
    https://developer.amazon.com/docs/account-linking/add-account-linking-logic-custom-skill.html

    :param handler_input: The handler input instance that is generally
        passed in the sdk's request and exception components
    :type handler_input: ask_sdk_core.handler_input.HandlerInput
    :return: User account linked access token if available. None if not
        available
    :rtype: Optional[str]
    """
    return handler_input.request_envelope.context.system.user.access_token


def gcd(a: int, b: int) ->int:
    """
    Recursively computes the greatest common denominator.

    Parameters:
        a (int): First integer.
        b (int): Second integer.

    Returns:
        int: GCD of `a` and `b`.

    Examples:
        >>> from samson.math.general import gcd
        >>> gcd(256, 640)
        128

        >>> from samson.math.algebra.all import FF
        >>> from samson.math.symbols import Symbol
        >>> x = Symbol('x')
        >>> P = FF(2, 8)[x]
        >>> gcd(P(x**2), P(x**5))
        <Polynomial: x**2, coeff_ring=F_(2**8)>

    """
    while b:
        a, b = b, a % b
    return a


def _format_decimal_coords(ra, dec):
    """
    Print *decimal degree* RA/Dec values in an IPAC-parseable form
    """
    return '{0} {1:+}'.format(ra, dec)


def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)


def add_options(_parser):
    """
    Adds options to the passed in '_parser'

    :type _parser: OptionParser instance
    :param _parser: passed in parser

    :rtype: None
    :return: None
    """
    _parser.add_option('-y', '--year', dest='year', action='store', help=
        'Year for the merge')
    _parser.add_option('-m', '--month', dest='month', action='store', help=
        'Month for the merge')
    _parser.add_option('-d', '--day', dest='day', action='store', help=
        'Day for the merge')
    _parser.add_option('-D', '--directory', dest='directory', action=
        'store', help='Directory containing files to merge')
    _parser.add_option('-f', '--file', dest='file', action='store', help=
        'File containing list of input directories')
    _parser.add_option('-w', '--window', dest='window', action='store',
        help='Window in days (merge for the past *n* days')
    _parser.add_option('-l', '--lookback', dest='lookback', action='store',
        help='Lookback period (merge for 1 day *n* days prior)')
    _parser.add_option('-t', '--topic', dest='topic', action='store', help=
        'Topic for the merge')
    _parser.add_option('-i', '--input-prefix', dest='input_prefix', action=
        'store', help='Input directory prefix')
    _parser.add_option('-o', '--output-prefix', dest='output_prefix',
        action='store', help='Output directory prefix')
    _parser.add_option('-n', '--num-reducers', dest='num_reducers', action=
        'store', help='Number of reducers')
    _parser.add_option('-c', '--codec', dest='codec', action='store', help=
        'Compression codec to use')
    _parser.add_option('-q', '--queue', dest='queue', action='store', help=
        'Mapreduce job queue')
    _parser.add_option('-r', '--dry-run', dest='dry_run', action=
        'store_true', default=False, help=
        'Dry run; create, but dont execute the Pig script')


def entry_type_filter(entrystream, entryclass):
    """
    Generic entry filter.

    :param entrystream: a stream of entries
    :param entryclass: specify the type of entry upon which to filter
    """
    for entry in entrystream:
        if isinstance(entry, entryclass):
            yield entry


def convert(val, in_units, to=None):
    """Converts value in certain units into other units

    """
    from .managers import energy_units
    from .managers import Manager
    m = Manager()
    with energy_units(in_units):
        e = m.convert_energy_2_internal_u(val)
    if to is None:
        ne = m.convert_energy_2_current_u(e)
    else:
        with energy_units(to):
            ne = m.convert_energy_2_current_u(e)
    return ne


def horizontal_inactive_link_mask(shape, node_status):
    """Array mask of horizontal links that are inactive."""
    is_inactive = node_status == 0
    is_inactive.shape = shape
    inactive_outlinks = is_inactive[1:-1, :-1]
    inactive_inlinks = is_inactive[1:-1, 1:]
    return inactive_outlinks | inactive_inlinks


def _format_list_items(list_items):
    """Generate an indented string out of a list of items."""
    list_string = ''
    if list_items:
        for item in list_items:
            list_string = list_string + "    '" + item + "',\n"
        list_string = '[\n    {}\n]'.format(list_string.strip()[:-1])
    else:
        list_string = '[]'
    return list_string


def filter_data(data, fields):
    """
    Removes keys in data that are not part of fields
    :param data: dict of data
    :param fields: dict representing the keys/indexes to be saved
    :return: a dict with the parsed data inside
    """
    todo = [(data, fields)]
    while len(todo) > 0:
        tofilter, tosave = todo.pop()
        tosave_list = list(tosave.keys()) if isinstance(tosave, dict
            ) else tosave
        if isinstance(tofilter, dict):
            tofilter_key_copy = list(tofilter.keys()).copy()
            for k in tofilter_key_copy:
                if k not in tosave_list:
                    tofilter.pop(k)
                elif isinstance(tosave, dict):
                    todo.append((tofilter[k], tosave[k]))
        elif isinstance(tofilter, list):
            tofilter_len = len(tofilter)
            for i in range(0, tofilter_len):
                if i not in tosave_list:
                    del tofilter[i]
                    i -= 1
                elif isinstance(tosave, dict):
                    todo.append((tofilter[i], tosave[i]))
        print('\n', tofilter)
        print(tosave)
        print(tosave_list, '\n')


def get_name(friendly=False):
    """Get name of this resource

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Service dependency'
    return 'servicedependency'


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

    :dictionary: [Dict] - Diccionario a convertir

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


def get_pgroupvolume(module, array):
    """Return Protection Group Volume or None"""
    try:
        pgroup = array.get_pgroup(module.params['name'])
        for volume in pgroup['volumes']:
            if volume == module.params['restore']:
                return volume
    except Exception:
        return None


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

        :param TeamMergeRequestRejectedShownToSecondaryTeamDetails val:
        :rtype: EventDetails
        """
    return cls('team_merge_request_rejected_shown_to_secondary_team_details',
        val)


def ones_like(x):
    """Return an array of the same shape as `x` containing only ones."""
    return x * 0.0 + 1.0


def request_contents_processor(request):
    """
    Django request contents RequestContext Handler
    """
    return {'REQUEST_CONTENTS': request.GET or request.POST}


def read_hook_hash(path):
    """Verify that the file at path is the therapist hook and return the hash"""
    with open(path, 'r') as f:
        f.readline()
        version_line = f.readline()
        if version_line.startswith('# THERAPIST'):
            return version_line.split()[2]


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_str()
    return parameters


@classmethod
def collect_metrics(cls):
    """Build the metrics reports for all configured handlers."""
    for handler in cls.handlers:
        handler.write(cls.meters)


def readVariables(src):
    """
  Reads and store NetCDF variables (type,dimensions,metadata) into dict.

  Parameters
  ----------
  src:netCDF4 object

  Returns
  -------
  dict : {id:{type,dimensions,...metadata}}
  """
    variables = {}
    for id in src.variables:
        variable = {}
        variable['type'] = src.variables[id].dtype.name
        variable['dimensions'] = list(src.variables[id].dimensions)
        for ncattr in src.variables[id].ncattrs():
            variable[ncattr] = src.variables[id].getncattr(ncattr)
        variables[id] = variable
    return variables


def spmax(a):
    """
    Maximum value in a matrix or vector to deal with sparse and dense objects

    Parameters
    ----------
    a           : array or sparse matrix
                  Object with one or more columns.

    Returns
    -------
    max a       : int or float
                  maximum value in a
    """
    return a.max()


def display_init_libraries_folder(root):
    """display function for creating new libraries folder"""
    print('Created libraries directory at %s' % root)


def _check_list(str_or_list):
    """ If `str_or_list` is a list will return it as it is. If it is a str, will return a
    list with the str inside.

    Parameters
    ----------
    str_or_list: str or list

    Returns
    -------
    list
    """
    if str_or_list is None:
        return None
    if isinstance(str_or_list, list):
        return str_or_list
    if isinstance(str_or_list, str):
        return [str_or_list]
    raise ValueError('Expected a `str` or a `list`, got {}.'.format(type(
        str_or_list)))


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

    """
    pass


def jbig2Encode(stream, parameters):
    """
        Method to encode streams using the JBIG2 standard (NOT IMPLEMENTED YET)

        @param stream: A PDF stream
        @return: A tuple (status,statusContent), where statusContent is the encoded PDF stream in case status = 0 or an error in case status = -1
    """
    return -1, 'Jbig2Encode not supported yet'


def upload(stream, mimetype_hint=False):
    """ Replace the current contents of this file's blob with the
        contents of ``stream``.  ``mimetype_hint`` can be any of the
        folliwing:

        - ``None``, meaning don't reset the current mimetype.  This is the
          default.

        - A string containing a filename with an extension; the mimetype will
          be derived from the extension in the filename.

        - The constant :attr:`substanced.file.USE_MAGIC`, which will derive the
          content type using the ``python-magic`` library based on the
          stream's actual content.
        """


def get_path(request):
    """Ensure we get a valid path
    """
    return request.validated.get('path', request.matchdict)


def update_authorizer(restApiId=None, authorizerId=None, patchOperations=None):
    """
    Updates an existing  Authorizer resource.
    See also: AWS API Documentation

    :example: response = client.update_authorizer(
        restApiId='string',
        authorizerId='string',
        patchOperations=[
            {
                'op': 'add'|'remove'|'replace'|'move'|'copy'|'test',
                'path': 'string',
                'value': 'string',
                'from': 'string'
            },
        ]
    )

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

    :type authorizerId: string
    :param authorizerId: [REQUIRED]
            The identifier of the Authorizer resource.

    :type patchOperations: list
    :param patchOperations: A list of update operations to be applied to the specified resource and in the order specified in this list.
            (dict) -- A single patch operation to apply to the specified resource. Please refer to http://tools.ietf.org/html/rfc6902#section-4 for an explanation of how each operation is used.
            op (string) --An update operation to be performed with this PATCH request. The valid value can be 'add', 'remove', or 'replace'. Not all valid operations are supported for a given resource. Support of the operations depends on specific operational contexts. Attempts to apply an unsupported operation on a resource will return an error message.
            path (string) --The op operation's target, as identified by a JSON Pointer value that references a location within the targeted resource. For example, if the target resource has an updateable property of {'name':'value'} , the path for this property is /name . If the name property value is a JSON object (e.g., {'name': {'child/name': 'child-value'}} ), the path for the child/name property will be /name/child~1name . Any slash ('/') character appearing in path names must be escaped with '~1', as shown in the example above. Each op operation can have only one path associated with it.
            value (string) --The new target value of the update operation. When using AWS CLI to update a property of a JSON value, enclose the JSON object with a pair of single quotes in a Linux shell, e.g., '{'a': ...}'. In a Windows shell, see Using JSON for Parameters .
            from (string) --Not supported.

    :rtype: dict
    :return: {
        'id': 'string',
        'name': 'string',
        'type': 'TOKEN'|'COGNITO_USER_POOLS',
        'providerARNs': [
            'string',
        ],
        'authType': 'string',
        'authorizerUri': 'string',
        'authorizerCredentials': 'string',
        'identitySource': 'string',
        'identityValidationExpression': 'string',
        'authorizerResultTtlInSeconds': 123
    }

    :returns:
    (string) --

    """
    pass


def base_initializer(shape, dtype, ctx, id_range):
    """The function signature for feature initializer.

    Any customized feature initializer should follow this signature (see
    example below).

    Parameters
    ----------
    shape : tuple of int
        The shape of the result features. The first dimension
        is the batch dimension.
    dtype : data type object
        The data type of the returned features.
    ctx : context object
        The device context of the returned features.
    id_range : slice
        The start id and the end id of the features to be initialized.
        The id could be node or edge id depending on the scenario.
        Note that the step is always None.

    Examples
    --------
    If PyTorch is used as backend, the following code defines an feature
    initializer that initializes tensor value to 1

    >>> import torch
    >>> import dgl
    >>> def initializer(shape, dtype, ctx, id_range):
    >>>     return torch.ones(shape, dtype=dtype, device=ctx)
    >>> g = dgl.DGLGraph()
    >>> g.set_n_initializer(initializer)

    See Also
    --------
    dgl.DGLGraph.set_n_initializer
    dgl.DGLGraph.set_e_initializer
    """
    raise NotImplementedError


def out_p2(t: float) ->float:
    """
    quadratic ease-out function

    :param t: input value in range [0,1]
    """
    return 1.0 - (1.0 - t) * (1.0 - t)


def in_notebook():
    """Check if code is being executed in a Jupyter notebook.

	:rtype: bool
	"""
    try:
        from IPython import get_ipython
    except ImportError:
        return False
    ipy = get_ipython()
    if not ipy:
        return False
    return type(ipy).__name__ == 'ZMQInteractiveShell'


def initialize_stats_dict(individual):
    """
    Initializes the stats dict for individual
    The statistics initialized are:
        'generation': generation in which the individual was evaluated. Initialized as: 0
        'mutation_count': number of mutation operations applied to the individual and its predecessor cumulatively. Initialized as: 0
        'crossover_count': number of crossover operations applied to the individual and its predecessor cumulatively. Initialized as: 0
        'predecessor': string representation of the individual. Initialized as: ('ROOT',)

    Parameters
    ----------
    individual: deap individual

    Returns
    -------
    object
    """
    individual.statistics['generation'] = 0
    individual.statistics['mutation_count'] = 0
    individual.statistics['crossover_count'] = 0
    individual.statistics['predecessor'] = 'ROOT',


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 spectrum_embedding(x, p=2, binary=False):
    """
	Computes the spectrum embedding of a seuqnce.
	The feature space contains the number of occurrences of all possible substrings

	p: the length of substructures
	binary: counts of occurrences or 1/0
	"""
    vx = {}
    for i in range(len(x) - p + 1):
        u = x[i:i + p]
        vx[u] = 1 if u not in vx or binary else vx[u] + 1
    return vx


@classmethod
def from_dict(cls, image_props):
    """Create instance from image properties dict

        :param image_props: dictionary of image metadata properties

        Creates a new object instance, initializing from a
        dictionary of image metadata properties

        :returns: an ImageMetaProps instance
        """
    obj = cls()
    obj._set_attr_from_legacy_names(image_props)
    obj._set_attr_from_current_names(image_props)
    obj._set_attr_from_trait_names(image_props)
    return obj


@classmethod
def from_string(cls, region_string):
    """
        Convert a string into a :class:`~GenomicRegion`.
        This is a very useful convenience function to quickly
        define a :class:`~GenomicRegion` object from a descriptor
        string.
        :param region_string: A string of the form
                              <chromosome>[:<start>-<end>[:<strand>]]
                              (with square brackets indicating optional
                              parts of the string). If any optional
                              part of the string is omitted, intuitive
                              defaults will be chosen.
        :return: :class:`~GenomicRegion`
        """
    chromosome = None
    start = None
    end = None
    no_space_region_string = ''.join(region_string.split())
    fields = no_space_region_string.split(':')
    if len(fields) > 3:
        raise ValueError(
            'Genomic range string must be of the form <chromosome>[:<start>-<end>:[<strand>]]'
            )
    if len(fields) > 0:
        chromosome = fields[0]
    if len(fields) > 1 and fields[1] != '':
        start_end_bp = fields[1].split('-')
        if len(start_end_bp) > 0:
            try:
                start = int(start_end_bp[0])
            except ValueError:
                raise ValueError('Start of genomic range must be integer')
        if len(start_end_bp) > 1:
            try:
                end = int(start_end_bp[1])
            except ValueError:
                raise ValueError('End of genomic range must be integer')
            if not end > start:
                raise ValueError(
                    'The end coordinate must be bigger than the start.')
    return cls(start=start, end=end, chromosome=chromosome)


@classmethod
def fromkeys(cls, iterable, *args):
    """Create a ChainMap with a single dict created from the iterable."""
    return cls(dict.fromkeys(iterable, *args))


def _process_configuration(comments):
    """Extract sampling information."""
    num_samples = None
    num_warmup = None
    save_warmup = None
    for comment in comments:
        comment = comment.strip('#').strip()
        if comment.startswith('num_samples'):
            num_samples = int(comment.strip('num_samples = ').strip(
                '(Default)'))
        elif comment.startswith('num_warmup'):
            num_warmup = int(comment.strip('num_warmup = ').strip('(Default)'))
        elif comment.startswith('save_warmup'):
            save_warmup = bool(int(comment.strip('save_warmup = ').strip(
                '(Default)')))
        elif comment.startswith('thin'):
            thin = int(comment.strip('thin = ').strip('(Default)'))
    return {'num_samples': num_samples, 'num_warmup': num_warmup,
        'save_warmup': save_warmup, 'thin': thin}


def add_user_preferences(apps, schema_editor):
    """ add UserPreference entry for each existing user """
    User = apps.get_model('auth', 'User')
    UserPreference = apps.get_model('userextensions', 'UserPreference')
    for user in User.objects.all():
        UserPreference.objects.create(user=user)


def to_unicode(s, encoding='utf-8'):
    """Convert to `unicode` string.

    :param s: String to convert.
    :param str encoding: Encoding codec.
    :return: `unicode` string, it's `unicode` in Python 2.x, `str` or `unicode` in Python 3.x.
    :rtype: unicode

    * In Python 2, convert `s` to `unicode` if it's `str` or `bytes`.
    * In Python 2, return original `s` if it's neither `str` or `bytes`.
    * In Python 3, convert `s` to `str` or `unicode` if it's `bytes`.
    * In Python 3, return original `s` if it's not `bytes`.
    * In Python 3, it equals to :func:`to_str`.
    """
    if isinstance(s, bytes):
        return s.decode(encoding)
    else:
        return s


@classmethod
def load(cls, filename):
    """
        Loads a WordDictionary object from a vocabulary file.
        """
    words = []
    with open(filename, 'rb') as f:
        for word in f:
            word = word.decode('utf-8').strip()
            if word:
                words.append(word)
    return cls.init_from_wordlist(words)


@staticmethod
def _make_test(klass, uid, description=None, subtests_filter=None, **
    test_arguments):
    """
        Create test template
        :param klass: test class
        :param uid: test uid (by default used as id and name)
        :param description: Description appended to "uid" (for listing purpose)
        :param subtests_filter: optional filter of methods for avocado tests
        :param test_arguments: arguments to be passed to the klass(test_arguments)
        """
    if subtests_filter and not subtests_filter.search(uid):
        return []
    if description:
        uid = '%s: %s' % (uid, description)
    test_arguments['name'] = uid
    return [(klass, test_arguments)]


def val_checker(val):
    """Type check of variable to pass to style functions.

	Parameters
	----------
	val : str
		String containing the value to evaluate
	Returns
	-------
	val : Recasted value
	"""
    from distutils.util import strtobool
    if "'" not in val and '"' not in val:
        try:
            val = float(val) if '.' in val else int(val)
        except ValueError:
            try:
                val = bool(strtobool(val))
            except ValueError:
                val = val
    return val


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
                "body_analyzed": {
                  "type": "text",
                  "fielddata": true,
                  "index": true
                }
           }
        } """
    return {'items': mapping}


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


def two_dec(num: float) ->str:
    """Format a floating point number with 2 decimal places."""
    return '{0:.2f}'.format(num)


def _extract_project_version(requirement):
    """
    Extract the information on a concrete project version from pkg_configs Requirement information.

    :param requirement: A pkg_config Requirement
    :return: Pair of project_name and version
    """
    specs = requirement.specs
    if len(specs) == 1:
        spec = specs[0]
        if spec[0] == '==':
            return requirement.project_name, spec[1]
        else:
            raise ValueError(
                'Versions must be specified exactly. "{}" is not an exact version specification.'
                .format(requirement))
    elif len(specs) > 1:
        raise ValueError(
            'Multiple version specifications on a single line are not supported.'
            )
    else:
        raise ValueError('Version specification is missing for "{}".'.
            format(requirement))


def bytes_to_int(value, signed=False):
    """Return integer given bytes."""
    return int.from_bytes(bytes(value), byteorder='big', signed=signed)


def type_object_attrgetter(obj, attr, *defargs):
    """
    This implements an improved attrgetter for type objects (i.e. classes)
    that can handle class attributes that are implemented as properties on
    a metaclass.

    Normally `getattr` on a class with a `property` (say, "foo"), would return
    the `property` object itself.  However, if the class has a metaclass which
    *also* defines a `property` named "foo", ``getattr(cls, 'foo')`` will find
    the "foo" property on the metaclass and resolve it.  For the purposes of
    autodoc we just want to document the "foo" property defined on the class,
    not on the metaclass.

    For example::

        >>> class Meta(type):
        ...     @property
        ...     def foo(cls):
        ...         return 'foo'
        ...
        >>> class MyClass(metaclass=Meta):
        ...     @property
        ...     def foo(self):
        ...         ""\"Docstring for MyClass.foo property.""\"
        ...         return 'myfoo'
        ...
        >>> getattr(MyClass, 'foo')
        'foo'
        >>> type_object_attrgetter(MyClass, 'foo')
        <property at 0x...>
        >>> type_object_attrgetter(MyClass, 'foo').__doc__
        'Docstring for MyClass.foo property.'

    The last line of the example shows the desired behavior for the purposes
    of autodoc.
    """
    for base in obj.__mro__:
        if attr in base.__dict__:
            if isinstance(base.__dict__[attr], property):
                return base.__dict__[attr]
            break
    return getattr(obj, attr, *defargs)


def print_header():
    """
    Prints the header for the normal phase of a benchmark.
    """
    print('{:<12s} {:<12s} {:<12s} ( {:<12s} )'.format('', 'user', 'system',
        'real'))


@staticmethod
def _sink_kafka():
    """Method to add kafka as sink."""
    pass


@classmethod
def record_rename(cls, old_dn, new_dn):
    """Called to indicate a change in DN.

        :param str old_dn: The old DN.

        :param str new_dn: The new DN.

        :return: None - any returned value is ignored.

        This callback happens when an entry's DN changes.

        This callback can happen in all modes, and in all phases, to indicate
        that an entry's DN has been changed.  In refresh-only mode, and the
        refresh phase of refresh-and-perist mode, the change may have taken
        place at any time since your last update.  In the persist phase of
        refresh-and-persist mode, the entry has just changed.

        You should expect a call to
        :meth:`~syncrepl_client.callbacks.BaseCallback.record_change()` shortly
        after this callback completes.
        """
    pass


def destructure(dict, keys):
    """
    Simula el comportamiento de una asignación por destructuración de js.

    :dict: [Dict] - diccionrio sobre el cual se buscaran las claves

    :keys: [List(String)] - claves requeridas

    :return: [Dict] - Diccionario con todas las claves que se encuentran
    """
    for key in keys:
        if key.__name__ in dict.keys():
            key = dict[key.__name__]


def fid(a):
    """
    The id high-order function
    @sig fid :: a -> a
    """
    return a


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 get_send_quota():
    """
    Returns the user's current sending limits.
    This action is throttled at one request per second.
    See also: AWS API Documentation

    Examples
    The following example returns the Amazon SES sending limits for an AWS account:
    Expected Output:

    :example: response = client.get_send_quota()

    :rtype: dict
    :return: {
        'Max24HourSend': 123.0,
        'MaxSendRate': 123.0,
        'SentLast24Hours': 123.0
    }

    """
    pass


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


def page_name_original_metadata(index):
    """Get the key name for the page name metadata data for the indexed tiff page

    These are TIFF IFD #'s 285+

    index - zero-based index of the page
    """
    return 'PageName #%d' % index


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

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


@classmethod
def parse(cls, string):
    """ Parse a JSON string into python objects """
    decoded = cls.DECODER(string)
    return cls.makeNative(decoded)


@classmethod
def addRootLogHandler(cls, h):
    """Adds a new handler to the root logger

           :param h: (logging.Handler) the new log handler
        """
    h.setFormatter(cls.getLogFormat())
    cls.initRoot().addHandler(h)


def primitive_plane_add(radius: float=1.0, calc_uvs: bool=False, 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 filled planar mesh with 4 vertices

    :param radius: Radius
    :type radius: float
    :param calc_uvs: Generate UVs, Generate a default UV map
    :type calc_uvs: bool
    :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 sourceToWordIds(text):
    """Return a sequence of ids of the words parsed from the text.

        The input text may be either a string or a list of strings.

        Parse the text as if they come from a source document, and
        creates new word ids for words that aren't (yet) in the
        lexicon.
        """


def loader_from_key(key):
    """Returns the name, loader pair given a key."""
    if ':' in key:
        return key.split(':')
    return key, None


def in_ipython_frontend():
    """
    Helper function which is variation of :meth:`pandas:pandas.io.formats.console.in_ipython_frontend` which
    checks to see if we are inside an IPython zmq frontend

    :return: `True` if D-Tale is being invoked within ipython notebook, `False` otherwise
    """
    try:
        from IPython import get_ipython
        ip = get_ipython()
        return 'zmq' in str(type(ip)).lower()
    except BaseException:
        pass
    return False


def cigar_conversion(cigar):
    """Convert character or integer to corresponding integer or character for the SAM/BAM formatting
    :param cigar: character or int to get corresponding CIGAR equivalent
    """
    assert type(cigar) is str or type(cigar
        ) is int, 'Cigar character must be int or str'
    chars = ['M', 'I', 'D', 'N', 'S', 'H', 'P', '=', 'X']
    if type(cigar) is str:
        assert cigar in chars, 'Character is not a cigar string character'
        return chars.index(cigar)
    else:
        assert 0 <= cigar <= 8, 'Integer must be between 0 and 8'
        return chars[cigar]


def cross3(v1, v2):
    """
    Quick convenient function to compute cross product betwee two 3-element vectors
    cross3: 326 ns | np.cross: 35.8 us
    """
    a1, a2, a3 = v1
    b1, b2, b3 = v2
    return [a2 * b3 - a3 * b2, a3 * b1 - a1 * b3, a1 * b2 - a2 * b1]


def principalPermissionGrant(principal, permission):
    """Return the principal-permission grant if any

        The return value is one of Allow, Deny, or Unset
        """


def _reshape_values(values, unique_values):
    """Reshape values into 4D array.

    :param values: Raw values data
    :type values: numpy array
    :param unique_values: Tuple of unique latitudes, longitudes and times data.
    :type unique_values: Tuple

    :returns: Reshaped values data
    :rtype: Numpy array
    """
    lats_len = len(unique_values[0])
    lons_len = len(unique_values[1])
    times_len = len(unique_values[2])
    values = values.reshape(times_len, lats_len, lons_len)
    return values


def up(f, c):
    """Find the positive values in the series.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the column ``c``.
    c : str
        Name of the column in the dataframe ``f``.

    Returns
    -------
    new_column : pandas.Series (bool)
        The array containing the new feature.

    """
    new_column = f[c] > 0
    return new_column


def translate_urls(json_home, new_prefix):
    """Given a JSON Home document, sticks new_prefix on each of the urls."""
    for dummy_rel, resource in json_home['resources'].items():
        if 'href' in resource:
            resource['href'] = new_prefix + resource['href']
        elif 'href-template' in resource:
            resource['href-template'] = new_prefix + resource['href-template']


def _is_odd(integer):
    """Helper for testing if an integer is odd by bitwise & with 1."""
    return integer & 1


@classmethod
def _from_et(cls, root, parent):
    """
        Create a :class:`Element` from a :code:`element` element.

        :param root: The element tree tree to parse.
        :param parent: :class:`EagleFilePart` that should hold the resulting :class:`EagleFilePart`
        :rtype: :class:`Element`
        """
    n = cls()
    n._init_from_et(root, parent)
    return n


def _get_int(src_proto, dst_dict, attr_name):
    """ Getter for an integer """
    dst_dict[attr_name] = int(getattr(src_proto, attr_name))


@classmethod
def loads_xml(cls, bytestring, encoding=None, **kwargs):
    """
        Currently processes "<dmrs>...</dmrs>"
        To be updated for "<dmrslist>...</dmrslist>"...
        Expects a bytestring; to load from a string instead, specify encoding
        """
    from pydmrs.serial import loads_xml
    return loads_xml(bytestring, encoding=encoding, cls=cls, **kwargs)


@classmethod
def _get_attributes(cls):
    """Get an attribute dictionary

        Returns a map of property names to attr instances (or None for default
        attribute behavior) describing the properties of the object.

        By default, this method will return the class's _ATTRIBUTES field.
        Classes can override this method to do custom initialization of the
        attributes when needed.
        """
    return cls._ATTRIBUTES


def _generate_symbol(path, width, height, command='C'):
    """Sequence generator for SVG path."""
    if len(path) == 0:
        return
    yield 'M'
    yield path[0].anchor[1] * width
    yield path[0].anchor[0] * height
    yield command
    points = zip(path, path[1:] + path[0:1]) if path.is_closed() else zip(path,
        path[1:])
    for p1, p2 in points:
        yield p1.leaving[1] * width
        yield p1.leaving[0] * height
        yield p2.preceding[1] * width
        yield p2.preceding[0] * height
        yield p2.anchor[1] * width
        yield p2.anchor[0] * height
    if path.is_closed():
        yield 'Z'


def render_preview(view_type, obj):
    """Render preview of object using this registry.

        This calls the render_preview method defined on the view found.
        """


def flush(library, session, mask):
    """Manually flushes the specified buffers associated with formatted I/O operations and/or serial communication.

    Corresponds to viFlush function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param mask: Specifies the action to be taken with flushing the buffer.
                 (Constants.READ*, .WRITE*, .IO*)
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viFlush(session, mask)


def reveal(select: bool=True):
    """Make previously hidden curves visible again in Graph Editor view

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


def height_from_height_shoulders(segment_length):
    """
    Calculates body height based on the height of the shoulders from the ground

    args:
        segment_length (float): height of the shoulders

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


def enrich_dblog_metadata(apps, _):
    """
    Add objpk and objname to the DbLog table metadata.
    """
    import json
    DbLog = apps.get_model('db', 'DbLog')
    query_set = DbLog.objects.all()
    for log in query_set.iterator():
        met = json.loads(log.metadata)
        if 'objpk' not in met:
            met['objpk'] = log.objpk
        if 'objname' not in met:
            met['objname'] = log.objname
        log.metadata = json.dumps(met)
        log.save(update_fields=['metadata'])


def _load_asset_allocation():
    """ Load asset allocation from AA library """
    from asset_allocation import AppAggregate, HtmlFormatter, AsciiFormatter
    aa = AppAggregate()
    model = aa.get_asset_allocation()
    formatter = AsciiFormatter()
    full = False
    output = formatter.format(model, full=full)
    return output


def precision_system_output(entity, partitioned_entity):
    """ Compute a spanning tree from antecedent information.

    All edges in the spanning tree correspond to anaphor-antecedent pairs. In
    order to access this antecedent information, the attribute "antecedent" of
    the mentions in the entity must be set.

    Args:
        entity (EntityGraph): The EntityGraph for the entity for which the
            spanning tree should be computed.
        partitioned_entity (EntityGraph): A partition of the entity -- not
            used for this algorithm.

    Returns:
        list(Mention, Mention): A list of mention pairs, which constitute the
        edges of the spanning tree. For a pair (m, n), n appears later in
        the text than m.
    """
    edges = []
    for mention in entity.edges:
        if 'antecedent' in mention.attributes and mention.attributes[
            'antecedent'] in entity.edges[mention]:
            edges.append((mention, mention.attributes['antecedent']))
    return sorted(edges)


def pulpDoctest():
    """
    runs all doctests
    """
    import doctest
    if __name__ != '__main__':
        from . import pulp
        doctest.testmod(pulp)
    else:
        doctest.testmod()


@classmethod
def from_xml_root(cls, root, content_language=None):
    """Wrap for selector matching the root of an XML or XHTML document.

        :param root:
            An ElementTree :class:`~xml.etree.ElementTree.Element`
            for the root element of a document.
            If the given element is not the root,
            selector matching will behave is if it were.
            In other words, selectors will be `scope-contained`_
            to the subtree rooted at that element.
        :returns:
            A new :class:`ElementWrapper`

        .. _scope-contained:
            http://dev.w3.org/csswg/selectors4/#scope-contained-selectors

        """
    return cls._from_root(root, content_language, in_html_document=False)


def add_vertex(location: float=(0.0, 0.0)):
    """Add vertex to active spline

    :param location: Location, Location of vertex in normalized space
    :type location: float
    """
    pass


def file_percentage_parser(line):
    """
    Parses lines of the following form: extracts only the seconds part

        File duration: 5248.68s (100.00%)

    :param line: string
    :return: float containing the duration for the file in percentage
    """
    is_ = line.find('(')
    ie_ = line.find('%')
    try:
        return float(line[is_ + 1:ie_])
    except:
        return 0.0


def find(projname, crstype, strict=False):
    """
    Search for a projection name located in this module.

    Arguments:

    - **projname**: The projection name to search for.
    - **crstype**: Which CRS naming convention to search (different
        CRS formats have different names for the same projection).
    - **strict** (optional): If False, ignores minor name mismatches
        such as underscore or character casing, otherwise must be exact
        match (defaults to False).
    """
    if not strict:
        projname = projname.lower().replace(' ', '_')
    for itemname, item in globals().items():
        if itemname.startswith('_'):
            continue
        try:
            if hasattr(item.name, crstype):
                itemname = getattr(item.name, crstype)
                if not strict:
                    itemname = itemname.lower().replace(' ', '_')
                if projname == itemname:
                    return item
        except:
            pass
    else:
        return None


def add_arg(func, *args, **kwargs):
    """Bind CLI arguments to a shell.py `do_foo` function."""
    if not hasattr(func, 'arguments'):
        func.arguments = []
    if (args, kwargs) not in func.arguments:
        func.arguments.insert(0, (args, kwargs))


@staticmethod
def applicable(dataset):
    """Check whether plot is applicable to the given dataset.

        Returns `True` by default and needs to be implemented in classes
        inheriting from Plotter according to their needs.

        A typical example would be a 2D plot applied to a 1D dataset that will
        most probably not be possible/sensible.

        Returns
        -------
        applicable : :class:`bool`
            `True` if successful, `False` otherwise.

        """
    return True


def get_MLUw(sents, words_to_ignore=None):
    """Mean length of utterance (MLU) in words"""
    total_utterance_count = 0
    total_word_count = 0
    for sent in sents:
        total_utterance_count += 1
        for word in sent:
            if words_to_ignore and word in words_to_ignore:
                continue
            total_word_count += 1
    if total_utterance_count:
        return total_word_count / total_utterance_count
    else:
        return 0


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


def set_global_constants(include_damping_in_qmodel_change=None):
    """Sets various global constants used by the classes in this module."""
    global _INCLUDE_DAMPING_IN_QMODEL_CHANGE
    if include_damping_in_qmodel_change is not None:
        _INCLUDE_DAMPING_IN_QMODEL_CHANGE = include_damping_in_qmodel_change


def copy_cache(records, env):
    """ Recursively copy the cache of ``records`` to the environment ``env``. """
    env.cache.copy(records, env)


def nest_list(f, expr, n):
    """
    returns the list of results of applying f to expr n times

    Parameters
    ----------
    f : function
        function to be applied.
    expr : any
        what function is to be applied to.
    n : int
        number of times f is to be applied.

    Returns
    -------
    out : list
        returns [f(expr), f(f(expr)), f(f(f(expr))), ...]

    Examples
    --------

    >>> xt.nest_list(lambda x:x//2, 1024, 10)
    [512, 256, 128, 64, 32, 16, 8, 4, 2, 1]

    >>> xt.nest_list(lambda x:x[0], [['a','b'],['c','d']], 2)
    [['a', 'b'], 'a']

    """
    end = []
    for i in range(n):
        expr = f(expr)
        end.append(expr)
    return end


def merge(reports):
    """Merge multiple report instances into one."""
    raise NotImplementedError


def busy_conf_minutes(lofp):
    """
    lofp is a list of tuples of (begin_minute, end_minute) busy times, e.g., [(b1, e1) , (b2, e2), ...]. By construction bi < ei. By sort, bi <= bi+1.
    Return list of busy intervals, list of conflict intervals, busy minutes.
    [(540, 600), (600, 720)]
    >>> busy_conf_minutes([(540, 600)])
    ([(540, 600)], [], 60)
    >>> busy_conf_minutes([(540, 600), (600, 720)])
    ([(540, 600), (600, 720)], [], 180)
    >>> busy_conf_minutes([(540, 620), (600, 720), (660, 700)])
    ([(540, 600), (620, 660), (700, 720)], [(600, 620), (660, 700)], 180)
    """
    lofp.sort()
    busy_minutes = []
    conf_minutes = []
    if not lofp:
        return [], [], 0
    b, e = lofp.pop(0)
    while lofp:
        B, E = lofp.pop(0)
        if e <= B:
            busy_minutes.append((b, e))
            b = B
            e = E
        else:
            busy_minutes.append((b, B))
            if e <= E:
                conf_minutes.append((B, e))
                b = e
                e = E
            else:
                conf_minutes.append((B, E))
                b = E
                e = e
    busy_minutes.append((b, e))
    total_minutes = 0
    for b, e in (busy_minutes + conf_minutes):
        total_minutes += e - b
    return busy_minutes, conf_minutes, total_minutes


@staticmethod
def _require_system(*args, **kwargs):
    """You need a finalized system; Use Builder.finalized() first."""
    raise TypeError(
        'You need a finalized system; use Builder.finalized() first.')


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 session_queued(method):
    """Apply this decorator to a method of class :class:`.HermesSnipsComponent`
    to register it as a callback to be triggered when the dialogue manager
    queues the current session.
    """
    method.subscribe_method = 'subscribe_session_queued'
    return method


def wavekE(wavekE):
    """Convert wavelength to energy & vise versa

    :param float waveKe:wavelength in A or energy in kE

    :returns float waveKe:the other one

    """
    return 12.397639 / wavekE


def get_user_id(conversation):
    """returns the _id used to send smooch requests"""
    return conversation['appUser']['_id']


def poke_8(library, session, address, data):
    """Write an 8-bit value from the specified address.

    Corresponds to viPoke8 function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param address: Source address to read the value.
    :param data: value to be written to the bus.
    :return: Data read from bus.
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viPoke8(session, address, data)


def to_stylesheet_color(color):
    """Utility to convert QColor to stylesheet specification"""
    return 'rgb({!r}, {!r}, {!r})'.format(color.red(), color.green(), color
        .blue())


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


def get_usage_plan(usagePlanId=None):
    """
    Gets a usage plan of a given plan identifier.
    See also: AWS API Documentation

    :example: response = client.get_usage_plan(
        usagePlanId='string'
    )

    :type usagePlanId: string
    :param usagePlanId: [REQUIRED]
            The identifier of the UsagePlan resource to be retrieved.

    :rtype: dict
    :return: {
        'id': 'string',
        'name': 'string',
        'description': 'string',
        'apiStages': [
            {
                'apiId': 'string',
                'stage': 'string'
            },
        ],
        'throttle': {
            'burstLimit': 123,
            'rateLimit': 123.0
        },
        'quota': {
            'limit': 123,
            'offset': 123,
            'period': 'DAY'|'WEEK'|'MONTH'
        },
        'productCode': 'string'
    }

    """
    pass


def _texture(number):
    """Generates ARB assembly for a texture."""
    return 'texture[{}]'.format(number)


def make_shard_endpoints(total_length, shard_size=int(1000000.0)):
    """
    Partition the half-open integer interval [0, total_length) into a
    sequence of half-open subintervals [s0,e0), [s1,e1), ... [s_n, e_n)
    such that s0 = 0, s_(k+1) = e_k, e_n = total_length, and each of these
    subintervals (except possibly the last) has length equal to the given
    shard_size.  Return the sequence of pairs of endpoints of the
    subintervals.
    """
    shard_end = 0
    shards = []
    while True:
        shard_start = shard_end
        shard_end = shard_start + shard_size
        if shard_end > total_length:
            shard_end = total_length
        if shard_start >= shard_end:
            break
        shards.append((shard_start, shard_end))
    return shards


def _whctrs(anchor):
    """Return width, height, x center, and y center for an anchor (window)."""
    w = anchor[2] - anchor[0] + 1
    h = anchor[3] - anchor[1] + 1
    x_ctr = anchor[0] + 0.5 * (w - 1)
    y_ctr = anchor[1] + 0.5 * (h - 1)
    return w, h, x_ctr, y_ctr


def reload():
    """Gracefully reloads uWSGI.

    * http://uwsgi.readthedocs.io/en/latest/Management.html#reloading-the-server

    :rtype: bool
    """
    return False


@classmethod
def is_track_file(classname, filename):
    """Is the file a type PyTopo recognizes as a track file?
           But it's more efficient to call read_track_file() wrapped in a try
           to avoid checking the extension twice.
        """
    ext = classname.lowerext(filename)
    for mapper in classname.mappers:
        if ext in mapper[0]:
            return True
    return False


@staticmethod
def get_model_prefix(model):
    """Get model API prefix"""
    app_label = model._meta.app_label.replace(' ', '_').lower()
    model_name = model.__name__.lower()
    return '{}/{}'.format(app_label, model_name)


def unindent(text, skip1=False):
    """Remove leading spaces that are present in all lines of ``text``.

    Parameters
    ----------
    test : str
        The text from which leading spaces should be removed.
    skip1 : bool
        Ignore the first line when determining number of spaces to unindent,
        and remove all leading whitespaces from it.
    """
    lines = text.splitlines()
    ws_lead = []
    for line in lines[skip1:]:
        len_stripped = len(line.lstrip(' '))
        if len_stripped:
            ws_lead.append(len(line) - len_stripped)
    if len(ws_lead) > skip1:
        rm = min(ws_lead)
        if rm:
            if skip1:
                lines[0] = ' ' * rm + lines[0].lstrip()
            text = '\n'.join(line[rm:] for line in lines)
    return text