def move_detach_links_release(NODE_OT_links_detach=None,
    NODE_OT_translate_attach=None):
    """Move a node to detach links

    :param NODE_OT_links_detach: Detach Links, Remove all links to selected nodes, and try to connect neighbor nodes together
    :param NODE_OT_translate_attach: Move and Attach, Move nodes and attach to frame
    """
    pass


@classmethod
def get_id_prefix(cls):
    """Return a prefix applied to worker Ids"""
    return 'swm_worker'


def calc_num_params(net):
    """
    Calculate the count of trainable parameters for a model.

    Parameters
    ----------
    net : Module
        Analyzed model.
    """
    import numpy as np
    net_params = filter(lambda p: p.requires_grad, net.parameters())
    weight_count = 0
    for param in net_params:
        weight_count += np.prod(param.size())
    return weight_count


def affiliationsSet(request):
    """
        Called when a affiliations modify request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}

        @return: A deferred that fires with C{None} when the affiliation
            changes were succesfully processed..
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}

        @note: Affiliations are always on the bare JID. The JIDs in
            L{wokkel.pubsub.PubSubRequest}'s C{affiliations} attribute are
            already stripped of any resource.
        """


def plot_color(background_paper_color=None, background_plot_color=None):
    """
    *Plot and paper color*

    Parameters:
        background_plot_color (str or tuple): Background color of the main plot area.
            Possible values: See :ref:`colors`.
        background_paper_color (str or tuple): Background color of the entire drawing area.
            Possible values: See :ref:`colors`.
    """


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 highlight_update():
    """Update the item highlight based on the current mouse position

    """
    pass


@staticmethod
def process_action(*args, **kwargs):
    """
        This static method receives preprocessed arguments in input, and
        shall perform the transactional action it represents, returning its result (if any).
        Any error preventing the success of this action shall simply be left propagating, so
        that upper level transactional structures can take measures accordingly (:meth:`rollback_action`
        shall not be directly called by this method).
        Note that the signature and return type of this method are free, as long as expected arguments
        match the output of the potential :meth:`preprocess_arguments` method.
        """
    raise NotImplementedError()


def _raise_exception(exception_object):
    """Raise exception with short traceback."""
    raise exception_object


def read_record():
    """
        Receive and deserialize next record from peer.
        Return None if no more records available
        """


def db_copy(obj, to, *skip, **kwargs):
    """
    Copies a model from one database into another.
    `obj` is the model that is going to be cloned
    `to` is the db definition
    `skip` is a list of attribtues that won't be copied
    `kwargs is a list of elements that will be overwritten over model data
    returns the copied object in `to` db
    """
    from django.forms.models import model_to_dict
    from django.db.models import Model
    assert isinstance(obj, Model)
    data = model_to_dict(obj)
    for key in skip:
        if key in data:
            v = data.pop(key)
            print('Removing {}: {}'.format(key, v))
    data.update(kwargs)
    return type(obj).objects.using(to).create(**data)


def __neighcom(node, graph, status):
    """
    Compute the communities in the neighborood of node in the graph given
    with the decomposition node2com
    """
    weights = {}
    for neighbor, datas in graph[node].items():
        if neighbor != node:
            weight = datas.get('weight', 1)
            neighborcom = status.node2com[neighbor]
            weights[neighborcom] = weights.get(neighborcom, 0) + weight
    return weights


def image_shape(img):
    """handle different image formats, returning (width,height) tuple"""
    if hasattr(img, 'shape'):
        return img.shape[1], img.shape[0]
    return img.width, img.height


def get_endpoints(tenant_id, entry_generator, prefix_for_endpoint):
    """
    Canned response for Identity's get endpoints call.  This returns endpoints
    only for the services implemented by Mimic.

    :param entry_generator: A callable, like :func:`canned_entries`, which
        takes a datetime and returns an iterable of Entry.
    """
    result = []
    for entry in entry_generator(tenant_id):
        for endpoint in entry.endpoints:
            result.append({'region': endpoint.region, 'tenantId': endpoint.
                tenant_id, 'internalURL': endpoint.url_with_prefix(
                prefix_for_endpoint(endpoint), internal_url=True),
                'publicURL': endpoint.url_with_prefix(prefix_for_endpoint(
                endpoint)), 'name': entry.name, 'type': entry.type, 'id':
                endpoint.endpoint_id})
    return {'endpoints': result}


def fixture(cls):
    """ A simple decorator to set the fixture flag on the class."""
    setattr(cls, '__FIXTURE__', True)
    return cls


@staticmethod
def get_files_dir():
    """
        Alternative App._get_user_data_dir() implementation for Android
        that also works when within a service activity.
        """
    from jnius import autoclass, cast
    PythonActivity = autoclass('org.kivy.android.PythonActivity')
    activity = PythonActivity.mActivity
    if activity is None:
        PythonService = autoclass('org.kivy.android.PythonService')
        activity = PythonService.mService
    context = cast('android.content.Context', activity)
    file_p = cast('java.io.File', context.getFilesDir())
    data_dir = file_p.getAbsolutePath()
    return data_dir


def describe():
    """
    Describe Dependency supported.
    """
    print('acl - clausal modifier of noun')
    print('advcl - adverbial clause modifier')
    print('advmod - adverbial modifier')
    print('amod - adjectival modifier')
    print('appos - appositional modifier')
    print('aux - auxiliary')
    print('case - case marking')
    print('ccomp - clausal complement')
    print('compound - compound')
    print('compound:plur - plural compound')
    print('conj - conjunct')
    print('cop - cop')
    print('csubj - clausal subject')
    print('dep - dependent')
    print('det - determiner')
    print('fixed - multi-word expression')
    print('flat - name')
    print('iobj - indirect object')
    print('mark - marker')
    print('nmod - nominal modifier')
    print('nsubj - nominal subject')
    print('obj - direct object')
    print('parataxis - parataxis')
    print('root - root')
    print('xcomp - open clausal complement')
    print(
        'you can read more from https://universaldependencies.org/treebanks/id_pud/index.html'
        )


def get_near_name(begin, items):
    """ Return the closest matching playlist name that starts with begin. """
    for name in sorted(items):
        if name.lower().startswith(begin.lower()):
            return name
    return begin


def unregister(ob):
    """Remove the object from the indexes.

        IntIdMissingError is raised if ob is not registered previously.
        """


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 lambd_CO2_H_HMW84(T, P):
    """n-c: carbon-dioxide hydrogen [HMW84]."""
    lambd = 0.0
    valid = T == 298.15
    return lambd, valid


def sculptmode_toggle():
    """Toggle sculpt mode in 3D view

    """
    pass


def take(source, count):
    """
    take(source, count) -> list object

    Return a subset of a string or list `source`, starting
    at index 0 and of length `count`
    """
    pass


def fetch_extra_data(resource):
    """Return a dict with extra data retrieved from cern oauth."""
    person_id = resource.get('PersonID', [None])[0]
    identity_class = resource.get('IdentityClass', [None])[0]
    department = resource.get('Department', [None])[0]
    return dict(person_id=person_id, identity_class=identity_class,
        department=department)


def portrayCell(cell):
    """
    This function is registered with the visualization server to be called
    each tick to indicate how to draw the cell in its current state.
    :param cell:  the cell in the simulation
    :return: the portrayal dictionary.
    """
    assert cell is not None
    return {'Shape': 'rect', 'w': 1, 'h': 1, 'Filled': 'true', 'Layer': 0,
        'x': cell.x, 'y': cell.y, 'Color': 'black' if cell.isAlive else 'white'
        }


@classmethod
def site_fields(cls):
    """ All site fields """
    return cls.shared_fields + cls.unshared_fields + cls.site_only_fields


def load_uvarint_b(buffer):
    """
    Variable int deserialization, synchronous from buffer.
    :param buffer:
    :return:
    """
    result = 0
    idx = 0
    byte = 128
    while byte & 128:
        byte = buffer[idx]
        result += (byte & 127) << 7 * idx
        idx += 1
    return result


def coefficient_cfn(friction, normal):
    """Usage: Find coefficient with friction and normal force"""
    return friction / normal


def getTOFalphaDeriv(dsp):
    """get derivatives of TOF peak profile beta wrt alpha

    :param float dsp: d-spacing of peak

    :returns: float getTOFalphaDeriv: d(alp)/d(alpha)

    """
    return 1.0 / dsp


@classmethod
def create(cls, index):
    """ Create a new index """
    return cls('Create', None, index=index)


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

    """
    pass


@classmethod
def get_recharge_record_by_data(cls, recharge_object_code_list,
    recharge_rule_id_list):
    """
        根据充值对象编号列表、充值方案ID 获取本充值对象适用此类充值方案的充值记录(返回值 所用充值方案ID)
        :param recharge_object_code_list:
        :param recharge_rule_id_list:
        :return:
        """
    return cls.objects(recharge_object_code__in=recharge_object_code_list,
        recharge_status__in=[cls.get_dict_id('balance_recharge_status',
        '充值成功')], recharge_rule_id__in=recharge_rule_id_list).only(
        'recharge_rule_id').all()


@staticmethod
def _flatten_mailjet_headers(headers):
    """Convert Mailjet's dict-of-strings-and/or-lists header format to our list-of-name-value-pairs

        {'name1': 'value', 'name2': ['value1', 'value2']}
          --> [('name1', 'value'), ('name2', 'value1'), ('name2', 'value2')]
        """
    result = []
    for name, values in headers.items():
        if isinstance(values, list):
            for value in values:
                result.append((name, value))
        else:
            result.append((name, values))
    return result


def lockShared(principal_ids=None, duration=None):
    """lock context with a shared lock, and return token.

        if principal_ids is None, use interaction's principals; if interaction
        does not have any principals, raise ValueError.

        if principal_ids is not None, principal_ids must be in interaction,
        or else raise ParticipationError.  Must be at least one id.

        Same constraints as token utility's register method.
        """


def get_string(value):
    """ Returns string representation of the value or empty string if None """
    if value:
        return str(value)
    else:
        return ''


def listify(item):
    """
    If item is not a list, return it as a list
    :param item: Item which may or may not be a list
    :return: List
    """
    if not isinstance(item, list):
        return [item]
    return item


def RESULT_TABLE(workflow_id):
    """Get default result table name for the workflow with the given
    identifier. It is assumed that the identifier is a UUID that only contains
    letters and digits and no white space or special characters.

    Parameters
    ----------
    workflow_id: string
        Unique workflow identifier

    Returns
    -------
    string
    """
    return 'res_{}'.format(workflow_id)


def prepare(prefix):
    """
    Prepare the environment.
    """
    return True


def config_fallocate_value(reserve_value):
    """
    Returns fallocate reserve_value as an int or float.
    Returns is_percent as a boolean.
    Returns a ValueError on invalid fallocate value.
    """
    try:
        if str(reserve_value[-1:]) == '%':
            reserve_value = float(reserve_value[:-1])
            is_percent = True
        else:
            reserve_value = int(reserve_value)
            is_percent = False
    except ValueError:
        raise ValueError(
            'Error: %s is an invalid value for fallocate_reserve.' %
            reserve_value)
    return reserve_value, is_percent


def CDLCONSEALBABYSWALL(df):
    """
    Concealing Baby Swallow
    """


def smooth(number):
    """Returns an integer if the float is a whole number"""
    return int(number) if number.is_integer() else number


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


@staticmethod
def get_show_name(uri):
    """Get show name from uri"""
    tokens = uri.split('_')
    channel = tokens[0]
    show = tokens[1]
    return channel + '_' + show


def get_text_fingerprint(text, hash_meth, encoding='utf-8'):
    """
    Use default hash method to return hash value of a piece of string
    default setting use 'utf-8' encoding.
    """
    m = hash_meth()
    m.update(text.encode(encoding))
    return m.hexdigest()


def dim1(s):
    """Dimension of the slice list for dimension 1."""
    return s[1].stop - s[1].start


@classmethod
def from_dict(cls, metadata: dict, kwargs: dict, **extra) ->'Message':
    """Create a message instance given the metadata and kwargs

        Will be used by the serializers
        """
    raise NotImplementedError()


def _prefix_paths(tree, nodes):
    """ Generate all paths of tree leading to all item nodes """
    for node in nodes:
        path = []
        support = node.count
        node = node.parent
        while node.item is not None:
            path.append(node.item)
            node = node.parent
        if path:
            yield support, path


@classmethod
def create_from_learning_model(cls, model_id, label, description=None,
    default_prediction_server_id=None):
    """Create a deployment from a DataRobot model.

        .. versionadded:: v2.17

        Parameters
        ----------
        model_id : str
            id of the DataRobot model to deploy
        label : str
            a human readable label of the deployment
        description : str, optional
            a human readable description of the deployment
        default_prediction_server_id : str
            an identifier of a prediction server to be used as the default prediction server

        Returns
        -------
        deployment : Deployment
            The created deployment

        Examples
        --------
        .. code-block:: python

            from datarobot import Project, Deployment
            project = Project.get('5506fcd38bd88f5953219da0')
            model = project.get_models()[0]
            deployment = Deployment.create_from_learning_model(model.id, 'New Deployment')
            deployment
            >>> Deployment('New Deployment')
        """
    payload = {'model_id': model_id, 'label': label, 'description': description
        }
    if default_prediction_server_id:
        payload['default_prediction_server_id'] = default_prediction_server_id
    url = '{}fromLearningModel/'.format(cls._path)
    deployment_id = cls._client.post(url, data=payload).json()['id']
    return cls.get(deployment_id)


@classmethod
def find(cls, query, **kwargs):
    """ Query MongoDB to find multiple objects.

        :param dict query: a MongoDB query
        :rtype: :class:`~mormon.mormon.MCursor` OR None
        """
    return cls._find(query, **kwargs)


def create_job_queue(jobQueueName=None, state=None, priority=None,
    computeEnvironmentOrder=None):
    """
    Creates an AWS Batch job queue. When you create a job queue, you associate one or more compute environments to the queue and assign an order of preference for the compute environments.
    You also set a priority to the job queue that determines the order in which the AWS Batch scheduler places jobs onto its associated compute environments. For example, if a compute environment is associated with more than one job queue, the job queue with a higher priority is given preference for scheduling jobs to that compute environment.
    See also: AWS API Documentation

    Examples
    This example creates a job queue called LowPriority that uses the M4Spot compute environment.
    Expected Output:
    This example creates a job queue called HighPriority that uses the C4OnDemand compute environment with an order of 1 and the M4Spot compute environment with an order of 2.
    Expected Output:

    :example: response = client.create_job_queue(
        jobQueueName='string',
        state='ENABLED'|'DISABLED',
        priority=123,
        computeEnvironmentOrder=[
            {
                'order': 123,
                'computeEnvironment': 'string'
            },
        ]
    )

    :type jobQueueName: string
    :param jobQueueName: [REQUIRED]
            The name of the job queue.

    :type state: string
    :param state: The state of the job queue. If the job queue state is ENABLED , it is able to accept jobs.

    :type priority: integer
    :param priority: [REQUIRED]
            The priority of the job queue. Job queues with a higher priority (or a lower integer value for the priority parameter) are evaluated first when associated with same compute environment. Priority is determined in ascending order, for example, a job queue with a priority value of 1 is given scheduling preference over a job queue with a priority value of 10 .

    :type computeEnvironmentOrder: list
    :param computeEnvironmentOrder: [REQUIRED]
            The set of compute environments mapped to a job queue and their order relative to each other. The job scheduler uses this parameter to determine which compute environment should execute a given job. Compute environments must be in the VALID state before you can associate them with a job queue. You can associate up to 3 compute environments with a job queue.
            (dict) --The order in which compute environments are tried for job placement within a queue. Compute environments are tried in ascending order. For example, if two compute environments are associated with a job queue, the compute environment with a lower order integer value is tried for job placement first.
            order (integer) -- [REQUIRED]The order of the compute environment.
            computeEnvironment (string) -- [REQUIRED]The Amazon Resource Name (ARN) of the compute environment.

    :rtype: dict
    :return: {
        'jobQueueName': 'string',
        'jobQueueArn': 'string'
    }

    """
    pass


def _split_left_right(name):
    """Split record name at the first whitespace and return both parts.

    RHS is set to an empty string if not present.
    """
    parts = name.split(None, 1)
    lhs, rhs = [parts[0], parts[1] if len(parts) > 1 else '']
    return lhs, rhs


def get_main_package_directory(distribution):
    """
    Given a Distribution object, return the main package directory.
    """
    return min(distribution.packages, key=len)


@classmethod
def adjust_database_uri(cls, uri, selected_schema: str):
    """Based on a URI and selected schema, return a new URI

        The URI here represents the URI as entered when saving the database,
        ``selected_schema`` is the schema currently active presumably in
        the SQL Lab dropdown. Based on that, for some database engine,
        we can return a new altered URI that connects straight to the
        active schema, meaning the users won't have to prefix the object
        names by the schema name.

        Some databases engines have 2 level of namespacing: database and
        schema (postgres, oracle, mssql, ...)
        For those it's probably better to not alter the database
        component of the URI with the schema name, it won't work.

        Some database drivers like presto accept '{catalog}/{schema}' in
        the database component of the URL, that can be handled here.
        """
    return uri


def get_obj_name(obj):
    """Return printable name for objects or functions."""
    if hasattr(obj, 'name'):
        return obj.name
    elif hasattr(obj, 'func_name'):
        return obj.func_name
    else:
        return str(obj)


def canonical_format_name(format):
    """Convert format name "format" to a consistent version."""
    format = format.lower()
    if format in ['jpg', 'jpeg']:
        return 'jpeg'
    elif format in ['tiff', 'tif']:
        return 'tiff'
    else:
        return format


def usage_percent(used, total, round_=None):
    """Calculate percentage usage of 'used' against 'total'."""
    try:
        ret = used / total * 100
    except ZeroDivisionError:
        ret = 0.0 if isinstance(used, float) or isinstance(total, float) else 0
    if round_ is not None:
        return round(ret, round_)
    else:
        return ret


def format_hex_width(value, width):
    """! @brief Formats the value as hex of the specified bit width.

    @param value Integer value to be formatted.
    @param width Bit width, must be one of 8, 16, 32, 64.
    @return String with (width / 8) hex digits. Does not have a "0x" prefix.
    """
    if width == 8:
        return '%02x' % value
    elif width == 16:
        return '%04x' % value
    elif width == 32:
        return '%08x' % value
    elif width == 64:
        return '%016x' % value
    else:
        raise ValueError('unrecognized register width (%d)' % width)


def remove_duplicate_columns(x_train, x_test=None):
    """
    Removes columns whose values are exact duplicates of each other.

    Parameters
    ----------
    x_train: Dataframe or array like - 2d
        Dataset.

    x_test: Dataframe or array like - 2d
        Testing dataset, by default None.

    Returns
    -------
    Dataframe, *Dataframe
        Transformed dataframe with rows with a missing values in a specific row are missing

    Returns 2 Dataframes if x_test is provided.
    """
    x_train = x_train.T.drop_duplicates().T
    if x_test is not None:
        x_test = x_test.T.drop_duplicates().T
    return x_train, x_test


def run(thug, log):
    """
        This method is called when the plugin is invoked

        Parameters:
        @thug:  Thug class main instance
        @log:   Thug root logger
        """
    pass


def compute_total_length(hyp):
    """Compute total length of a hypothesis/reference.

    Args:
        hyp: a list of tuples, where each tuple is (speaker, start, end)
            of type (string, float, float)

    Returns:
        a float number for the total length
    """
    total_length = 0.0
    for element in hyp:
        total_length += element[2] - element[1]
    return total_length


@classmethod
def parse(cls, name, default_owner=None, default_activity_group=None):
    """
        This parses the standard, extended format for naming statistics.  It is one to three fields, separated by ':'.
        These are one of 'name', 'owner:name', or 'owner:name:activity_group'.
        Currently this is used only by reftuple which itself is used only in the power pipeline configuration.
        """
    parts, owner, activity_group = name.split(':'), None, None
    if len(parts) == 1:
        name = parts[0]
    elif len(parts) == 2:
        owner, name = parts
    else:
        owner, name, activity_group = parts
    if not owner:
        owner = default_owner
    if not owner:
        raise Exception(f'Missing owner for {name}')
    if not activity_group:
        activity_group = default_activity_group
    if activity_group == 'None':
        activity_group = None
    return owner, name, activity_group


def julday2mjd(*args):
    """ julian day to modified julian day

    Args:
        julday (int) : julian day
        hour (int) : hour, optional
        minute (int) : minute, optional
        seconds (float) : seconds, optional

    Returns:
        float : modified julian day

"""
    julday = args[0]
    mjd = julday - 2400001.0
    hms = [24, 1440, 86400]
    for i, v in enumerate(args[1:]):
        mjd += v / hms[i]
    return mjd


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


@classmethod
def from_operator_name(cls, name: str, **kwargs) ->'DiffusionMaps':
    """Instantiate new model to approximate operator (to be selected by name).

        Parameters
        ----------
        name
            "laplace_beltrami", "fokker_plank", "graph_laplacian" or "rbf".

        **kwargs
            All parameters in :py:class:`DiffusionMaps` but ``alpha``.

        Returns
        -------
        DiffusionMaps
            self
        """
    if name == 'laplace_beltrami':
        eigfunc_interp = cls.laplace_beltrami(**kwargs)
    elif name == 'fokker_planck':
        eigfunc_interp = cls.fokker_planck(**kwargs)
    elif name == 'graph_laplacian':
        eigfunc_interp = cls.graph_laplacian(**kwargs)
    elif name == 'rbf':
        eigfunc_interp = cls.rbf_kernel(**kwargs)
    else:
        raise ValueError(
            f"name='{name}' not known. Choose from {cls._cls_valid_operator_names}"
            )
    if name not in cls._cls_valid_operator_names:
        raise NotImplementedError(
            f'This is a bug. name={name} each name has to be listed in VALID_OPERATOR_NAMES'
            )
    return eigfunc_interp


def process(proc_data):
    """
    Final processing to conform to the schema.

    Parameters:

        proc_data:   (dictionary) raw structured data to process

    Returns:

        List of dictionaries. Structured data with the following schema:

        [
          {
            "group_name":       string,
            "password":         string,
            "administrators": [
                                string
            ],
            "members": [
                                string
            ]
          }
        ]
    """
    for entry in proc_data:
        if entry['administrators'] == ['']:
            entry['administrators'] = []
        if entry['members'] == ['']:
            entry['members'] = []
    return proc_data


def on_solved(response, **kwargs):
    """Callback; set this attribute in the parent class."""
    raise NotImplementedError


@classmethod
def _clear_resolvers(cls) ->None:
    """Remove all resolvers.

        This method is EXCLUSIVELY for use in tests.
        """
    cls._resolver_by_type.clear()


def ident(v):
    """a identity function used by default converter"""
    return v


def concatfunc(func, lst):
    """
    Concatenate returned list of `func(elem)` for `elem` in `lst`
    """
    ret = []
    for elem in lst:
        ret += func(elem)
    return ret


def valid_port(port):
    """
    Returns True if `port` is a valid port.

    **Example usage**

    >>> assert(not valid_port(-1))
    >>> assert(not valid_port('something not a port'))
    >>> assert(valid_port('80'))
    >>> valid_port(65535)
    True
    """
    try:
        return 0 <= int(port) < 2 ** 16
    except:
        return False


def utf8_decoder(s):
    """ Decode the unicode as UTF-8 """
    if s is None:
        return None
    return s.decode('utf-8')


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


@classmethod
def default_chunk_size(cls):
    """ Returns the default chunk size for this source.
        """
    return 256


def _is_dunder(name):
    """Returns True if a __dunder__ name, False otherwise."""
    return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
        ] != '_' and len(name) > 4


def report_copy():
    """Copy selected reports to Clipboard

    """
    pass


def parse_storm_version(version_string):
    """
    Parses the version of storm.

    :param version_string: String containing version information.
    :return: Tuple (version, commit)
    """
    split = version_string.split('-')
    version = split[0]
    commit = ''
    if len(split) > 1:
        commit = split[1]
    return version, commit


def rxfilter(rx, select, cursor):
    """Utility function to convert a sequence `cursor` to a generator, but
    applying a filtering predicate to select which rows to return.

    The assumption is that `cursor` yields uniform sequence objects ("rows"),
    and the `select` operator can be invoked with ``select(row)`` for each
    retrieved row to return a string. If the value returned matches the
    regular expression `rx`, the original row is included in the generator
    output, otherwise it's skipped.

    :arg re.RegexObject rx: Regular expression to match against, or at least
     any object which supports ``rx.match(value)`` on the value returned by
     the ``select(row)`` operator.
    :arg callable select: An operator which returns the item to filter on,
     given a row of values, typically an :func:`operator.itemgetter`.
    :arg sequence cursor: Input sequence."""
    for row in cursor:
        if rx.match(select(row)):
            yield row


def count_str(text, sub, start=None, end=None):
    """
    Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``.

    Optional arguments start and end are interpreted as in slice notation.

    :param text: The string to search
    :type text:  ``str``

    :param sub: The substring to count
    :type sub:  ``str``

    :param start: The start of the search range
    :type start:  ``int``

    :param end: The end of the search range
    :type end:  ``int``

    :return: The number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``.
    :rtype:  ``int``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.count(sub, start, end)


def c2min(f, c1, c2):
    """Take the minimum value between two columns in a dataframe.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the two columns ``c1`` and ``c2``.
    c1 : str
        Name of the first column in the dataframe ``f``.
    c2 : str
        Name of the second column in the dataframe ``f``.

    Returns
    -------
    min_val : float
        The minimum value of the two columns.

    """
    min_val = min(f[c1], f[c2])
    return min_val


@staticmethod
def pre_run_report(**kwarg):
    """ This runs in the context of __main__ """
    pass


@classmethod
def find(cls, channel, start, end, frametype=None, pad=None, scaled=None,
    dtype=None, nproc=1, verbose=False, **readargs):
    """Find and read data from frames for a channel

        Parameters
        ----------
        channel : `str`, `~gwpy.detector.Channel`
            the name of the channel to read, or a `Channel` object.

        start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
            GPS start time of required data,
            any input parseable by `~gwpy.time.to_gps` is fine

        end : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
            GPS end time of required data,
            any input parseable by `~gwpy.time.to_gps` is fine

        frametype : `str`, optional
            name of frametype in which this channel is stored, will search
            for containing frame types if necessary

        nproc : `int`, optional, default: `1`
            number of parallel processes to use, serial process by
            default.

        pad : `float`, optional
            value with which to fill gaps in the source data,
            by default gaps will result in a `ValueError`.

        dtype : `numpy.dtype`, `str`, `type`, or `dict`
            numeric data type for returned data, e.g. `numpy.float`, or
            `dict` of (`channel`, `dtype`) pairs

        allow_tape : `bool`, optional, default: `True`
            allow reading from frame files on (slow) magnetic tape

        verbose : `bool`, optional
            print verbose output about read progress, if ``verbose``
            is specified as a string, this defines the prefix for the
            progress meter

        **readargs
            any other keyword arguments to be passed to `.read()`
        """
    return cls.DictClass.find([channel], start, end, frametype=frametype,
        verbose=verbose, pad=pad, scaled=scaled, dtype=dtype, nproc=nproc,
        **readargs)[str(channel)]


def total_seconds(delta):
    """Determines total seconds with python < 2.7 compat."""
    return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) *
        1000000.0) / 1000000.0


def eval_expr(code, local_dict, global_dict):
    """
    Evaluate Python code generated by ``stringify_expr``.

    Generally, ``parse_expr`` should be used.

    """
    expr = eval(code, global_dict, local_dict)
    return expr


def is_reorderable():
    """ Return true if the folder can be reordered, false otherwise."""


@classmethod
def setUpClass(cls):
    """Hook method for setting up class fixture before running tests in the class."""


def three_digit(number):
    """ Add 0s to inputs that their length is less than 3.
    :param number:
        The number to convert
    :type number:
        int
    :returns:
        String
    """
    number = str(number)
    if len(number) == 1:
        return u'00%s' % number
    elif len(number) == 2:
        return u'0%s' % number
    else:
        return number


def select_less():
    """Deselect objects at the boundaries of parent/child relationships

    """
    pass


@classmethod
def getDescription(cls, str_):
    """Get description."""
    if not str_ or str_[0] != '$':
        return ''
    value = int(str_[1:])
    if value == 1:
        ret = 'Sum Li Active power+ (QI+QIV)'
    elif value == 2:
        ret = 'Sum Li Active power- (QII+QIII)'
    elif value == 3:
        ret = 'Sum Li Reactive power+ (QI+QII)'
    elif value == 4:
        ret = 'Sum Li Reactive power- (QIII+QIV)'
    elif value == 5:
        ret = 'Sum Li Reactive power QI'
    elif value == 6:
        ret = 'Sum Li Reactive power QII'
    elif value == 7:
        ret = 'Sum Li Reactive power QIII'
    elif value == 8:
        ret = 'Sum Li Reactive power QIV'
    elif value == 9:
        ret = 'Sum Li Apparent power+ (QI+QIV)'
    elif value == 10:
        ret = 'Sum Li Apparent power- (QII+QIII)'
    elif value == 11:
        ret = 'Current: any phase'
    elif value == 12:
        ret = 'Voltage: any phase'
    elif value == 13:
        ret = 'Sum Li Power factor'
    elif value == 14:
        ret = 'Supply frequency'
    elif value == 15:
        ret = 'Sum Li Active power (abs(QI+QIV)+abs(QII+QIII))'
    elif value == 16:
        ret = 'Sum Li Active power (abs(QI+QIV)-abs(QII+QIII))'
    elif value == 17:
        ret = 'Sum Li Active power QI'
    elif value == 18:
        ret = 'Sum Li Active power QII'
    elif value == 19:
        ret = 'Sum Li Active power QIII'
    elif value == 20:
        ret = 'Sum Li Active power QIV'
    elif value == 21:
        ret = 'L1 Active power+ (QI+QIV)'
    elif value == 22:
        ret = 'L1 Active power- (QII+QIII)'
    elif value == 23:
        ret = 'L1 Reactive power+ (QI+QII)'
    elif value == 24:
        ret = 'L1 Reactive power- (QIII+QIV)'
    elif value == 25:
        ret = 'L1 Reactive power QI'
    elif value == 26:
        ret = 'L1 Reactive power QII'
    elif value == 27:
        ret = 'L1 Reactive power QIII'
    elif value == 28:
        ret = 'L1 Reactive power QIV'
    elif value == 29:
        ret = 'L1 Apparent power+ (QI+QIV)'
    elif value == 30:
        ret = 'L1 Apparent power- (QII+QIII)'
    elif value == 31:
        ret = 'L1 Current'
    elif value == 32:
        ret = 'L1 Voltage'
    elif value == 33:
        ret = 'L1 Power factor'
    elif value == 34:
        ret = 'L1 Supply frequency'
    elif value == 35:
        ret = 'L1 Active power (abs(QI+QIV)+abs(QII+QIII))'
    elif value == 36:
        ret = 'L1 Active power (abs(QI+QIV)-abs(QII+QIII))'
    elif value == 37:
        ret = 'L1 Active power QI'
    elif value == 38:
        ret = 'L1 Active power QII'
    elif value == 39:
        ret = 'L1 Active power QIII'
    elif value == 40:
        ret = 'L1 Active power QIV'
    elif value == 41:
        ret = 'L2 Active power+ (QI+QIV)'
    elif value == 42:
        ret = 'L2 Active power- (QII+QIII)'
    elif value == 43:
        ret = 'L2 Reactive power+ (QI+QII)'
    elif value == 44:
        ret = 'L2 Reactive power- (QIII+QIV)'
    elif value == 45:
        ret = 'L2 Reactive power QI'
    elif value == 46:
        ret = 'L2 Reactive power QII'
    elif value == 47:
        ret = 'L2 Reactive power QIII'
    elif value == 48:
        ret = 'L2 Reactive power QIV'
    elif value == 49:
        ret = 'L2 Apparent power+ (QI+QIV)'
    elif value == 50:
        ret = 'L2 Apparent power- (QII+QIII)'
    elif value == 51:
        ret = 'L2 Current'
    elif value == 52:
        ret = 'L2 Voltage'
    elif value == 53:
        ret = 'L2 Power factor'
    elif value == 54:
        ret = 'L2 Supply frequency'
    elif value == 55:
        ret = 'L2 Active power (abs(QI+QIV)+abs(QII+QIII))'
    elif value == 56:
        ret = 'L2 Active power (abs(QI+QIV)-abs(QI+QIII))'
    elif value == 57:
        ret = 'L2 Active power QI'
    elif value == 58:
        ret = 'L2 Active power QII'
    elif value == 59:
        ret = 'L2 Active power QIII'
    elif value == 60:
        ret = 'L2 Active power QIV'
    elif value == 61:
        ret = 'L3 Active power+ (QI+QIV)'
    elif value == 62:
        ret = 'L3 Active power- (QII+QIII)'
    elif value == 63:
        ret = 'L3 Reactive power+ (QI+QII)'
    elif value == 64:
        ret = 'L3 Reactive power- (QIII+QIV)'
    elif value == 65:
        ret = 'L3 Reactive power QI'
    elif value == 66:
        ret = 'L3 Reactive power QII'
    elif value == 67:
        ret = 'L3 Reactive power QIII'
    elif value == 68:
        ret = 'L3 Reactive power QIV'
    elif value == 69:
        ret = 'L3 Apparent power+ (QI+QIV)'
    elif value == 70:
        ret = 'L3 Apparent power- (QII+QIII)'
    elif value == 71:
        ret = 'L3 Current'
    elif value == 72:
        ret = 'L3 Voltage'
    elif value == 73:
        ret = 'L3 Power factor'
    elif value == 74:
        ret = 'L3 Supply frequency'
    elif value == 75:
        ret = 'L3 Active power (abs(QI+QIV)+abs(QII+QIII))'
    elif value == 76:
        ret = 'L3 Active power (abs(QI+QIV)-abs(QI+QIII))'
    elif value == 77:
        ret = 'L3 Active power QI'
    elif value == 78:
        ret = 'L3 Active power QII'
    elif value == 79:
        ret = 'L3 Active power QIII'
    elif value == 80:
        ret = 'L3 Active power QIV'
    elif value == 82:
        ret = 'Unitless quantities (pulses or pieces)'
    elif value == 84:
        ret = 'Sum Li Power factor-'
    elif value == 85:
        ret = 'L1 Power factor-'
    elif value == 86:
        ret = 'L2 Power factor-'
    elif value == 87:
        ret = 'L3 Power factor-'
    elif value == 88:
        ret = 'Sum Li A2h QI+QII+QIII+QIV'
    elif value == 89:
        ret = 'Sum Li V2h QI+QII+QIII+QIV'
    elif value == 90:
        ret = (
            'SLi current (algebraic sum of the unsigned value of the currents in all phases)'
            )
    elif value == 91:
        ret = 'Lo Current (neutral)'
    elif value == 92:
        ret = 'Lo Voltage (neutral)'
    else:
        ret = ''
    return ret


def setup_root(newroot):
    """
    Sets up the root component, so the logger knows where to send logging
    signals.

    :param newroot:
    """
    global root
    root = newroot


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'junos_info':
        "A two-level dictionary providing Junos software version information for each RE in the system. The first-level key is the name of the RE. The second level key is 'text' for the version as a string and 'object' for the version as a version_info object."
        , 'hostname':
        'A string containing the hostname of the current Routing Engine.',
        'hostname_info':
        'A dictionary keyed on Routing Engine name. The value of each key is the hostname of the Routing Engine.'
        , 'model':
        'An uppercase string containing the model of the chassis in which the current Routing Engine resides.'
        , 'model_info':
        'A dictionary keyed on Routing Engine name. The value of each key is an uppercase string containing the model of the chassis in which the Routing Engine resides.'
        , 'version':
        'A string containing the Junos version of the current Routing Engine.',
        'version_info':
        'The Junos version of the current Routing Engine as a version_info object.'
        , 'version_RE0':
        'A string containing the Junos version of the RE in slot 0. (Assuming the system contains an RE0.)'
        , 'version_RE1':
        'A string containing the Junos version of the RE in slot 1. (Assuming the system contains an RE1)'
        }


@classmethod
def merge(cls, a, b):
    """Merges two FrozeDict. Similar to update(), but returns new instance"""
    x = {}
    x.update(a)
    x.update(b)
    return cls(x)


def extrude_edges_indiv(mirror: bool=False):
    """Extrude individual edges only

    :param mirror: Mirror Editing
    :type mirror: bool
    """
    pass


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 read_file_str(file_path):
    """
    Read the target file string.

    Parameters
    ----------
    file_path : str
        Path of target file.

    Returns
    -------
    file_str : str
        The target string read.
    """
    with open(file_path, mode='r', encoding='utf-8') as f:
        file_str = f.read()
    return file_str


def pairs_to_dict(response):
    """Create a dict given a list of key/value pairs"""
    it = iter(response)
    return dict(zip(it, it))


def _make_function(name, code, globals_=None):
    """Return a function created by executing a code string in a new namespace.

    This is not much more than a wrapper around :func:`exec`.

    Args:
        name: The name of the function to create. Must match the function name
            in ``code``.

        code: A String containing the function definition code. The name of the
            function must match ``name``.

        globals_: A dict of globals to mix into the new function's namespace.
            ``__builtins__`` must be provided explicitly if required.

    .. warning:

        All pitfalls of using :func:`exec` apply to this function as well.

    """
    namespace = dict(__builtins__={})
    if globals_:
        namespace.update(globals_)
    exec(code, namespace)
    return namespace[name]


def viz_tree(tree_object):
    """Takes a Sklearn Decision Tree and returns a png image using graph_viz and pydotplus."""
    from sklearn.externals.six import StringIO
    from IPython.display import Image
    from sklearn.tree import export_graphviz
    import pydotplus
    dot_data = StringIO()
    export_graphviz(tree_object, out_file=dot_data, filled=True, rounded=
        True, special_characters=True)
    graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
    tree_viz = Image(graph.create_png())
    return tree_viz


def start_servers():
    """Checks if servers are running, if not starts them."""
    import os
    try:
        os.system("gnome-terminal -e 'qvm -S'")
        os.system("gnome-terminal -e 'quilc -S'")
    except:
        try:
            os.system("terminal -e 'qvm -S'")
            os.system("terminal -e 'quilc -S'")
        except:
            exit()


def bounding_box_half_values(bbox_min, bbox_max):
    """
    Returns the values half way between max and min XYZ given tuples
    :param bbox_min: tuple, contains the minimum X,Y,Z values of the mesh bounding box
    :param bbox_max: tuple, contains the maximum X,Y,Z values of the mesh bounding box
    :return: tuple(int, int, int)
    """
    min_x, min_y, min_z = bbox_min
    max_x, max_y, max_z = bbox_max
    half_x = (min_x + max_x) * 0.5
    half_y = (min_y + max_y) * 0.5
    half_z = (min_z + max_z) * 0.5
    return half_x, half_y, half_z


@staticmethod
def p_pa_data(p):
    """pa_data : generic_parameter_list"""
    p[0] = p[1]


@staticmethod
def countline(fpath):
    """Return the number of line in a file"
        """
    with open(fpath, 'r') as f:
        return sum(1 for nbline in f)


def text(theWhere, theX, theY, theText, theFontScale=0.4, theColor=13553358):
    """
	Display a piece of text.

	Parameters
	----------
	theWhere: np.ndarray
		image/frame where the component should be rendered.
	theX: int
		position X where the component should be placed.
	theY: int
		position Y where the component should be placed.
	theText: str
		the text content.
	theFontScale: float
		size of the text.
	theColor: uint
		color of the text in the format `0xRRGGBB`, e.g. `0xff0000` for red.

	See Also
	----------
	printf()
	"""
    print('This is wrapper function to help code autocompletion.')


def lenUVARI(v):
    """Returns the length of a UVARI value when represented in bytes."""
    if v > 127:
        if v > 16383:
            return 4
        else:
            return 2
    return 1


def contains(a, b):
    """Same as b in a (note reversed operands)."""
    return b in a


def get_example_client_pull():
    """dummy client with pull method"""
    example = """
from bubble import Bubble
class MyFancyHelloPuller(Bubble):
    def say_hello(self,i=0):
        return 'Hello, ' + str(i)

# alias for the bubble client to be found by the bubble machinery
class BubbleClient(Bubble):
    def __init__(self,cfg={}):
        self.CFG=cfg
        self.client=MyFancyHelloPuller()

class BubbleClient(Bubble):
    def __init__(self,cfg={}):
        self.CFG=cfg
        self.client=MyFancyHelloPuller()
    def pull(self, amount=42+1, index=0):
        self.say('BC: %d,%d'%(amount,index))
        for i in range(amount):
           hello_pull=self.client.say_hello('Pulling in Hello:' + str(i));
           yield {'in': hello_pull}

if __name__ == '__main__':
    from bubble.util.cfg import get_config
    BCFG = get_config()
    HELLO = BCFG.CFG.DEV.SOURCE
    puller = BubbleClient(HELLO)
    print(puller)
    print(puller.pull())

"""
    return example


def yggtime_py():
    """Plot timing statistics comparing the different versions of Python."""
    from yggdrasil import timing
    timing.plot_scalings(compare='python')


def postInstall(context):
    """called as at the end of the setup process and the right place for your code"""


@classmethod
def select(cls, for_class, since=None):
    """ Select data from this data source and yield each record as an
        instance of the fact class provided.
        """
    raise NotImplementedError('No select method defined for this source')


def setup_rdfview(ax, system):
    """Builds the radial distribution function visualisation pane.

    Parameters
    ----------
    ax: Axes object
        The axes position that the pane should be placed in.
    system: System
        The whole system information.
    """
    ax.plot([0], color='#34a5daff')
    ax.set_xlim([0, system.box_length / 2])
    ax.set_yticks([])
    ax.set_ylabel('RDF', fontsize=16)
    ax.set_xlabel('r/m', fontsize=16)


def get_distribution_language(section):
    """derive language of a given distribution construct"""
    try:
        return section.split('_')[1]
    except IndexError:
        return 'en'


def get_elasticsearch_version(default=(2, 0, 0)):
    """Get Elasticsearch version.

    :param default: Default value. Mainly added for building the docs
        when Elasticsearch is not running.
    :type default: tuple
    :return:
    :rtype: list
    """
    try:
        from elasticsearch_dsl import __version__
        return __version__
    except ImportError:
        return default


def __init__(field, context, request):
    """Adapts field, context and request.
        """


def parse_objective_coefficient(entry):
    """Return objective value for reaction entry.

    Detect objectives that are specified using the non-standardized
    kinetic law parameters which are used by many pre-FBC SBML models. The
    objective coefficient is returned for the given reaction, or None if
    undefined.

    Args:
        entry: :class:`SBMLReactionEntry`.
    """
    for parameter in entry.kinetic_law_reaction_parameters:
        pid, name, value, units = parameter
        if pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT':
            return value
    return None


def listDirectory():
    """Lists the contents of this directory.

        Raises OSError if the directory cannot be read.
        """


def lambd_NH3_Ba_CB89(T, P):
    """n-c: ammonia barium [CB89]."""
    lambd = -0.021
    valid = T == 298.15
    return lambd, valid


def scale_size(scalar: float=1.0):
    """Change brush size by a scalar

    :param scalar: Scalar, Factor to scale brush size by
    :type scalar: float
    """
    pass


@staticmethod
def _negotiate(client: int, server: int) ->int:
    """Return the negotiated value between what the client has requested
        and the server has requested for how the two will communicate.

        """
    return min(client, server) or (client or server)


def convert_post_to_VERB(request, verb):
    """
    Force Django to process the VERB.
    """
    if request.method == verb:
        if not hasattr(request, '_read_started'):
            request._read_started = False
        if hasattr(request, '_post'):
            del request._post
            del request._files
        try:
            request.method = 'POST'
            request._load_post_and_files()
            request.method = verb
        except AttributeError:
            request.META['REQUEST_METHOD'] = 'POST'
            request._load_post_and_files()
            request.META['REQUEST_METHOD'] = verb
        setattr(request, verb, request.POST)
    return request


def column_fullname(column, prefix=None):
    """Get a fully qualified name for a column

    Parameters
    ----------
    column : SQLAlchemy column
        A SQLAlchemy column object to get the full name for
    prefix : str, optional
        If specified, a manual prefix to prepend to the output string. This
        will automatically be separted with a ".".

    Returns
    -------
    str
        A fully qualified column name. The exact format will vary depending on
        your SQLAlchemy metadata, but an example would be: schema.table.column

    """
    name = '%s.%s' % (column.table.fullname, column.name)
    if prefix:
        name = prefix + '.' + name
    return name


def join_rows(rows, sep='\n'):
    """Given a list of rows (a list of lists) this function returns a
    flattened list where each the individual columns of all rows are joined
    together using the line separator.

    """
    output = []
    for row in rows:
        if len(output) <= len(row):
            for i in range(len(row) - len(output)):
                output.extend([[]])
        for i, field in enumerate(row):
            field_text = field.strip()
            if field_text:
                output[i].append(field_text)
    return list(map(lambda lines: sep.join(lines), output))


def extract_job_ids(condor_submit_text):
    """Extract Job Ids from Condor Submit Text."""
    _, _, count, *_, cluster = condor_submit_text.strip().split()
    for process in map(str, range(int(count))):
        yield cluster + process


def Mg2SiO4(mw_atmos, mh=1):
    """Defines properties for Mg2SiO4 as condensible"""
    if mh != 1:
        raise Exception(
            'Alert: No M/H Dependence in Mg2SiO4 Routine. Consult your local theorist to determine next steps.'
            )
    gas_mw = 140.7
    gas_mmr = 7.1625e-05 / 2 * (gas_mw / mw_atmos)
    rho_p = 3.214
    return gas_mw, gas_mmr, rho_p


@staticmethod
def _split_markdown(text_url, tld_pos):
    """
        Split markdown URL. There is an issue wen Markdown URL is found.
        Parsing of the URL does not stop on right place so wrongly found URL
        has to be split.

        :param str text_url: URL that we want to extract from enclosure
        :param int tld_pos: position of TLD
        :return: URL that has removed enclosure
        :rtype: str
        """
    left_bracket_pos = text_url.find('[')
    if left_bracket_pos > tld_pos - 3:
        return text_url
    right_bracket_pos = text_url.find(')')
    if right_bracket_pos < tld_pos:
        return text_url
    middle_pos = text_url.rfind('](')
    if middle_pos > tld_pos:
        return text_url[left_bracket_pos + 1:middle_pos]
    return text_url


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True, axis_range: bool=False):
    """Select all keyframes within the specified region

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    :param axis_range: Axis Range
    :type axis_range: bool
    """
    pass


def find_common_url(repo_a, repo_b):
    """ Find Common Url """
    for url_a in repo_a.urls:
        for url_b in repo_b.urls:
            if url_a == url_b:
                return url_b
    return None


def _can_change_or_view(model, user):
    """ Return True iff `user` has either change or view permission
    for `model`.
    """
    model_name = model._meta.model_name
    app_label = model._meta.app_label
    can_change = user.has_perm(app_label + '.change_' + model_name)
    can_view = user.has_perm(app_label + '.view_' + model_name)
    return can_change or can_view


def toFieldValue(element):
    """
        Convert the ElementTree element to a value which can be legally
        assigned to the field.
        """


@classmethod
def static_init():
    """init collection copy"""
    pass


def isQuark(pid):
    """Determine if the PID is that of a quark (incl 4th gen)"""
    return pid != 0 and abs(pid) <= 8


def mse(output, target):
    """
    Returns mean squared error cost of the output.
    """
    return 0.5 * (output - target) ** 2


def theta_none(T, P):
    """i-i': no interaction effect."""
    theta = 0
    valid = T > 0
    return theta, valid


@classmethod
def from_grid(cls, base_structure, grid, expansions=0):
    """Generate a gamma surface from a base structure and a grid specification at a
        given expansion.

        Parameters
        ----------
        base_structure : Bicrystal
        grid : list of length two
            Number of relative shifts in each boundary vector direction.
        expansions : number or (list or ndarray) of numbers, optional
            Expansion(s) for all shifts in the grid. By default, 0, meaning a single grid
            is added. If a list or ndarray is supplied, multiple grids are added, one for
            each expansion value.

        """
    gamma_surface = cls(base_structure, None, None)
    gamma_surface.add_grid(grid, expansions)
    return gamma_surface


def space_solar_power(x):
    """Return the radiant power density (W/m²) where x is the distance from  the sun (m)"""
    return 2.8942e+25 / x ** 2


@staticmethod
def display_time(seconds, precision=3):
    """
        method to display time in human readable format
        :param seconds: Number of seconds
        :param precision: Decimal precision
        :return: String
        """
    intervals = [('weeks', 604800), ('days', 86400), ('hours', 3600), (
        'minutes', 60), ('seconds', 1)]
    result = list()
    dtype = type(seconds).__name__
    if dtype != 'int' or dtype != 'long' or dtype != 'float':
        try:
            seconds = float(seconds)
        except (TypeError, ValueError, NameError):
            print('Type not coercible to Float')
    for name, count in intervals:
        if name != 'seconds':
            value = seconds // count
            if value:
                seconds -= value * count
                if value == 1:
                    name = name.rstrip('s')
                value = str(int(value))
                result.append('{v} {n}'.format(v=value, n=name))
        else:
            value = '{:.{p}f}'.format(seconds, p=precision)
            result.append('{v} {n}'.format(v=value, n=name))
    return ' '.join(result)


def z2g(r_geoid, g0, z):
    """Calculate gravitational acceleration at elevation

    Derived from atmlabs equivalent function
    https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m

    :param r: surface radius at point [m]
    :param g0: surface gravitational acceleration at point [m/s^2]
    :param z: elevation [m]
    :returns: gravitational acceleration at point [m/s^2]
    """
    return g0 * (r_geoid / (r_geoid + z)) ** 2


def _load_defaults(config):
    """Set config defaults."""
    config_defaults = config['Config'].get('Defaults', {})
    defaults = {}
    defaults['type'] = config_defaults.get('Type', 'list')
    defaults['source'] = config_defaults.get('Source', None)
    defaults['source_loader'] = config_defaults.get('SourceLoader', None)
    defaults['source_type'] = config_defaults.get('SourceType', None)
    defaults['randomizer'] = config_defaults.get('Randomizer', None)
    defaults['use_name_skp'] = config_defaults.get('UseNameForSourceKeyPath',
        None)
    return defaults


@classmethod
def fromFile(cls, filePath, *args, **kwargs):
    """
        Load a BNBL from a filesystem file.
        """
    with open(filePath, 'rb') as f:
        return cls(f.read(), *args, **kwargs)


@staticmethod
def names():
    """Return a tuple of all the names of the actions we support."""
    return ('print', 'fit_width', 'fit_height', 'fit_both', 'zoom_natural',
        'zoom_originalzoom_in', 'zoom_out', 'zoomer', 'rotate_left',
        'rotate_right', 'layout_single', 'layout_double_right',
        'layout_double_left', 'layout_raster', 'vertical', 'horizontal',
        'continuous', 'reload', 'previous_page', 'next_page', 'pager',
        'magnifier')


def get_pt2262_cmd(device_id, data_bits):
    """Extract and return the data bits from a Lighting4/PT2262 packet."""
    try:
        data = bytearray.fromhex(device_id)
    except ValueError:
        return None
    mask = 255 & (1 << data_bits) - 1
    return hex(data[-1] & mask)


@classmethod
def get_market_order_book(cls, pair):
    """return order book for the market"""
    return cls.api(cls.url + '/exchange/order_book?currencyPair=' + cls.
        format_pair(pair))


def q(s):
    """Quotes html string."""
    return s.replace('&', '&').replace('<', '<').replace('>', '>'
        ).replace('"', '"')


@classmethod
def as_attenuation(cls, vrms=1, **kwargs):
    """
        Allows levels to be specified in dB attenuation
        """
    return cls.from_spl(0, vrms, **kwargs)


def slice_process(slc):
    """Returns dictionaries for different slice syntaxes."""
    if slc.step is None:
        if slc.start is not None and slc.stop is not None:
            return {slc.start: slc.stop}
        if slc.start is not None and slc.stop is None:
            return {slc.start: ''}
        if slc.start is None and slc.stop is None:
            return {None: None}
    raise ValueError('Unsupported slice syntax')


@classmethod
def _from_dict(cls, _dict):
    """Initialize a DeleteModelResult object from a json dictionary."""
    args = {}
    if 'status' in _dict:
        args['status'] = _dict.get('status')
    else:
        raise ValueError(
            "Required property 'status' not present in DeleteModelResult JSON")
    return cls(**args)


def reverse_bits(i, n):
    """Reverse the bits of the ``n``-bit decimal number ``i``.

    Examples:
        >>> reverse_bits(12, 7)
        24
        >>> reverse_bits(0, 1)
        0
        >>> reverse_bits(1, 2)
        2
    """
    return int(bin(i)[2:].zfill(n)[::-1], 2)


def merge_noun_chunks(doc):
    """Merge noun chunks into a single token.

    doc (Doc): The Doc object.
    RETURNS (Doc): The Doc object with merged noun chunks.

    DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks
    """
    if not doc.is_parsed:
        return doc
    with doc.retokenize() as retokenizer:
        for np in doc.noun_chunks:
            attrs = {'tag': np.root.tag, 'dep': np.root.dep}
            retokenizer.merge(np, attrs=attrs)
    return doc


def struct_encode(schema, obj, outstream, endianness='='):
    """
    In the future, this function will be used to encode a structure into
    a stream. For the moment, it just raises :py:exc:`NotImplementedError`.
    """
    raise NotImplementedError


def _zero_triband(a, lower=0):
    """
    Explicitly zero out unused elements of a real symmetric banded matrix.

    INPUTS:
       a   -- a real symmetric banded matrix (either upper or lower hald)
       lower   -- if True, a is assumed to be the lower half

    """
    nrow, ncol = a.shape
    if lower:
        for i in range(nrow):
            a[(i), ncol - i:] = 0.0
    else:
        for i in range(nrow):
            a[(i), 0:i] = 0.0
    return a


def normalize(arr):
    """This normalizes an array to values between 0 and 1.

    Parameters
    ----------
    arr : ndarray

    Returns
    -------
    ndarray of float
        normalized array
    """
    ptp = arr.max() - arr.min()
    if ptp == 0:
        ptp = 1
    scaled_arr = (arr - arr.min()) / ptp
    return scaled_arr


def is_correct(grading_results):
    """The grading protocol provides grading_results, a dictionary which
    provides the count of tests passed, failed or locked for a single
    question. Return True if all tests have passed.
    """
    if grading_results['locked'] > 0:
        return False
    return sum(grading_results.values()) == grading_results['passed']


@classmethod
def green(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``."""
    return cls(3066993)


def write(response, file, chunk_size=8192):
    """
    Load the data from the http request and save it to disk
    :param response: data returned from the server
    :param file:
    :param chunk_size: size chunk size of the data
    :return:
    """
    bytes_written = 0
    while 1:
        chunk = response.read(chunk_size)
        bytes_written += len(chunk)
        if not chunk:
            break
        file.write(chunk)
    return bytes_written


def detect_line_sep(content):
    """Parse line separator from content.

    >>> detect_line_sep('\\r\\n')
    '\\r\\n'
    >>> detect_line_sep('\\r')
    '\\r'
    >>> detect_line_sep('\\n')
    '\\n'
    >>> detect_line_sep('')
    '\\n'
    """
    if '\r\n' in content:
        return '\r\n'
    elif '\r' in content:
        return '\r'
    else:
        return '\n'


def channels_fcurves_enable():
    """Clears ‘disabled’ tag from all F-Curves to get broken F-Curves working again

    """
    pass


def challenge(environ, status, app_headers, forget_headers):
    """ args -> WSGI application or None

        o 'environ' is the WSGI environment.

        o 'status' is the status written into start_response by the
          downstream application.

        o 'app_headers' is the headers list written into start_response by the
          downstream application.

        o 'forget_headers' is a list of headers which must be passed
          back in the response in order to perform credentials reset
          (logout).  These come from the 'forget' method of
          IIdentifier plugin used to do the request's identification.

        Examine the values passed in and return a WSGI application
        (a callable which accepts environ and start_response as its
        two positional arguments, ala PEP 333) which causes a
        challenge to be performed.  Return None to forego performing a
        challenge.
        """


def classinit_pic_quantizers(cls):
    """
        Decorator that adds the PIC quantizer static tables to *cls*.
        """
    cls._quantizer = []
    cls._quantizer9 = []
    cls._quantizer81 = []
    for i in range(-255, -20):
        cls._quantizer.append(-4)
    for i in range(-20, -6):
        cls._quantizer.append(-3)
    for i in range(-6, -2):
        cls._quantizer.append(-2)
    for i in range(-2, 0):
        cls._quantizer.append(-1)
    cls._quantizer.append(0)
    for i in range(1, 3):
        cls._quantizer.append(1)
    for i in range(3, 7):
        cls._quantizer.append(2)
    for i in range(7, 21):
        cls._quantizer.append(3)
    for i in range(21, 256):
        cls._quantizer.append(4)
    for q in cls._quantizer:
        cls._quantizer9.append(9 * q)
        cls._quantizer81.append(81 * q)
    return cls


def get_referenced_errordata(err_id):
    """ get data for referenced errors
        """


@classmethod
def from_name(cls, name):
    """Create an enum value from a name"""
    try:
        return cls[name.upper()]
    except KeyError:
        pass
    raise ValueError('%r is not a valid %s' % (name, cls.__name__))


def generate_template(filepath, for_level=0):
    """Generate a template file using the Minigame APIs.

    Arguments:
        filepath (str): The path to where the template file will be written.
        for_level (int): The corresponding level for the minigame. Defaults to 0.
    """
    template = (
        """#
# This script corresponds to the Advanced Mode script for Level %s in the minigame.
# It is recommended to keep the appropriate template code to start. Remember that the goal is to
# collect all coins and reach the exit.
#
# To access the documentation for the minigame APIs, either go to Settings > Minigame and click
# "Open Documentation", go to Help > Documentation, or visit the following link in your browser:
# https://fira.marquiskurt.net/api/. Go to https://fira.marquiskurt.net/gameplay.html#limitations-1
# to view the limitations of using the official API as called here.
#
# If you want to use a third-party tool or framework instead of the official Fira API and want to
# sideload in a virtual machine file, do not write any code in this file. More information can be
# found at https://fira.marquiskurt.net/implementation.html#obtaining-code-from-third-party-tools.
#

# Import the level information APIs.
from uvn_fira.api import get_level_information, CSPlayer, CSWorld

# Get all of the information for this particular level.
game_player, game_world = get_level_information(%s,
                                                fn_path=renpy.config.savedir + "/minigame/",
                                                exists=renpy.loadable,
                                                load=renpy.exports.file) # type: (CSPlayer, CSWorld)

# WRITE CODE HERE
"""
         % (for_level, for_level))
    with open(filepath, 'w+') as file_obj:
        file_obj.write(template)


def contract_arguments(amount, address):
    """
    Get contract arguments.

    :param amount: bytom amount.
    :type amount: int
    :param address: bytom address.
    :type address: str
    :returns: list -- bytom contract arguments.

    >>> from shuttle.providers.bytom.utils import contract_arguments
    >>> contract_arguments(bytom_amount, bytom_address)
    [...]
    """
    return [dict(type=str('integer'), value=amount), dict(type=str(
        'address'), value=address), dict(type=str('data'), value=str())]


def push_indexed_params(params, key, vals):
    """Populate the params dict for list of vals

    Here the key would be changed from plural to
    singular, dropping the last 's'.
    So --image-ids jmi-xxx jmi-yyy would be treated
    as ImageId.1=jmi-xxx&ImageId.2=jmi-yyy

    param params: dictionary to populate

    param key: key to be used in the dictionary

    param vals: list of values to be saved in the dict

    return: Nothing
    """
    if key[-1] == 's':
        key = key[:-1]
    idx = 0
    for val in vals:
        idx += 1
        elements = val
        key_index = key + '.' + str(idx)
        elements = val.split(',')
        if len(elements) == 1 and val.find('=') == -1:
            params[key_index] = val
            continue
        for element in elements:
            if element.find('=') != -1:
                parts = element.split('=')
                if len(parts) != 2:
                    msg = 'Unsupported value ' + element + 'given in request.'
                    raise ValueError(msg)
                element_key, element_val = parts[0], parts[1]
                if element_key == 'Values':
                    element_key = element_key[:-1] + '.' + str(idx)
                updated_key = key_index + '.' + element_key
                params[updated_key] = element_val
            else:
                msg = 'Bad request syntax. Please see help for valid request.'
                raise ValueError(msg)


def pyAttrName2XmlAttrName(key):
    """
    The @pyAttrName2XmlAttrName@ converts the Python XML attribute name @key@ to an
    appropriate XML attribute identifier.
    If the *key* is 'cssClass' then it is translated into 'class'.
    If there is an HTML5 attribute *data_xxxx* used, then change that to *data-xxxx*.
    """
    if key == 'cssClass':
        key = 'class'
    elif key == 'cssId':
        key = 'id'
    elif key.startswith('data'):
        key = key.replace('_', '-')
    return key


def checkBoundsByModel(solution, model):
    """ check if the flux distribution 'solution' violates any flux bounds
        defined for the reactions in the given model

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


def single_title(title):
    """Convert the two parts of an icon.sys title into one string."""
    title = title[0] + ' ' + title[1]
    return ' '.join(title.split())


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

        :param SharedLinkDownloadType val:
        :rtype: EventType
        """
    return cls('shared_link_download', val)


def _google_sheets():
    """
    Returns a query item matching messages that have Google Sheets attachments.

    """
    return f'has:spreadsheet'


def text_(s, encoding='latin-1', errors='strict'):
    """ If ``s`` is an instance of ``bytes``, return ``s.decode(encoding,
    errors)``, otherwise return ``s``"""
    if isinstance(s, bytes):
        return s.decode(encoding, errors)
    return s


def _nob_print_params(tab_length=2, line_length=40):
    """Defining parameters and special characters
       for nested object printing
    Inputs:
    ----------
    tab_length : Number of spaces describing a tab
    line_length : the maximum allowed number of characters in a line

    Returns :
    ---------
    chars : a dictionnary gathering special characters and max line length
    """
    chars = dict()
    chars['vertical_bar'] = u'┃'
    chars['horizontal_bar'] = u'━'
    chars['child_bar'] = u'┓'
    chars['standard_child'] = u'┣'
    chars['last_child'] = u'┗'
    chars['tab'] = ' ' * tab_length
    chars['max_length'] = line_length
    return chars


def args_to_dict(args):
    """Convert command line arguments in a comma separated string to a dictionary

    Args:
        args (str): Command line arguments

    Returns:
        DictUpperBound[str,str]: Dictionary of arguments

    """
    arguments = dict()
    for arg in args.split(','):
        key, value = arg.split('=')
        arguments[key] = value
    return arguments


def queryAttribute(name, lang=None, default=None):
    """Get name attribute of the language specific translation or default.

        Parameter:

        name -- Attribute name.

        language -- Language code for example 'de'. If None the default language
        is returned.

        default -- Any object.

        Return Value:

        object -- Evaluate of the language specific data object or return default
        if not found.

        """


def strftime(format):
    """Format the date/time using the *current timezone representation*."""


def reorder():
    """Called when the items in the grid are reordered"""


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


@classmethod
def xform(cls, column_headers, lines):
    """
        Transform column values and yield just the line info.

        :param column_headers: the column headers
        :type column_headers: list of str
        :param lines: information about each line
        :type lines: dict of str * str
        """
    key = column_headers[0]
    for line in lines:
        line_info = line['node']
        line_info[key] = cls.calculate_prefix(line) + line_info[key]
        yield line_info


def reduce_list_of_bags_of_words(list_of_keyword_sets):
    """
    Reduces a number of keyword sets to a bag-of-words.

    Input:  - list_of_keyword_sets: This is a python list of sets of strings.

    Output: - bag_of_words: This is the corresponding multi-set or bag-of-words, in the form of a python dictionary.
    """
    bag_of_words = dict()
    get_bag_of_words_keys = bag_of_words.keys
    for keyword_set in list_of_keyword_sets:
        for keyword in keyword_set:
            if keyword in get_bag_of_words_keys():
                bag_of_words[keyword] += 1
            else:
                bag_of_words[keyword] = 1
    return bag_of_words


def find_df_dx(f, x):
    """Find the partial derivative of f with respect to given x

    EXAMPLES
    =========
    >>> x = VariableNode(3)
    >>> f = 2 * x
    >>> print(find_df_dx(f=v, x=x))
    6
    """
    f._grad = 1
    return x.grad


def create_astropy_constant(py_obj, h_group, call_id=0, **kwargs):
    """ dumps an astropy constant

    Args:
        py_obj: python object to dump; should be a python type (int, float, bool etc)
        h_group (h5.File.group): group to dump data into.
        call_id (int): index to identify object's relative location in the iterable.
    """
    d = h_group.create_dataset('data_%i' % call_id, data=py_obj.value,
        dtype='float64')
    d.attrs['type'] = [b'astropy_constant']
    d.attrs['unit'] = [str(py_obj.unit)]
    d.attrs['abbrev'] = [str(py_obj.abbrev)]
    d.attrs['name'] = [str(py_obj.name)]
    d.attrs['reference'] = [str(py_obj.reference)]
    d.attrs['uncertainty'] = [py_obj.uncertainty]
    if py_obj.system:
        d.attrs['system'] = [py_obj.system]


def print_bdd(bdd):
    """Print bdd at stdout."""
    for var, val in bdd.get_str_values().items():
        print(var, '=', val)


@classmethod
def Sym(cls, s, location=None):
    """Construct a symbol token."""
    return cls(cls.SYMBOL, s, location)


def _get_petsc_vec_array_new(vec):
    """
    Get the array of values for the given PETSc vector.

    Helper function to handle a petsc backwards incompatibility.

    Parameters
    ----------
    vec : petsc vector
        Vector whose data is being requested.

    Returns
    -------
    ndarray
        A readonly copy of the array of values from vec.
    """
    return vec.getArray(readonly=True)


@staticmethod
def gcd(a, b):
    """
        Calculates the Greatest Common Divisor.

        :param a: the first number.
        :param b: the second number.
        :return: GCD(a, b)
        """
    while b:
        a, b = b, a % b
    return a


def configget(config, section, var, default):
    """
    gets parameter from config file and returns a default value
    if the parameter is not found
    """
    try:
        ret = config.get(section, var)
    except:
        print('returning default (' + default + ') for ' + section + ':' + var)
        ret = default
    return ret


def hnum(num, units='decimal'):
    """
    returns rounded human readable str with units suffix

    >>> khnum.hnum(123456789)  # decimal
    '123.5M'  # million

    >>> khnum.hnum(123456789, 'b')  # bytes
    '123.5MB'  # megabytes

    >>> khnum.hnum(123456789, 's')  # SI
    '117.7MiB'  # mebibytes

    >>> khnum.hnum(123456789e24, 'si')
    '102121062.3YiB'  # yobibytes

    raises ValueError for un-supported units

    Power  Decimal   Bytes      SI (binary)
    ---------------------------------------------
    10^3   Kilo (K)  Kilo (KB)  1024^1 Kibi (KiB)
    10^6   Mill (M)  Mega (MB)  1024^2 Mebi (MiB)
    10^9   Bill (B)  Giga (GB)  1024^3 Gibi (GiB)
    10^12  Tril (T)  Tera (TB)  1024^4 Tebi (TiB)
    10^15  Quad (Q)  Peta (PB)  1024^5 Pebi (PiB)
    10^18  Quin (Qn) Exa- (EB)  1024^6 Exbi (EiB)
    10^21  Sext (S)  Zeta (ZB)  1024^7 Zebi (ZiB)
    10^24  Sept (Sp) Yota (YB)  1024^8 Yobi (YiB)
    """
    if units.lower().startswith('d'):
        units = ['', 'K', 'M', 'B', 'T', 'Q', 'Qn', 'S']
        boundary = 1000.0
        last_unit = 'Sp'
        suffix = ''
    elif units.lower().startswith('b'):
        units = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']
        boundary = 1000.0
        last_unit = 'Y'
        suffix = 'B'
    elif units.lower().startswith('s'):
        units = ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']
        boundary = 1024.0
        last_unit = 'Yi'
        suffix = 'B'
    else:
        raise ValueError('unsupported units: %s' % units)
    for unit in units:
        if abs(num) < boundary:
            return '%3.1f%s%s' % (num, unit, suffix)
        num /= boundary
    return '%.1f%s%s' % (num, last_unit, suffix)


def get_min_max(mydata, min_max, mini, maxi, acc):
    """Find minimum and maximum indeces.

    Parameters
    ----------
    mydata : list
        List of cycle numbers to be checked for index of given min/max
    min_max : list
        List of min/max values to search for
    mini : dict
        Dictionary of found min cycle number of lists acc/rej
    maxi : dict
        Dictionary of found max cycle number of lists acc/rej
    acc : string
        'a' or 'r' for acc/rej lists, respectively

    Returns/updates
    ---------------
    mini, maxi : dict
        Stores values for min/max in acc and rej lists to the correct dicts.

    """
    for i, item in enumerate(mydata):
        if item == min_max[0]:
            mini[acc] = i
            break
        elif item > min_max[0]:
            mini[acc] = i - 1 if i > 0 else 0
            break
    for i, item in enumerate(mydata[mini[acc]:]):
        if item > min_max[1]:
            if i == 0:
                maxi[acc] = 0
                break
            else:
                maxi[acc] = mini[acc] + i - 1
                break
        elif i == len(mydata) - 1:
            maxi[acc] = len(mydata) - 1


def __len__():
    """Return the number of objects indexed."""


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

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

    """
    pass


def _offsets_equal(o1, o2):
    """
    Given two lists of (start, end) integer offset sets, returns
    whether they identify the same sets of characters.
    """
    if o1 == o2:
        return True
    return sorted(o1) == sorted(o2)


def get_app_name(cls):
    """Return the app_name associated with the given ViewPack class."""
    app_name = getattr(cls, 'app_name', None)
    if app_name is not None:
        return app_name
    return cls.__module__.partition('.')[0]


def n1_to(n, sgn='-', sep='.'):
    """converts a base negative one value to base ten"""
    l = len(n)
    if not l % 2:
        return -l // 2
    else:
        return l // 2 + 1


def free_bake_all():
    """Free all baked caches of all objects in the current scene

    """
    pass


def sample_sort(sample_names):
    """Sort sample names like a human.

    Our samples have occasionally used underscores and minus signs inconsistently
    in sample names as field separators or space substitutions. Therefore simple
    ASCII sorting can give surprises such as not grouping by prefix (since the
    underscore is sorted after the digits and letter):

        >>> sorted(["N01-a", "N01_b", "N01 c", "N011-a"])
        ['N01 c', 'N01-a', 'N011-a', 'N01_b']

    We specifically want "_" (ASCII , after the letters) to sort like " "
    or "-" (ASCII 32 or 45, both before the digits and letters). In case
    any samples are using plus/minus, will map underscore and space to
    the minus sign for sorting.

        >>> sample_sort(["N01-a", "N01_b", "N01 c", "N011-d"])
        ['N01-a', 'N01_b', 'N01 c', 'N011-a']

    """
    return sorted(sample_names, key=lambda _: _.replace('_', '-').replace(
        ' ', '-'))


def delta_chunk_apply(dc, bbuf, write):
    """Apply own data to the target buffer
    :param bbuf: buffer providing source bytes for copy operations
    :param write: write method to call with data to write"""
    if dc.data is None:
        write(bbuf[dc.so:dc.so + dc.ts])
    elif dc.ts < len(dc.data):
        write(dc.data[:dc.ts])
    else:
        write(dc.data)


def psi_Mg_CO3_SO4_HMW84(T, P):
    """c-a-a': magnesium carbonate sulfate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


@staticmethod
def __and(A, B):
    """Return a new Set that is an intersection of A and B."""
    return A - ~B


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


@staticmethod
def fix_table(tree):
    """
        Force tables to have table-layout: auto, no borders on table data
        """
    for table in tree.findall('.//table'):
        table.set('style', 'table-layout:auto')
        for td in table.findall('.//td'):
            newstyle = td.get('style', '')
            if newstyle:
                newstyle += '; '
            newstyle += 'border:none'
            td.set('style', newstyle)


def get_bytes(data):
    """
    If data is not bytes, encode it.

    :param data: the input data
    :return: the bytes of data
    """
    if not isinstance(data, bytes):
        data = data.encode('utf-8')
    return data


def word2bytes(value):
    """
    >>> word2bytes(0xff09)
    (255, 9)

    >>> [hex(i) for i in word2bytes(0xffab)]
    ['0xff', '0xab']

    >>> word2bytes(0xffff +1)
    Traceback (most recent call last):
    ...
    AssertionError
    """
    assert 0 <= value <= 65535
    return value >> 8, value & 255


def includeme(config):
    """
    void function used to ensure the models are added to the metadatas
    """
    pass


def set_file_storage(source='local', **kwargs):
    """ Creates file storage depending

    Parameters
    ----------
    source: str
        Default is 'local' which will create
        file storage in the local environment
    kwargs: dict
        Contains data to setup S3 storage
    """
    pass


def adjustHF(H, F, n_new, n_old):
    """
    adjust hit/false alarm rate for ceiling effects
    according to Macmillan&Creelman, pp8
    urut/nov06
    """
    if H == 1:
        H = 1 - 1 / (2 * n_old)
    if F == 1:
        F = 1 - 1 / (2 * n_new)
    if H == 0:
        H = 1 / (2 * n_old)
    if F == 0:
        F = 1 / (2 * n_new)
    return H, F


def set_log_level(logger, log_level: int):
    """Set log level for the given logger."""
    logger.setLevel(log_level)
    for handler in logger.handlers:
        handler.setLevel(log_level)


def _bulk_deregister(notifier, registered, details_filter=None):
    """Bulk deregisters callbacks associated with many states."""
    while registered:
        state, cb = registered.pop()
        notifier.deregister(state, cb, details_filter=details_filter)


def camel_case(name):
    """Convert words into CamelCase."""
    return ''.join(name.capitalize().split())


def is_filter_like(filter_like):
    """Check if the provided dict looks like a search request or filter."""
    if 'item_types' in filter_like or 'filter' in filter_like:
        filter_like = filter_like.get('filter', {})
    return 'type' in filter_like and 'config' in filter_like


def _read_text(file):
    """ Read a file in utf-8 encoding."""
    with open(file, mode='r', encoding='utf-8') as f:
        return f.read()


def include_static_jquery():
    """ include static files """
    return None


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 _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


def p_main(t):
    """main : files shape dims"""
    t[0] = t[1], t[2], t[3]


def calculate_normalization_metrics(genome_dict: dict) ->None:
    """
    Calculates the normalized abundance values for each header's RefSeq instance in genome_dict
        1. Reads per kilobase (RPK) is calculated using the reference sequence's length and number of reads (provided
        by the user via CLI)
        2. Fragments per kilobase per million mappable reads (FPKM) is calculated from the number of fragments
        (this is different from reads by, in a paired-end library, forward and reverse pair makes up one fragment)
        normalized by the reference sequence length and the number of reads mapped.
        2. Transcripts per million (TPM) is calculated similarly to FPKM but the order of operations is different.

    :param genome_dict: A dictionary of RefSeq instances indexed by headers (sequence names)
    :return: None
    """
    rpk_sum = 0
    for header in sorted(genome_dict.keys()):
        ref_seq = genome_dict[header]
        ref_seq.calc_rpk(ref_seq.weight_total)
        rpk_sum += ref_seq.rpk
    for header in sorted(genome_dict.keys()):
        ref_seq = genome_dict[header]
        if ref_seq.weight_total == 0:
            continue
        ref_seq.calc_fpkm(ref_seq.weight_total)
    denominator = rpk_sum / 1000000.0
    for header in genome_dict.keys():
        ref_seq = genome_dict[header]
        ref_seq.calc_tpm(denominator)
    return


@staticmethod
def check_louie(receiver, signal, method='connect'):
    """
        Check if the connect or disconnect method's arguments are valid in
        order to automatically convert to EventDispatcher's bind
        The old valid signals are:

            - Coherence.UPnP.Device.detection_completed
            - Coherence.UPnP.RootDevice.detection_completed
            - Coherence.UPnP.Device.removed
            - Coherence.UPnP.RootDevice.removed

        .. versionadded:: 0.9.0
        """
    if not callable(receiver):
        raise Exception(
            'The receiver should be callable in order to use the method {method}'
            )
    if not signal:
        raise Exception(f'We need a signal in order to use method {method}')
    if not (signal.startswith('Coherence.UPnP.Device.') or signal.
        startswith('Coherence.UPnP.RootDevice.')):
        raise Exception(
            'We need a signal an old signal starting with: "Coherence.UPnP.Device." or "Coherence.UPnP.RootDevice."'
            )


def unshape_data(data):
    """
    Return 1D version of data.
    """
    return data.flatten()


def total_energy_ejected(t):
    """
    Thermal and kinetic energy released by each type of SN up to the time t after the explosion
    where tc is the characteristic cooling time of the shell sorrounding the remnant (53000 yrs)
    from Ferrini & Poggiantti, 1993, ApJ, 410, 44F

    """
    if t <= 0:
        return 0.0
    tc = 5.3e-05
    if t > tc:
        rt = (tc / t) ** 0.4
        return 1 - 0.44 * rt ** 2 * (1 - 0.41 * rt) - 0.22 * rt ** 2
    else:
        return 9811.32 * t


def convert_blocking(blocking):
    """Converts a multi-type blocking variable into its derivatives."""
    timeout = None
    if not isinstance(blocking, bool):
        timeout = float(blocking)
        blocking = True
    return blocking, timeout


def tagtype(tagname):
    """Return the type of a given tag."""


@staticmethod
def _get_error(response):
    """Get error message from API response

        :param dict response: API response
        :return: Error message as :func:`str`
        """
    if 'error' in response:
        err = response.get('error')
    elif 'errors' in response:
        err = response.get('errors')
    else:
        err = 'No error message found'
    return err


def _Refractive(rho, T, l=0.5893):
    """Equation for the refractive index

    Parameters
    ----------
    rho : float
        Density, [kg/m³]
    T : float
        Temperature, [K]
    l : float, optional
        Light Wavelength, [μm]

    Returns
    -------
    n : float
        Refractive index, [-]

    Notes
    ------
    Raise :class:`NotImplementedError` if input isn't in limit:

        * 0 ≤ ρ ≤ 1060
        * 261.15 ≤ T ≤ 773.15
        * 0.2 ≤ λ ≤ 1.1

    Examples
    --------
    >>> _Refractive(997.047435, 298.15, 0.2265)
    1.39277824
    >>> _Refractive(30.4758534, 773.15, 0.5893)
    1.00949307

    References
    ----------
    IAPWS, Release on the Refractive Index of Ordinary Water Substance as a
    Function of Wavelength, Temperature and Pressure,
    http://www.iapws.org/relguide/rindex.pdf
    """
    if rho < 0 or rho > 1060 or T < 261.15 or T > 773.15 or l < 0.2 or l > 1.1:
        raise NotImplementedError('Incoming out of bound')
    Lir = 5.432937
    Luv = 0.229202
    d = rho / 1000.0
    Tr = T / 273.15
    L = l / 0.589
    a = [0.244257733, 0.00974634476, -0.00373234996, 0.000268678472,
        0.0015892057, 0.00245934259, 0.90070492, -0.0166626219]
    A = d * (a[0] + a[1] * d + a[2] * Tr + a[3] * L ** 2 * Tr + a[4] / L **
        2 + a[5] / (L ** 2 - Luv ** 2) + a[6] / (L ** 2 - Lir ** 2) + a[7] *
        d ** 2)
    return ((2 * A + 1) / (1 - A)) ** 0.5


def view_filter(**kwargs):
    """
    Filters blog posts by year/month/day, category, tag or author
    """
    from bambu_blog.models import Post, Category
    posts = Post.objects.select_related().live()
    if 'year' in kwargs:
        posts = posts.filter(date__year=int(kwargs['year']))
        if 'month' in kwargs:
            posts = posts.filter(date__month=int(kwargs['month']))
            if 'day' in kwargs:
                posts = posts.filter(date__day=int(kwargs['day']))
    if 'category' in kwargs:
        posts = posts.filter(categories__slug=kwargs['category'])
    elif 'tag' in kwargs:
        posts = posts.filter(tags__slug=kwargs['tag'])
    elif 'username' in kwargs:
        posts = posts.filter(author__username=kwargs['username'])
    return posts


def as_attribute_access():
    """Return this node as IAttributeAccess implementing object.
        """


def get_study_uid_dict(checked_uids, parsed_dicom_data, multi_plan_only=False):
    """
    This thread iterates through self.checked_uids which contains plan uids, but we need to iterate through
    study instance uids so that plans on the same study are imported adjacently.
    :return: a dictionary with study uids for the keys and a list of associated plan uids for values
    :rtype: dict
    """
    study_uids = {}
    for plan_uid in checked_uids:
        study_uid = parsed_dicom_data[plan_uid
            ].study_instance_uid_to_be_imported
        if study_uid not in list(study_uids):
            study_uids[study_uid] = []
        study_uids[study_uid].append(plan_uid)
    if multi_plan_only:
        for study_uid in list(study_uids):
            if len(study_uids[study_uid]) < 2:
                study_uids.pop(study_uid)
    return study_uids


def sizes_to_offsets(sizes):
    """takes list of (frame_size, frame_frames) tuples
    and converts it to a list of (cumulative_size, frame_frames)
    tuples"""
    current_position = 0
    offsets = []
    for frame_size, frame_frames in sizes:
        offsets.append((current_position, frame_frames))
        current_position += frame_size
    return offsets


def add_path(G, nodes, t, **attr):
    """Add a path at time t.

            Parameters
            ----------
            G : graph
                A DyNetx graph

            nodes : iterable container
                A container of nodes.

            t : snapshot id (default=None)
                snapshot id

            See Also
            --------
            add_path, add_cycle

            Examples
            --------
            >>> G = dn.DynGraph()
            >>> dn.add_path(G, [0,1,2,3], t=0)
            """
    nlist = list(nodes)
    edges = list(zip(nlist[:-1], nlist[1:]))
    G.add_interactions_from(edges, t, **attr)


def _is_python_file(filename):
    """Check if the input file looks like a Python script

    Returns True if the filename ends in ".py" or if the first line
    contains "python" and "#!", returns False otherwise.

    """
    if filename.endswith('.py'):
        return True
    else:
        with open(filename, 'r') as file_handle:
            first_line = file_handle.readline()
        return 'python' in first_line and '#!' in first_line


def custom_paginator(f, l, **kwargs):
    """Simple custom paginator for those can_pageniate() returns false
    :param f: API function
    :param l: name of the list object to paginate
    :param kwargs: Args passes to the API function
    :return: iterator of result object
    """
    next_token = None
    while True:
        if next_token is None:
            r = f(**kwargs)
        else:
            r = f(NextToken=next_token, **kwargs)
        for i in r[l]:
            yield i
        try:
            next_token = r['NextToken']
        except KeyError:
            break


def _no_overlap(y, z, y1, z1, y2, z2, pt_id, pt_1_id, pt_2_id):
    """
    Checks if a point (y,z) is inside a line given by (y1,z1) and
    (y2,z2). Also check if the point id matches with the ids from the line.

    Returns
    -------
    Boolean
    """
    if y < min(y1, y2) or y > max(y1, y2) or z < min(z1, z2) or z > max(z1, z2
        ):
        return True
    elif pt_id == pt_1_id or pt_id == pt_2_id:
        return True
    else:
        return False


def PolsAccDeath(t):
    """Number of policies: Accidental death"""
    return 0


def p_statement_create_db(p):
    """statement : CREATE DATABASE identifier"""
    p[0] = p[1:]


@staticmethod
def calc_parabola_param(pt1, pt2, pt3):
    """
        define a parabola using three points
        :param pt1: First point (x,y)
        :param pt2: Second point (x,y)
        :param pt3: Third point (x,y)
        :return tuple of a, b, and c for parabola a(x^2) + b*x + c = 0
        """
    x1, y1 = pt1
    x2, y2 = pt2
    x3, y3 = pt3
    _m_ = (x1 - x2) * (x1 - x3) * (x2 - x3)
    a_param = (x3 * (y2 - y1) + x2 * (y1 - y3) + x1 * (y3 - y2)) / _m_
    b_param = (x3 * x3 * (y1 - y2) + x2 * x2 * (y3 - y1) + x1 * x1 * (y2 - y3)
        ) / _m_
    c_param = (x2 * x3 * (x2 - x3) * y1 + x3 * x1 * (x3 - x1) * y2 + x1 *
        x2 * (x1 - x2) * y3) / _m_
    return a_param, b_param, c_param


@classmethod
def add_field(cls, rname, relation, model, table, ftype):
    """ Insert a relationship definition

        :param rname: name of the relationship
        :param relation: instance of the relationship
        :param model: namespace of the model
        :param table: name of the table of the model
        :param ftype: type of the AnyBlok Field
        """
    local_column = relation.info.get('local_column')
    remote_column = relation.info.get('remote_column')
    remote_model = relation.info.get('remote_model')
    remote_name = relation.info.get('remote_name')
    label = relation.info.get('label')
    nullable = relation.info.get('nullable', True)
    vals = dict(code=table + '.' + rname, model=model, name=rname,
        local_column=local_column, remote_model=remote_model, remote_name=
        remote_name, remote_column=remote_column, label=label, nullable=
        nullable, ftype=ftype)
    cls.insert(**vals)
    if remote_name:
        remote_type = 'Many2One'
        if ftype == 'Many2One':
            remote_type = 'One2Many'
        elif ftype == 'Many2Many':
            remote_type = 'Many2Many'
        elif ftype == 'One2One':
            remote_type = 'One2One'
        m = cls.registry.get(remote_model)
        vals = dict(code=m.__tablename__ + '.' + remote_name, model=
            remote_model, name=remote_name, local_column=remote_column,
            remote_model=model, remote_name=rname, remote_column=
            local_column, label=remote_name.capitalize().replace('_', ' '),
            nullable=True, ftype=remote_type, remote=True)
        cls.insert(**vals)