def rsqrt(data=None, out=None, name=None, **kwargs):
    """Returns element-wise inverse square-root value of the input.

    .. math::
       rsqrt(x) = 1/\\sqrt{x}

    Example::

       rsqrt([4,9,16]) = [0.5, 0.33333334, 0.25]

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

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L193

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

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

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


def t_nowdoc_END_NOWDOC(t):
    """(?<=\\n)[A-Za-z_][\\w_]*"""
    if t.value == t.lexer.nowdoc_label:
        del t.lexer.nowdoc_label
        t.lexer.pop_state()
    else:
        t.type = 'ENCAPSED_AND_WHITESPACE'
    return t


def split():
    """Split off selected bones from connected unselected bones

    """
    pass


def round_if_near_integer(a, epsilon=0.0001):
    """
    Round a to the nearest integer if that integer is within an epsilon
    of a.
    """
    if abs(a - round(a)) <= epsilon:
        return round(a)
    else:
        return a


def expand_rectangle(rect, scale):
    """
    Increase each side of the rectangle by scale.
    """
    x, y, w, h = rect
    w_new = int(w + w * scale * 2)
    h_new = int(h + h * scale * 2)
    x_new = max(0, int(x - w * scale))
    y_new = max(0, int(y - h * scale))
    return x_new, y_new, w_new, h_new


def format_seconds(total):
    """Format number of seconds to MM:SS.DD form."""
    minutes, seconds = divmod(total, 60)
    return '%2d:%05.2f' % (minutes, seconds)


def unhide_all():
    """Unhide all objects and collections

    """
    pass


def FormatDescriptorToPython(i):
    """
    Format a descriptor into a form which can be used as a python attribute

    example::

        >>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V')
        'Ljava_lang_LongLjava_lang_LongZZV

    :param i: name to transform
    :rtype: str
    """
    i = i.replace('/', '_')
    i = i.replace(';', '')
    i = i.replace('[', '')
    i = i.replace('(', '')
    i = i.replace(')', '')
    i = i.replace(' ', '')
    i = i.replace('$', '')
    return i


def _spot_worker(device: dict):
    """
    Worker to grab spotter data

    :param device: Dictionary containing the spotter id and name

    :return: Spotter object updated from the Sofar api with its latest data values
    """
    from pysofar.spotter import Spotter
    _id = device['spotterId']
    _name = device['name']
    sptr = Spotter(_id, _name)
    sptr.update()
    return sptr


def remove_fpgm_table(tt):
    """Removes fpgm table from a fontTools.ttLib.TTFont object"""
    try:
        del tt['fpgm']
    except KeyError:
        pass


def _to_unicode(s):
    """
    decode a string as ascii or utf8 if possible (as required by the sftp
    protocol).  if neither works, just return a byte string because the server
    probably doesn't know the filename's encoding.
    """
    try:
        return s.encode('ascii')
    except (UnicodeError, AttributeError):
        try:
            return s.decode('utf-8')
        except UnicodeError:
            return s


@classmethod
def fromflat(cls, flat):
    """
        Create an instance of this from new Bernoulli input

        :param flat: ([float]) the Bernoulli input data
        :return: (ProbabilityDistribution) the instance from the given Bernoulli input data
        """
    return cls(flat)


def hash_to_hex_str(x):
    """Convert a little-endian binary hash to displayed hex string.

    Display form of a binary hash is reversed and converted to hex.
    """
    return bytes(reversed(x)).hex()


def assert_frame_equal(left, right, data_function=None, data_args=None):
    """
    For unit testing equality of two DataFrames.

    :param left: first DataFrame
    :param right: second DataFrame
    :param data_function: if provided will use this function to assert compare the df.data
    :param data_args: arguments to pass to the data_function
    :return: nothing
    """
    if data_function:
        data_args = {} if not data_args else data_args
        data_function(left.data, right.data, **data_args)
    else:
        assert left.data == right.data
    assert left.index == right.index
    assert left.columns == right.columns
    assert left.index_name == right.index_name
    assert left.sort == right.sort
    assert left.dropin == right.dropin


def iter_parse(term, text):
    """
    Generator yields (text, capability) for characters of ``text``.

    value for ``capability`` may be ``None``, where ``text`` is
    :class:`str` of length 1.  Otherwise, ``text`` is a full
    matching sequence of given capability.
    """
    for match in term._caps_compiled_any.finditer(text):
        name = match.lastgroup
        value = match.group(name)
        if name == 'MISMATCH':
            yield value, None
        else:
            yield value, term.caps[name]


def render(request):
    """
        Get the document for this L{IRenderable}.

        @type request: L{IRequest} provider or L{None}
        @param request: The request in response to which this method is being
            invoked.

        @return: An object which can be flattened.
        """


def uint2int32(value):
    """
    Convert an unsigned 32 bits integer into a signed 32 bits integer.

    >>> print(uint2int32(1))
    1
    >>> print(uint2int32(2**32 + 1))  # ignore bits larger than 32 bits
    1
    >>> print(uint2int32(4294967295))
    -1
    >>> print(uint2int32(4294967294))
    -2
    >>> print(uint2int32(18446744073709551615))
    -1
    """
    value = value & 4294967295
    if value & 2147483648:
        v = value - 4294967296
    else:
        v = value
    return v


def get_restricted_translations():
    """
        get all the translated objects (including the context) if permitted
        """


def get_input(text):
    """wrapped input to enable unit testing / patching"""
    return input(text)


def duration_str(t1, t2):
    """String difference between pendulum datetimes."""
    delta = t2 - t1
    d = delta.days
    h = delta.hours
    m = delta.minutes
    if d > 0:
        result = '%dd-%d:%02d' % (d, h, m)
    else:
        result = '%d:%02d' % (h, m)
    return result


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

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


def where(condition):
    """
    Generates a where clause representing given condition.

    Parameters
    ----------
    condition: Q.C
        A condition built by `Q` and concatenated with operators.

    Returns
    -------
    str
        A where clause starting from `WHERE` or empty string if the condition is empty.
    """
    return ('', []) if condition.clause == '' else (f'WHERE {condition.clause}'
        , list(condition.params))


def highcharts_plot_view(context):
    """
    Dependencies for highcharts_plot_view gizmo.
    """
    return ('tethys_gizmos/vendor/highcharts/js/highcharts.js',
        'tethys_gizmos/vendor/highcharts/js/highcharts-more.js',
        'tethys_gizmos/vendor/highcharts/js/modules/exporting.js')


def close():
    """Reverse of :meth:`connect`."""


@classmethod
def getiddname(cls):
    """Get the name of the current IDD used by eppy.

        Returns
        -------
        str

        """
    return cls.iddname


@staticmethod
def _indent(line):
    """ Find out how much a line is left-indented. """
    return len(line) - len(line.lstrip())


def demix2(servo1, servo2, gain=0.5):
    """de-mix a mixed servo output"""
    s1 = servo1 - 1500
    s2 = servo2 - 1500
    out1 = (s1 + s2) * gain
    out2 = (s1 - s2) * gain
    return out2 + 1500


@classmethod
def gauss(cls, mean, stdDev):
    """Returns a normally distributed random variable."""
    A = 0.0
    _0 = True
    i = 0
    while True:
        if _0 is True:
            _0 = False
        else:
            i += 1
        if not i < 12:
            break
        A = A + cls.Math.random()
    return (A - 6.0) * stdDev + mean


def find_nearest_duration(dur, possible_durations, direction='<>'):
    """
    dur: a Dur or a float (will be converted to Dur via .fromfloat)
    possible_durations: a seq of Durs
    direction: "<"  -> find a dur from possible_durations which is lower than dur
               ">"  -> find a dur from possible_durations which is higher than dur
               "<>" -> find the nearest dur in possible_durations

    Example
    ~~~~~~~

    >>> possible_durations = [0.5, 0.75, 1]
    >>> find_nearest_duration(0.61, possible_durations, "<>")
    0.5

    """
    possdurs = sorted(possible_durations, key=lambda d: float(d))
    inf = float('inf')
    if dur < possible_durations[0]:
        return possible_durations[0] if direction != '<' else None
    elif dur > possible_durations[-1]:
        return possible_durations[-1] if direction != '>' else None
    if direction == '<':
        nearest = sorted(possdurs, key=lambda d: abs(dur - d) if d < dur else
            inf)[0]
        return nearest if nearest < inf else None
    elif direction == '>':
        nearest = sorted(possdurs, key=lambda d: abs(dur - d) if d > dur else
            inf)[0]
        return nearest if nearest < inf else None
    elif direction == '<>':
        nearest = sorted(possdurs, key=lambda d: abs(dur - d))[0]
        return nearest
    else:
        raise ValueError("direction should be one of '>', '<', or '<>'")


@classmethod
def parse(cls, raw_str, parser):
    """Factory for :class:`apacheconfig.BlockNode` from a config string.

        Args:
            raw_str (str): The text to parse.
            parser (:class:`apacheconfig.ApacheConfigParser`): parser object
                to use.
        Returns:
            :class:`apacheconfig.BlockNode` containing metadata parsed from
            ``raw_str``.
        """
    raw = parser.parse(raw_str)
    return cls(raw[1], parser)


def iterate(f, x):
    """Return an iterator yielding x, f(x), f(f(x)) etc.
    """
    while True:
        yield x
        x = f(x)


def snapshot_version(version):
    """
    Get the current release and snapshot version.

    Format is <debian-version>~<release>.gbp<short-commit-id>

    >>> snapshot_version('1.0-1')
    ('1.0-1', 0)
    >>> snapshot_version('1.0-1~1.test0')
    ('1.0-1~1.test0', 0)
    >>> snapshot_version('1.0-1~2.gbp1234')
    ('1.0-1', 2)
    """
    try:
        release, suffix = version.rsplit('~', 1)
        snapshot, commit = suffix.split('.', 1)
        if not commit.startswith('gbp'):
            raise ValueError
        else:
            snapshot = int(snapshot)
    except ValueError:
        release = version
        snapshot = 0
    return release, snapshot


def strip_diff_things(text):
    """Remove things from the text that make it look like a diff.

    The purpose of this is so we can run guess_lexer over the source text. If
    we have a diff of Python, Pygments might tell us the language is "Diff".
    Really, we want it to highlight it like it's Python, and then we'll apply
    the diff formatting on top.
    """
    s = ''
    for line in text.splitlines():
        if line.startswith(('diff --git', '--- ', '+++ ', 'index ', '@@ ',
            'Author:', 'AuthorDate:', 'Commit:', 'CommitDate:', 'commit ')):
            continue
        if line.startswith(('+', '-')):
            line = line[1:]
        s += line + '\n'
    return s


@staticmethod
def compose_account_number(number: str, bank_code: str) ->str:
    """
        Compose account number from number and bank code.

        Czech and Slovak bank accounts have account number separated from bank code using slash.
        """
    return '{}/{}'.format(number, bank_code)


def search(seq, val):
    """Search location of key in a sorted list.

    The method searches the location of a value in a list using
    binary searching algorithm. If it does not find the value, it return -1.

    Args:
        seq: A sorted list where to search the value.
        val: A value to search for.

    Returns:
        The location of the value in the sorted list if found.
        Otherwise returns -1.
    """
    lo, hi = 0, len(seq) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if val < seq[mid]:
            hi = mid - 1
        elif val > seq[mid]:
            lo = mid + 1
        else:
            return mid
    return -1


def model_with_weights(model, weights, skip_mismatch):
    """ Load weights for model.

    Args:
        model         : The model to load weights for.
        weights       : The weights to load.
        skip_mismatch : If True, skips layers whose shape of weights doesn't match with the model.
    """
    if weights is not None:
        model.load_weights(weights, by_name=True, skip_mismatch=skip_mismatch)
    return model


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

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


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

        :param ShowcaseChangeExternalSharingPolicyDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_change_external_sharing_policy_details', val)


def length_hint(obj, default=0):
    """
    Return an estimate of the number of items in obj.
    This is useful for presizing containers when building from an iterable.

    If the object supports len(), the result will be exact. Otherwise, it may
    over- or under-estimate by an arbitrary amount. The result will be an
    integer >= 0.
    """
    if not isinstance(default, int):
        msg = "'%s' object cannot be interpreted as an integer" % type(default
            ).__name__
        raise TypeError(msg)
    try:
        return len(obj)
    except TypeError:
        pass
    try:
        hint = type(obj).__length_hint__
    except AttributeError:
        return default
    try:
        val = hint(obj)
    except TypeError:
        return default
    if val is NotImplemented:
        return default
    if not isinstance(val, int):
        msg = '__length_hint__ must be integer, not %s' % type(val).__name__
        raise TypeError(msg)
    if val < 0:
        msg = '__length_hint__() should return >= 0'
        raise ValueError(msg)
    return val


def semicolon_combination(s1, s2, keep_order=False):
    """
    This will combine two strings with semicolons and drop duplication
    Example: s1='Q1;Q2', s2='Q2;Q3' -> 'Q1;Q2;Q3'
    Note that the order may change if keep_order=False
    """
    s_list = map(lambda _: _.strip(';').split(';'), (s1, s2))
    flatten_s = sum(s_list, [])
    unique_s = list(set(flatten_s))
    if keep_order:
        unique_s = sorted(unique_s, key=flatten_s.index)
    return ';'.join(unique_s)


def kmers(seq, ksize):
    """yield all k-mers of len ksize from seq.
    Returns an iterable object
    """
    for i in range(len(seq) - ksize + 1):
        yield seq[i:i + ksize]


def _get_namespace(obj: dict, parent_namespace: str=None) ->None:
    """ imputes the namespace if it doesn't already exist

    Namespaces follow the following chain of logic:
        - Use a namespace if it exists
        - If no namespace is given:
            - If referenced in a schema, inherit the same namespace as  parent
            - if not referenced in a schema and no parent, namespace = ''
              resembling the root of the input dir.

    Parameters
    ----------
        obj: dict
            serialized object resembling an avsc schema
        parent_namespace: str
            parent object namespace if applicable

    Returns
    -------
        None
    """
    if obj.get('namespace', None):
        return obj['namespace']
    elif parent_namespace:
        return parent_namespace
    else:
        return ''


def repo_name(repo_url: str) ->str:
    """Extract the name of the repo from its url.

    Args:
        repo_url: A url to a repo.
    """
    repo_name = repo_url.split('/')[-1]
    if repo_name.endswith('.git'):
        return repo_name[:-4]
    return repo_name


@classmethod
def from_file(cls, name='pyproject.toml'):
    """
        Read Configuration from pyproject.toml (or similar).
        Raises exceptions when file is not found or toml is
        not installed or the file has invalid format or does
        not contain the [tool.setuptools_scm] section.
        """
    with open(name) as strm:
        defn = __import__('toml').load(strm)
    section = defn.get('tool', {})['setuptools_scm']
    return cls(**section)


def make_comment(content: str) ->str:
    """Return a consistently formatted comment from the given `content` string.

    All comments (except for "##", "#!", "#:") should have a single space between
    the hash sign and the content.

    If `content` didn't start with a hash sign, one is provided.
    """
    content = content.rstrip()
    if not content:
        return '#'
    if content[0] == '#':
        content = content[1:]
    if content and content[0] not in ' !:#':
        content = ' ' + content
    return '#' + content


def getService(serviceClass):
    """
    Get any service from OSGi
    """
    raise Exception(
        'definition not implemented for Jython : getService(...). TODO, implement it :)'
        )


@classmethod
def factory(cls, table_map):
    """ Provide a protocol factory for a given map instance.
        """
    return lambda : cls(table_map)


def pack_bits(bits):
    """convert a bit (bool or int) tuple into a int"""
    packed = 0
    level = 0
    for bit in bits:
        if bit:
            packed += 2 ** level
        level += 1
    return packed


def mangle_attr(source, attr):
    """
  Simulate python private attritubutes mangling. Taken from:
  http://stackoverflow.com/a/7789483/1162884
  """
    if not attr.startswith('__') or attr.endswith('__') or '.' in attr:
        return attr
    if not hasattr(source, '__bases__'):
        source = source.__class__
    return '_%s%s' % (source.__name__.lstrip('_'), attr)


@classmethod
def render(cls, snippet, template_args=None):
    """Render and return a HTML string for the given snippet"""
    template = cls.get_jinja_env().get_template(cls.template_path)
    template_args = template_args or {}
    template_args.update({'snippet': snippet})
    return template.render(**template_args)


@staticmethod
def _from_db_object(context, tag, db_tag):
    """Method to help with migration to objects.

        Converts a database entity to a formal object.
        """
    if db_tag is None:
        return None
    for field in tag.fields:
        tag[field] = db_tag[field]
    tag.obj_reset_changes()
    return tag


def _line_parse(line):
    """Removes line ending characters and returns a tuple (`stripped_line`,
    `is_terminated`).
    """
    if line[-2:] in ['\r\n', b'\r\n']:
        return line[:-2], True
    elif line[-1:] in ['\r', '\n', b'\r', b'\n']:
        return line[:-1], True
    return line, False


def _cat_proc_cpuinfo_grep_query_sort_uniq(query):
    """Determine the number of unique lines in /proc/cpuinfo

    Parameters
    ----------
    string : query
        string the lines to be searched for shall begin with

    Returns
    -------
    set
        unique lines in /proc/cpuinfo that begin with query

    May throw an IOError exception in case /proc/cpuinfo does not exist.
    """
    items_seen = set()
    with open('/proc/cpuinfo') as fp:
        for line_raw in fp:
            if line_raw.startswith(query):
                line = line_raw.replace('\t', '').strip('\n')
                items_seen.add(line)
    return items_seen


def __init_subclass__(cls, **kwargs):
    """
        Catch-subclass declarations and register them.
        """
    super().__init_subclass__(**kwargs)
    cls.__registry__[cls.__name__] = cls


def delete_request_validator(restApiId=None, requestValidatorId=None):
    """
    Deletes a  RequestValidator of a given  RestApi .
    See also: AWS API Documentation

    :example: response = client.delete_request_validator(
        restApiId='string',
        requestValidatorId='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            [Required] The identifier of the RestApi from which the given RequestValidator is deleted.

    :type requestValidatorId: string
    :param requestValidatorId: [REQUIRED]
            [Required] The identifier of the RequestValidator to be deleted.

    """
    pass


def twice_nll(pars, data, pdf):
    """
    Twice the negative Log-Likelihood.

    Args:
        data (`tensor`): the data
        pdf (~pyhf.pdf.Model): The statistical model adhering to the schema model.json

    Returns:
        Twice the negative log likelihood.

    """
    return -2 * pdf.logpdf(pars, data)


def t_quoted_VARIABLE(t):
    """\\$[A-Za-z_][\\w_]*"""
    t.lexer.push_state('quotedvar')
    return t


def _test_merge_next_block(ircfg, loc_key):
    """
    Test if the irblock at @loc_key can be merge with its son
    @ircfg: IRCFG instance
    @loc_key: LocKey instance of the candidate parent irblock
    """
    if loc_key not in ircfg.blocks:
        return None
    sons = ircfg.successors(loc_key)
    if len(sons) != 1:
        return None
    son = list(sons)[0]
    if ircfg.predecessors(son) != [loc_key]:
        return None
    if son not in ircfg.blocks:
        return None
    return son


def theta_Ca_K_HMW84(T, P):
    """c-c': calcium potassium [HMW84]."""
    theta = 0.032
    valid = T == 298.15
    return theta, valid


@classmethod
def num_networks(cls):
    """ Returns the number of alive instances. """
    return cls.__num_networks


@staticmethod
def normalize_parameter(value):
    """ Normalizes parameter values. """
    if isinstance(value, str):
        value = value.replace(chr(92), chr(92) + chr(92))
        value = value.replace('"', chr(92) + '"')
    return value


def lerp(v0, v1, t):
    """
    returns a value lerped between v0 and v1, according to t
    t == 0 maps to v0, t == 1 maps to v1
    """
    return v0 + (v1 - v0) * t


@classmethod
def global_config(cls, key, *args):
    """ This reads or sets the global settings stored in class.settings. """
    if args:
        cls.settings = cls.settings.copy()
        cls.settings[key] = args[0]
    else:
        return cls.settings[key]


def stability_selection_to_threshold(stability_selection, n_boots):
    """Converts user inputted stability selection to an array of
    thresholds. These thresholds correspond to the number of bootstraps
    that a feature must appear in to guarantee placement in the selection
    profile.

    Parameters
    ----------
    stability_selection : int, float, or array-like
        If int, treated as the number of bootstraps that a feature must
        appear in to guarantee placement in selection profile. If float,
        must be between 0 and 1, and is instead the proportion of
        bootstraps.

    n_boots: int
        The number of bootstraps that will be used for selection
    """
    if isinstance(stability_selection, float):
        selection_threshold = int(stability_selection * n_boots)
    elif isinstance(stability_selection, int):
        selection_threshold = stability_selection
    else:
        raise ValueError('Stability selection must be a valid float or int.')
    if not (selection_threshold <= n_boots and selection_threshold >= 1):
        raise ValueError(
            'Stability selection thresholds must be within the correct bounds.'
            )
    return selection_threshold


@staticmethod
def get_alexa_slot_value(data, slot=None):
    """Gets values for slots from the interaction model.

        Args:
            data: The request data received from Alexa.
            slot: Name of the slot. If a name is not specified, all slots will be returned as
                a dictionary. If a name is specified but is not found, None will be returned.

        Returns:
            A ``string`` representing the value of the slot from the interaction model, or a ``hash`` of slots.

        Examples:
            >>> beer_type = ADAPI.get_alexa_intent(data, "beer_type")
            >>> all_slots = ADAPI.get_alexa_intent(data)

        """
    if 'request' in data and 'intent' in data['request'] and 'slots' in data[
        'request']['intent']:
        if slot is None:
            return data['request']['intent']['slots']
        elif slot in data['request']['intent']['slots'] and 'value' in data[
            'request']['intent']['slots'][slot]:
            return data['request']['intent']['slots'][slot]['value']
        else:
            return None
    else:
        return None


def psi_Na_Sr_Cl_MP98(T, P):
    """c-c'-a: sodium strontium chloride [MP98]."""
    psi = -0.015
    valid = T == 298.15
    return psi, valid


def seconds_to_milliseconds(seconds: float) ->int:
    """
    Converts from seconds to milliseconds.

    :param seconds: time in seconds
    :return: converted time rounded to nearest millisecond
    """
    return int(seconds * 1000)


@classmethod
def createFrom(cls, src, force_copy=False, **extra):
    """Create a LogicProgram of the current class from another LogicProgram.

        :param src: logic program to convert
        :type src: :class:`.LogicProgram`
        :param force_copy: default False, If true, always create a copy of the original logic         program.
        :type force_copy: bool
        :param extra: additional arguments passed to all constructors and action functions
        :returns: LogicProgram that is (externally) identical to given one
        :rtype: object of the class on which this method is invoked

        If the original LogicProgram already has the right class and force_copy is False, then         the original program is returned.
        """
    if not force_copy and src.__class__ == cls:
        return src
    else:
        obj = cls(**extra)
        if hasattr(src, 'extra_info'):
            obj.extra_info.update(src.extra_info)
        if hasattr(src, 'source_root'):
            obj.source_root = src.source_root
        if hasattr(src, 'source_files'):
            obj.source_files = src.source_files[:]
            obj.source_parent = src.source_parent[:]
        if hasattr(src, 'line_info'):
            obj.line_info = src.line_info[:]
        obj.add_all(src)
        return obj


@classmethod
def configure(cls, parser):
    """Configure ``parser``.

        ``parser`` is an :class:`argparse.ArgumentParser`.

        """


def unindex_doc(docid):
    """Remove an object with id 'docid' from the index."""


@classmethod
def _check_pretrained_file_names(cls, pretrained_file_name):
    """Checks if a pre-trained token embedding file name is valid.

        Parameters
        ----------
        pretrained_file_name : str
            The pre-trained token embedding file.
        """
    embedding_name = cls.__name__.lower()
    if pretrained_file_name not in cls.pretrained_file_name_sha1:
        raise KeyError(
            'Cannot find pretrained file %s for token embedding %s. Valid pretrained files for embedding %s: %s'
             % (pretrained_file_name, embedding_name, embedding_name, ', '.
            join(cls.pretrained_file_name_sha1.keys())))


def isColorBar(ax):
    """
    Guesses whether a set of Axes is home to a colorbar

    Parameters
    ----------
        ax
            Axes instance

    Returns
    -------
        True if the x xor y axis satisfies all of the
        following and thus looks like a colorbar:
            No ticks, no tick labels, no axis label

    """
    xcb = len(ax.get_xticks()) == 0 and len(ax.get_xticklabels()) == 0 and len(
        ax.get_xlabel()) == 0
    ycb = len(ax.get_yticks()) == 0 and len(ax.get_yticklabels()) == 0 and len(
        ax.get_ylabel()) == 0
    return xcb != ycb


@staticmethod
def is_number(s: str) ->bool:
    """
        Is this a string representation of an int or float?
        :param s: str
        :return: bool
        """
    try:
        int(s)
        return True
    except ValueError:
        try:
            float(s)
            return True
        except ValueError:
            return False


@staticmethod
def _dump_foreach_function_name(flow_name, idx):
    """Create foreach function name for a dump.

        :param flow_name: flow name
        :type flow_name: str
        :param idx: index of condition within the flow
        :type idx: int
        :return: condition function representation
        """
    assert idx >= 0
    return '_foreach_{}_{}'.format(flow_name, idx)


def to_type(o, new_type):
    """
    Helper funciton that receives an object or a dict and convert it to a new given type.

    :param object|dict o: The object to convert
    :param Type new_type: The type to convert to.
    """
    if new_type == type(o):
        return o
    else:
        return new_type(**o)


def number_of_workers(value: str) ->int:
    """
    The number of worker processes, must be 1 or more
    :param value: The number of processes
    :return: The validated number of processes
    """
    value = int(value)
    if value < 1:
        raise ValueError('Number of workers must be at least 1')
    return value


@classmethod
def Find(cls, setting_matcher, port_path=None, serial=None, timeout_ms=None):
    """Gets the first device that matches according to the keyword args."""
    if port_path:
        device_matcher = cls.PortPathMatcher(port_path)
        usb_info = port_path
    elif serial:
        device_matcher = cls.SerialMatcher(serial)
        usb_info = serial
    else:
        device_matcher = None
        usb_info = 'first'
    return cls.FindFirst(setting_matcher, device_matcher, usb_info=usb_info,
        timeout_ms=timeout_ms)


@classmethod
def set_timeout(cls, timeout):
    """ Set Lambda context timeout.

            :param int timouet: Lambda context timeout in seconds
        """
    cls.timeout = timeout


def run_script():
    """Run active script

    """
    pass


def find_subscript_name(subscript_dict, element):
    """
    Given a subscript dictionary, and a member of a subscript family,
    return the first key of which the member is within the value list.
    If element is already a subscript name, return that

    Parameters
    ----------
    subscript_dict: dictionary
        Follows the {'subscript name':['list','of','subscript','elements']} format

    element: string

    Returns
    -------

    Examples:
    >>> find_subscript_name({'Dim1': ['A', 'B'],
    ...                      'Dim2': ['C', 'D', 'E'],
    ...                      'Dim3': ['F', 'G', 'H', 'I']},
    ...                      'D')
    'Dim2'
    """
    if element in subscript_dict.keys():
        return element
    for name, elements in subscript_dict.items():
        if element in elements:
            return name


def Any(arg):
    """
    Any argument is accepted
    Test is for existence of argument
    Can be used to simply test existence of positional or keyword arguments
    """
    return True


def isfloatarray(cell):
    """
    Convert cell to float if possible.
    """
    try:
        cell.astype(float)
        return True
    except ValueError:
        return False


def comma_separated_arg(string):
    """ Split a comma separated string """
    return string.split(',')


def is_valid_channel_name(name):
    """
    Return True if the given name is a valid channel name.
    """
    if len(name) == 0 or len(name) > 50:
        return False
    valid = (
        'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-=_+[]{}\\|;\':"./<>?'
        )
    invalid = set(name) - set(valid)
    return not bool(invalid)


def has_cmake_cache_arg(cmake_args, arg_name, arg_value=None):
    """Return True if ``-D<arg_name>:TYPE=<arg_value>`` is found
    in ``cmake_args``. If ``arg_value`` is None, return True only if
    ``-D<arg_name>:`` is found in the list."""
    for arg in reversed(cmake_args):
        if arg.startswith('-D%s:' % arg_name):
            if arg_value is None:
                return True
            elif '=' in arg:
                return arg.split('=')[1] == arg_value
    return False


def add_basin_outlines(mydem, fig, ax, size_outline=1, zorder=2, color='k'):
    """
		Add catchment outlines to any axis given with its associated LSDDEM object ofc.
		No need to mention that catchment needs to be extracted within the LSDDEM object beforehand.
		Arguments:
			fig: the matplotlib figure
			ax: the matplotlib ax
			size_outline: size (in matplotlib units) of the outline
			zorder: the matplotlib zorder to use
			color (any color code compatible with matplotlib): the color of the outline. Default is black
		Returns:
			Nothing, It directly acts on the figure passed in argument
		Authors:
			B.G.
		Date:
			12/2018 (last update on the 23/02/2018)
	"""
    outlines = mydem.cppdem.get_catchment_perimeter()
    for key, val in outlines.items():
        print(key)
        ax.scatter(val['x'], val['y'], c=color, s=size_outline, zorder=
            zorder, lw=0)


def create_quota_limits(apps, schema_editor):
    """Create quota limits."""
    User = apps.get_model('core', 'User')
    if not User.objects.exists():
        return
    ContentType = apps.get_model('contenttypes', 'ContentType')
    UserObjectLimit = apps.get_model('limits', 'UserObjectLimit')
    to_create = []
    ct = ContentType.objects.get(app_label='admin', model='domain')
    for u in User.objects.all():
        to_create.append(UserObjectLimit(user=u, name='quota', max_value=0,
            content_type=ct))
    UserObjectLimit.objects.bulk_create(to_create)


@staticmethod
def is_assert_winner():
    """
        Determine if this state is AssertWinner
        """
    return False


def p_postgap(t):
    """postgap : POSTGAP TIMESTAMP"""
    t[0] = 'postgap', t[2]


def absspec():
    """
        Returns the absolute asset specification for this asset
        (e.g. ``mypackage:templates/foo.pt``).
        """


def is_simple_array(v):
    """
    Return whether a value is considered to be an simple array
    """
    return isinstance(v, (list, tuple))


@classmethod
def _sql_columns(cls):
    """
        Returns all columns defined for this entity. Every field
        corresponds to a single column in a table.

        The first `N` columns returned correspond to this entity's
        primary key, where `N` is the number of columns in the
        primary key.
        """
    cols = cls._sql_tables['primary'][:]
    for table, table_cols in cls._sql_tables['tables']:
        cols += table_cols
    return cols


def create_required_folders(full_filenamepath, folder_delim='/', verbose=1):
    """Accepts a full file name path include folders with '/' as default delimiter.
    Recursively checks for all sub-folders in filepath and creates those that are missing."""
    import os
    check_for_folders = full_filenamepath.split(folder_delim)
    if len(check_for_folders) == 1:
        return print('[!] No folders detected in provided full_filenamepath')
    else:
        check_path = check_for_folders[0]
        if check_path not in os.listdir():
            if verbose > 0:
                print(f'\t- creating folder "{check_path}"')
            os.mkdir(check_path)
        if len(check_for_folders) > 2:
            for folder in check_for_folders[1:-1]:
                base_folder_contents = os.listdir(check_path)
                check_path = check_path + '/' + folder
                if folder not in base_folder_contents:
                    if verbose > 0:
                        print(f'\t- creating folder "{check_path}"')
                    os.mkdir(check_path)
        if verbose > 1:
            print('Finished. All required folders have been created.')
        else:
            return


def get_reward(intervention, state):
    """Compute the reward based on the observed state and choosen intervention."""
    Q, R1, R2, S = 0.1, 20000.0, 20000.0, 1000.0
    reward = S * state.immune_response - Q * state.free_virus
    reward -= R1 * intervention.updates['epsilon_1'] ** 2
    reward -= R2 * intervention.updates['epsilon_2'] ** 2
    return reward


def gipsy_dashboard_widget(context, widget, index=None):
    """
    Template tag that renders a given dashboard module
    """
    context.update({'template': widget.template, 'widget': widget, 'index':
        index})
    return context


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


def describe_user_pool(UserPoolId=None):
    """
    Returns the configuration information and metadata of the specified user pool.
    See also: AWS API Documentation

    :example: response = client.describe_user_pool(
        UserPoolId='string'
    )

    :type UserPoolId: string
    :param UserPoolId: [REQUIRED]
            The user pool ID for the user pool you want to describe.

    :rtype: dict
    :return: {
        'UserPool': {
            'Id': 'string',
            'Name': 'string',
            'Policies': {
                'PasswordPolicy': {
                    'MinimumLength': 123,
                    'RequireUppercase': True|False,
                    'RequireLowercase': True|False,
                    'RequireNumbers': True|False,
                    'RequireSymbols': True|False
                }
            },
            'LambdaConfig': {
                'PreSignUp': 'string',
                'CustomMessage': 'string',
                'PostConfirmation': 'string',
                'PreAuthentication': 'string',
                'PostAuthentication': 'string',
                'DefineAuthChallenge': 'string',
                'CreateAuthChallenge': 'string',
                'VerifyAuthChallengeResponse': 'string'
            },
            'Status': 'Enabled'|'Disabled',
            'LastModifiedDate': datetime(2015, 1, 1),
            'CreationDate': datetime(2015, 1, 1),
            'SchemaAttributes': [
                {
                    'Name': 'string',
                    'AttributeDataType': 'String'|'Number'|'DateTime'|'Boolean',
                    'DeveloperOnlyAttribute': True|False,
                    'Mutable': True|False,
                    'Required': True|False,
                    'NumberAttributeConstraints': {
                        'MinValue': 'string',
                        'MaxValue': 'string'
                    },
                    'StringAttributeConstraints': {
                        'MinLength': 'string',
                        'MaxLength': 'string'
                    }
                },
            ],
            'AutoVerifiedAttributes': [
                'phone_number'|'email',
            ],
            'AliasAttributes': [
                'phone_number'|'email'|'preferred_username',
            ],
            'SmsVerificationMessage': 'string',
            'EmailVerificationMessage': 'string',
            'EmailVerificationSubject': 'string',
            'SmsAuthenticationMessage': 'string',
            'MfaConfiguration': 'OFF'|'ON'|'OPTIONAL',
            'DeviceConfiguration': {
                'ChallengeRequiredOnNewDevice': True|False,
                'DeviceOnlyRememberedOnUserPrompt': True|False
            },
            'EstimatedNumberOfUsers': 123,
            'EmailConfiguration': {
                'SourceArn': 'string',
                'ReplyToEmailAddress': 'string'
            },
            'SmsConfiguration': {
                'SnsCallerArn': 'string',
                'ExternalId': 'string'
            },
            'UserPoolTags': {
                'string': 'string'
            },
            'SmsConfigurationFailure': 'string',
            'EmailConfigurationFailure': 'string',
            'AdminCreateUserConfig': {
                'AllowAdminCreateUserOnly': True|False,
                'UnusedAccountValidityDays': 123,
                'InviteMessageTemplate': {
                    'SMSMessage': 'string',
                    'EmailMessage': 'string',
                    'EmailSubject': 'string'
                }
            }
        }
    }

    :returns:
    (string) --

    """
    pass


def merge(tracks):
    """Return one or more tracks joined and sorted into a single track."""
    singletrack = []
    for track in tracks:
        singletrack.extend(track)
    singletrack.sort(key=lambda e: e[4])
    return singletrack


def get_fs_basis_name(function_space, qr_var=None, on_space=None):
    """
    Returns a name for the basis function on this FunctionSpace. If
    the name of an associated quadrature object is supplied then this
    is appended to the returned name. Similarly, if the function space
    at which the basis is to be evaluated is supplied then this is
    also appended to the name.

    :param function_space: the function space for which the basis is required
    :type function_space: :py:class:`psyclone.dynamo0p3.FunctionSpace`
    :param string qr_var: the name of the Quadrature Object for which the
                          basis functions are required
    :param on_space: the function space at which the basis functions
                     will be evaluated
    :type on_space: :py:class:`psyclone.dynamo0p3.FunctionSpace`
    :return: Name for the Fortran array holding the basis function
    :rtype: string
    """
    name = '_'.join(['basis', function_space.mangled_name])
    if qr_var:
        name += '_' + qr_var
    if on_space:
        name += '_on_' + on_space.mangled_name
    return name


def _create_parameter(model, pid, value, sbo=None, constant=True, units=
    None, flux_udef=None):
    """Create parameter in SBML model."""
    parameter = model.createParameter()
    parameter.setId(pid)
    parameter.setValue(value)
    parameter.setConstant(constant)
    if sbo:
        parameter.setSBOTerm(sbo)
    if units:
        parameter.setUnits(flux_udef.getId())


def rgb_int2css(rgbint):
    """
    converts a bin int number into css colour and alpha fraction.
    E.g. -1006567680 to '#00ff00', 0.5
    """
    alpha = rgbint % 256
    alpha = float(alpha) / 255
    b = rgbint // 256 % 256
    g = rgbint // 256 // 256 % 256
    r = rgbint // 256 // 256 // 256 % 256
    return '#%02x%02x%02x' % (r, g, b), alpha


@classmethod
def get(cls, user_id, client_id):
    """Get RemoteAccount object for user.

        :param user_id: User id
        :param client_id: Client id.
        :returns: A :class:`invenio_oauthclient.models.RemoteAccount` instance.
        """
    return cls.query.filter_by(user_id=user_id, client_id=client_id).first()


def prop(func):
    """Function decorator for defining property attributes

    The decorated function is expected to return a dictionary
    containing one or more of the following pairs:
        fget - function for getting attribute value
        fset - function for setting attribute value
        fdel - function for deleting attribute
    This can be conveniently constructed by the locals() builtin
    function; see:
    http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/205183
    """
    return property(doc=func.__doc__, **func())


def match_file(patterns, file):
    """
	Matches the file to the patterns.

	*patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`)
	contains the patterns to use.

	*file* (:class:`str`) is the normalized file path to be matched
	against *patterns*.

	Returns :data:`True` if *file* matched; otherwise, :data:`False`.
	"""
    matched = False
    for pattern in patterns:
        if pattern.include is not None:
            if file in pattern.match((file,)):
                matched = pattern.include
    return matched


def save_vtk_stru_point(path, vtk_dict, verbose=True):
    """
    A routine to save a structured point vtk file given by a dictionary.

    Parameters
    ----------
    path : string
        Path for the file to be saved to.
    vtk_dict : dict
        Dictionary containing information of a structured point vtk file.
        The following keywords are allowed:

        * ``"dimensions"``: (int, int, int)
        * ``"origin"``: (float, float, float)
        * ``"spacing"``: (float, float, float)
        * ``"header"``: string
        * ``"field_data"``: dict of {"name": array}
        * ``"point_data"``: dict of {"name": array}
        * ``"cell_data"``: dict of {"name": array}

    verbose : bool, optional
        Print information of the writing process. Default: True

    Notes
    -----
    All data is assumed to be scalar.
    """
    from numpy import ascontiguousarray as ascont
    from vtk import vtkStructuredPoints, vtkStructuredPointsWriter, vtkFieldData
    from vtk.util.numpy_support import numpy_to_vtk as np2vtk
    out = vtkStructuredPoints()
    if verbose:
        print("Set 'dimensions', 'origin', 'spacing'")
    out.SetDimensions(vtk_dict['dimensions'])
    out.SetOrigin(vtk_dict['origin'])
    out.SetSpacing(vtk_dict['spacing'])
    if vtk_dict['field_data']:
        if verbose:
            print("Set 'field_data'")
        data = vtkFieldData()
        for sgl_data in vtk_dict['field_data']:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(ascont(vtk_dict['field_data'][sgl_data].reshape(-1,
                order='F')))
            arr.SetName(sgl_data)
            data.AddArray(arr)
        out.SetFieldData(data)
    if vtk_dict['point_data']:
        if verbose:
            print("Set 'point_data'")
        data = out.GetPointData()
        for sgl_data in vtk_dict['point_data']:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(ascont(vtk_dict['point_data'][sgl_data].reshape(-1,
                order='F')))
            arr.SetName(sgl_data)
            data.AddArray(arr)
    if vtk_dict['cell_data']:
        if verbose:
            print("Set 'cell_data'")
        data = out.GetCellData()
        for sgl_data in vtk_dict['cell_data']:
            if verbose:
                print("  Set '" + sgl_data + "'")
            arr = np2vtk(ascont(vtk_dict['cell_data'][sgl_data].reshape(-1,
                order='F')))
            arr.SetName(sgl_data)
            data.AddArray(arr)
    writer = vtkStructuredPointsWriter()
    writer.SetFileName(path)
    writer.SetInputData(out)
    if 'header' in vtk_dict:
        writer.SetHeader(vtk_dict['header'])
    writer.Write()


def column_from_parts(table, column):
    """Given string parts, construct the full column name.

        >>> column_from_parts('foo', 'bar')
        'foo/@/bar'

    """
    if table is None:
        return column
    return '{}/@/{}'.format(table, column)


@classmethod
def from_idtag(cls, tag):
    """Parse idtag into `class`:Month.
        """
    y = int(tag[1:5])
    m = int(tag[5:])
    return cls(year=y, month=m)


@staticmethod
def get_extension():
    """File extension used for datastructure"""
    return '.json'


def _fill_list(the_list, length, fillvalue=None):
    """Method to fill a list to a specified length.

    Parameters
    ----------
    the_list : list
        The list to fill.
    length : int
        The required length.
    fillvalue : optional
        The value to insert. If None is given the last item in the list
        is repeated.
    """
    if fillvalue is None:
        fillvalue = the_list[-1]
    while len(the_list) < length:
        the_list.append(fillvalue)


@staticmethod
def get_testcase_property(test) ->tuple:
    """
            接受一个test, 并返回一个test的class_name, method_name, method_doc属性
        :param test:
        :return: (class_name, method_name, method_doc) -> tuple
        """
    class_name = test.__class__.__qualname__
    method_name = test.__dict__['_testMethodName']
    method_doc = test.__dict__['_testMethodDoc']
    return class_name, method_name, method_doc


def PolsSickHosp(t):
    """Number of policies: Sickness Hospitalization"""
    return 0


def convert_to_correct_type(data):
    """
    Takes a string and returns in the correct type, int, float or string

    :param string data: input string to check
    :return string: the converted string

    :raise ValueError: We accept only non list or dict
    """
    if type(data) == list or type(data) == dict:
        raise ValueError('Incorrect type received %s' % type(data))
    if data:
        if type(data) == int or type(data) == float:
            return data
        try:
            return int(data)
        except ValueError:
            pass
        try:
            return float(data)
        except ValueError:
            pass
    elif data is None:
        return ''
    return data


def get_subnet(module, blade):
    """Return Subnet or None"""
    subnet = []
    subnet.append(module.params['name'])
    try:
        res = blade.subnets.list_subnets(names=subnet)
        return res.items[0]
    except Exception:
        return None


def gpencil_material_preset_add(name: str='', remove_name: bool=False,
    remove_active: bool=False):
    """Add or remove grease pencil material preset

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


def p_statement_expr(t):
    """statement : expression"""
    t[0] = t[1]


def _simpleprint_styles(_styles):
    """
    A helper function for the _Style class.  Given the dictionary of
    {stylename: styleclass}, return a string rep of the list of keys.
    Used to update the documentation.
    """
    return '[{}]'.format('|'.join(map(" '{}' ".format, sorted(_styles))))


def address_from_string(address_string):
    """Address tuple from host:port string"""
    address = address_string.split(':')
    return address[0], int(address[1])


def concatenate(items):
    """
    Concatenate a list of items in a human friendly way.

    :param items: A sequence of strings.
    :returns: A single string.

    >>> from humanfriendly.text import concatenate
    >>> concatenate(["eggs", "milk", "bread"])
    'eggs, milk and bread'
    """
    items = list(items)
    if len(items) > 1:
        return ', '.join(items[:-1]) + ' and ' + items[-1]
    elif items:
        return items[0]
    else:
        return ''


def get_short_path(content):
    """ Get content's short path.
        """


@staticmethod
def _get_scanner_ldflags(ldflags):
    """g-ir-scanner only accepts -L/-l; must ignore -F and other linker flags"""
    for f in ldflags:
        if f.startswith(('-L', '-l', '--extra-library')):
            yield f


@classmethod
def _multi_string_get_transform(cls, item, **kwargs):
    """
        transform for getting REG_MULTI_SZ to properly handle `None`
        """
    if isinstance(item, list):
        return item
    elif item is None:
        return 'Not Defined'
    else:
        return 'Invalid Value'


def _split_by_comma(s, length=50):
    """Group a comma-separated string into a list of at-most
    ``length``-length words each."""
    str_split = s.split(',')
    str_list = []
    for i in range(0, len(str_split) + length, length):
        temp_str = ','.join(str_split[i:i + length])
        if temp_str:
            str_list.append(temp_str)
    return str_list


def google_fixed_width_font(style):
    """check if the css of the current element defines a fixed width font"""
    font_family = ''
    if 'font-family' in style:
        font_family = style['font-family']
    if 'Courier New' == font_family or 'Consolas' == font_family:
        return True
    return False


def __call__(cls, value, names=None, module=None, type=None):
    """Either returns an existing member, or creates a new enum class.

        This method is used both when an enum class is given a value to match
        to an enumeration member (i.e. Color(3)) and for the functional API
        (i.e. Color = Enum('Color', names='red green blue')).

        When used for the functional API: `module`, if set, will be stored in
        the new class' __module__ attribute; `type`, if set, will be mixed in
        as the first base class.

        Note: if `module` is not set this routine will attempt to discover the
        calling module by walking the frame stack; if this is unsuccessful
        the resulting class will not be pickleable.

        """
    if names is None:
        return cls.__new__(cls, value)
    return cls._create_(value, names, module=module, type=type)


@classmethod
def get(cls, *args, **kwargs):
    """
        The class method that fetches and instantiates the resource defined by
        the provided pk value. Any other extra keyword arguments are used to
        format the :attr:`Model._path` variable to construct the request URL.

        :param pk: The primary key value for the requested resource.
        :type pk: string

        :rtype: :class:`Model` or None

        """
    auth = kwargs.pop('auth', cls._auth)
    ids = dict(zip(cls._pk, args))
    path = cls._path.format(**ids)
    data = cls._rest_call(url=path, auth=auth).data
    if not data:
        return None
    instance = cls(**data)
    instance._pk_vals = args
    instance._fetched = True
    if auth:
        instance._auth = auth
    return instance


def formatter_test_output(Formatter, obj):
    """
    Formats an object and returns output as a string.
    For test purposes only.
    """
    from tempfile import mkstemp
    from os import remove
    _, name = mkstemp()
    fmt = Formatter()
    fmt.outfile = name
    fmt.format(obj)
    fmt.flush()
    with open(name) as f:
        res = f.read()
    remove(name)
    return res


def find_spanning_tree():
    """
    Cover maximum nodes in a damaged network, using least number of edges, or such that the lowest sum of edges are achieved.
    Implementation of Kruskal's Algorithm.
    Validated.
    :return:
    """
    pass


def sec2year(seconds):
    """
    Convert seconds into decimal Julian years.

    Julian years have 365.25 days.

    Parameters:

    * seconds : float
        Time in seconds

    Returns:

    * years : float
        Time in years

    Example::

        >>> print sec2year(31557600)
        1.0

    """
    return float(seconds) / 31557600.0


def pre_univ(mas, agents, states, moves):
    """
    Return the set of states q of mas such that for all moves in moves
    specifying an action for agents in q, all successors are in states.

    mas -- a multi-agent system;
    agents -- a subset of agents of mas;
    states -- a subset of states of mas;
    moves -- a set of moves for agents.
    """
    agents_cube = mas.inputs_cube_for_agents(agents)
    others_cube = mas.bddEnc.inputsCube - agents_cube
    states = states.forsome(mas.bddEnc.inputsCube)
    moves = moves.forsome(others_cube)
    states = states & mas.bddEnc.statesMask
    nstates = ~states & mas.bddEnc.statesMask
    moves = moves & mas.bddEnc.statesInputsMask
    res = ~((mas.weak_pre(nstates) & moves).forsome(mas.bddEnc.inputsCube) &
        mas.bddEnc.statesMask) & moves.forsome(mas.bddEnc.inputsCube)
    return res


def update_package_data(distribution):
    """update build_py options to get package_data changes"""
    build_py = distribution.get_command_obj('build_py')
    build_py.finalize_options()


def obj_make_dict_of_lists(context, list_cls, obj_list, item_key):
    """Construct a dictionary of object lists, keyed by item_key.

    :param:context: Request context
    :param:list_cls: The ObjectListBase class
    :param:obj_list: The list of objects to place in the dictionary
    :param:item_key: The object attribute name to use as a dictionary key
    """
    obj_lists = {}
    for obj in obj_list:
        key = getattr(obj, item_key)
        if key not in obj_lists:
            obj_lists[key] = list_cls()
            obj_lists[key].objects = []
        obj_lists[key].objects.append(obj)
    for key in obj_lists:
        obj_lists[key]._context = context
        obj_lists[key].obj_reset_changes()
    return obj_lists


def parse_bool(s: str, default: bool=False, strict: bool=False) ->bool:
    """
    parse_bool(s: str, default: bool = False, strict: bool = False) -> bool
    Parse a boolean string value. If the string is not recognized as a valid
    True/False string value, the default is returned if strict is False;
    otherwise, a ValueError is raised.

    True values are strings (case-insensitive): t true y yes 1
    False values are strings (case-insensitive): f false n no 0
    """
    s = s.lower()
    if s in ('t', 'true', 'y', 'yes', '1'):
        return True
    if s in ('f', 'false', 'n', 'no', '0'):
        return False
    if strict:
        raise ValueError(f'Not a valid boolean string: {s!r}')
    return default


def view_zoom(factor: float=0.0, use_cursor_init: bool=True):
    """Zoom in/out the image

    :param factor: Factor, Zoom factor, values higher than 1.0 zoom in, lower values zoom out
    :type factor: float
    :param use_cursor_init: Cursor Init, Use initial cursor position
    :type use_cursor_init: bool
    """
    pass


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

        :param TeamSpaceAllocation val:
        :rtype: SpaceAllocation
        """
    return cls('team', val)


def list_principals_for_portfolio(AcceptLanguage=None, PortfolioId=None,
    PageSize=None, PageToken=None):
    """
    Lists all principal ARNs associated with the specified portfolio.
    See also: AWS API Documentation

    :example: response = client.list_principals_for_portfolio(
        AcceptLanguage='string',
        PortfolioId='string',
        PageSize=123,
        PageToken='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

    :type PortfolioId: string
    :param PortfolioId: [REQUIRED]
            The portfolio identifier.

    :type PageSize: integer
    :param PageSize: The maximum number of items to return in the results. If more results exist than fit in the specified PageSize , the value of NextPageToken in the response is non-null.

    :type PageToken: string
    :param PageToken: The page token of the first page retrieved. If null, this retrieves the first page of size PageSize .

    :rtype: dict
    :return: {
        'Principals': [
            {
                'PrincipalARN': 'string',
                'PrincipalType': 'IAM'
            },
        ],
        'NextPageToken': 'string'
    }

    """
    pass


def sort_siblings(siblings, key, reverse=False):
    """ Sorts the siblings by the given key, writing the order to the
    database.

    """
    new_order = sorted(siblings, key=key, reverse=reverse)
    for ix, sibling in enumerate(new_order):
        sibling.order = ix


@classmethod
def get_elasticsearch_schema(clz, _es_version):
    """
        Returns the elasticsearch schema for the _invenio_explicit_acls property.

        The property looks like::

            _invenio_explicit_acls [{
               "timestamp": "...when the ACL has been applied to the resource",
               "acl": <id of the acl>,
               "operation": name of the operation
                system_role: ["any_user", "authenticated_user"]
            }]

        :return:
        """
    return {'type': 'keyword'}


def format_range(low, high, width):
    """Format a range from low to high inclusively, with a certain width."""
    if low == high:
        return '%0*d' % (width, low)
    else:
        return '%0*d-%0*d' % (width, low, width, high)


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


def _setAgent(agent):
    """Set the global :attr:`agent`.

    :param agent: An :api:`twisted.web.client.Agent` for issuing requests.
    """
    global _agent
    _agent = agent


def find_nested_attr(config, attr):
    """
    Takes a config dictionary and an attribute string as input and tries to
    find the attribute in the dictionary. The attribute may use dots to
    indicate levels of depth within the dictionary.

    Example:
    find_nested_attr({'one': {'two': {'three': 3}}}, 'one.two.three')
    --> 3
    """
    obj = config.copy()
    for section in attr.split('.'):
        obj = obj[section]
    return obj


def _np_max(a, axis=None, out=None, keepdims=False):
    """
    Return the maximum of an array or maximum along an axis.

    Parameters
    ----------
    a : ndarray
        Input data.
    axis : int, optional
        Axis along which to operate.  By default, flattened input is used.
    out : ndarray, optional
        Alternative output array in which to place the result.  Must
        be of the same shape and buffer length as the expected output.
        See `doc.ufuncs` (Section "Output arguments") for more details.
    keepdims : bool, optional
        If this is set to True, the axes which are reduced are left
        in the result as dimensions with size one. With this option,
        the result will broadcast correctly against the original `arr`.

    Returns
    -------
    max : ndarray
        Maximum of `a`. If `axis` is None, the result is an array of dimension 1.
        If `axis` is given, the result is an array of dimension
        ``a.ndim - 1``.

    See Also
    --------
    min :
        The minimum value of an array along a given axis, ignoring any nan.
    maximum :
        Element-wise maximum of two arrays, ignoring any nan.
    argmax :
        Return the indices of the maximum values.

    Notes
    -----
    NaN in the orginal `numpy` is denoted as nan and will be ignored.

    Don't use `max` for element-wise comparison of 2 arrays; when
    ``a.shape[0]`` is 2, ``maximum(a[0], a[1])`` is faster than
    ``max(a, axis=0)``.

    Examples
    --------
    >>> a = np.arange(4).reshape((2,2))
    >>> a
    array([[0., 1.],
        [2., 3.]])
    >>> np.max(a)            # Maximum of the flattened array
    array(3.)
    >>> np.max(a, axis=0)    # Maxima along the first axis
    array([2., 3.])
    >>> np.max(a, axis=1)    # Maxima along the second axis
    array([1., 3.])

    >>> b = np.arange(5, dtype=np.float32)
    >>> b[2] = np.nan
    >>> np.max(b)
    array(4.)
    """
    pass


def nextIter(it, default=None):
    """
    Returns the next element of the iterator,
    returning the default value if it's empty,
    rather than throwing an error.
    """
    try:
        return next(iter(it))
    except StopIteration:
        return default


def delta_seconds(before, after):
    """Return the difference between two timing objects.

    Compute the difference in seconds between two date, time, or
    datetime objects (as a float, to microsecond resolution).
    """
    delta = after - before
    try:
        return delta.total_seconds()
    except AttributeError:
        return delta.days * 24 * 3600 + delta.seconds + float(delta.
            microseconds) / 10 ** 6


def _format_servers_list_networks(networks):
    """Return a formatted string of a server's networks

    :param networks: a Server.networks field
    :rtype: a string of formatted network addresses
    """
    output = []
    for network, addresses in networks.items():
        if not addresses:
            continue
        addresses_csv = ', '.join(addresses)
        group = '%s=%s' % (network, addresses_csv)
        output.append(group)
    return '; '.join(output)


@classmethod
def localhost(cls, application_id):
    """
        The PostgreSQL environment on the local machine.
        """
    return cls(host='localhost', name=application_id, user=application_id)


def is_ffmpeg_available():
    """Check whether `name` is on PATH and marked as executable."""
    from shutil import which
    return which('ffmpeg') is not None


def init_chebyshev_poly(result, x, pos, cur_var):
    """Initialize the first and second order before starting the recursion.

    Mathematically this amounts to
    T_1 = x
    T_2 = 2x T_1 -1.

    .. note::

        The procedure on how an init function is built can be found in the
        docstring of the init function for
        standard polynomials *init_standard_poly*.

    :param result: Contains the observations along the first dimension
        and the function values of expansion w.r.t. an observation
        along the second dimension.
    :type result: numpy.ndarray

    :param x: The data to be expanded.
    :type x: numpy.ndarray

    :param pos: The index of the element to be computed, along the second
        dimension of result.
    :type int: int

    :param cur_var: The index of the current variable to be considered in the
        recursion. This value will have to be lower than x.shape[1].
    :type cur_var: int

    :returns: The index of the next element that will be computed in the
        recursion, the order of the next element, and the index of a special
        member. The special element is the first Chebyshev polynomial
        of the current variable.
    :rtype: Tuple[int, int, int]
    """
    result[:, (pos)] = x[:, (cur_var)]
    result[:, (pos + 1)] = 2.0 * x[:, (cur_var)] * result[:, (pos)] - 1
    return pos + 2, 3, pos


def ellipsis(source, max_length):
    """Truncates a string to be at most max_length long."""
    if max_length == 0 or len(source) <= max_length:
        return source
    return source[:max(0, max_length - 3)] + '...'


def UIRobot():
    """load UIRobot driver"""
    from .uirobot.uirobot_binding import UIRobot_binding
    return UIRobot_binding


def maxsteps(value, maxval=500):
    """
    Returns the maximum number of steps and stepsize for a value that may be
    divided up to a maximum value, all being rounded value. For example, if one
    wants to get the maximum number of steps to get to a value of 100 where it
    can be maximally divided 7 times, it will return nsteps=5, stepsize=20.
    """
    valrange = [value - 3, value - 2, value - 1, value]
    nsteps = 1
    for val in valrange:
        for _, n in enumerate(reversed(list(range(1, maxval)))):
            if val % n == 0:
                if n > nsteps:
                    nsteps = int(n)
                    stepsize = int(val / nsteps)
                break
    return nsteps, stepsize


def sort_string(s):
    """A simple little toy to sort a string."""
    return ''.join(sorted(list(s))) if s else s


def intr(n):
    """Returns a correctly rounded integer"""
    return int(round(n))


def import_object(name):
    """Imports an object by name.

    ``import_object('a')`` is equivalent to ``import a``.

    ``import_object('a.b.c')`` is equivalent to ``from a.b import c``.

    >>> import os.path
    >>> import_object('os') is os
    True
    >>> import_object('os.path') is os.path
    True
    >>> import_object('os.path.dirname') is os.path.dirname
    True
    >>> import_object('os.path.object_not_exist')
    Traceback (most recent call last):
        ......
    ImportError: cannot from os.path import not_exist
    """
    if '.' not in name:
        return __import__(name, None, None)
    f, i = name.rsplit('.', 1)
    module_object = __import__(f, None, None, [i], 0)
    try:
        return getattr(module_object, i)
    except AttributeError:
        raise ImportError('cannot from {} import {}'.format(f, i))


def create_environment(client, resource_group_name, lab_name, name,
    arm_template, parameters=None, artifact_source_name=None, user_name=
    '@me', tags=None):
    """ Command to create an environment the Azure DevTest Lab """
    from azure.mgmt.devtestlabs.models import EnvironmentDeploymentProperties, DtlEnvironment
    environment_deployment_properties = EnvironmentDeploymentProperties(
        arm_template, parameters)
    dtl_environment = DtlEnvironment(tags=tags, deployment_properties=
        environment_deployment_properties)
    return client.create_or_update(resource_group_name, lab_name, user_name,
        name, dtl_environment)


def print_report(result_in):
    """Print data fields."""
    if result_in[0]:
        print('Time Codes: ' + ' '.join(result_in[0][:]))
    if result_in[1]:
        print('Titles: ' + ' '.join(result_in[1]))
    if result_in[2]:
        print('YouTube URL: ' + result_in[2])
    if result_in[3]:
        print('Tags: ' + ' '.join(result_in[3]))


def all_unique(x):
    """Return True if the collection has no duplications."""
    return len(set(x)) == len(x)


@staticmethod
def _parse_wf_header(header):
    """
        Parse a waveform header send by our custom WF_HEADER command
        The reason why we are not using WFM:Outpre is that the documentation
        was not so sure about how its response might look

        Args:
            head (str): the result of a WF_HEADER command

        Returns:
            dict
        """
    head = header.split(';')
    keys = ['bytno', 'enc', 'npoints', 'xzero', 'xincr', 'yzero', 'yoff',
        'ymult', 'xunit', 'yunit']
    assert len(head) == len(keys
        ), 'Cannot read out all the header info I want!'
    parsed = dict(zip(keys, head))
    for k in parsed:
        try:
            f = float(parsed[k])
            parsed[k] = f
        except ValueError:
            continue
        parsed['xunit'] = parsed['xunit'].replace('"', '')
        parsed['yunit'] = parsed['yunit'].replace('"', '')
        parsed['npoints'] = int(parsed['npoints'])
    return parsed


@staticmethod
def should_render_js() ->bool:
    """Whether needs js rendering
        By default, it is False.

        :return: a boolean value indicating whether or not js rendering is needed
        :rtype: bool
        """
    return False


@staticmethod
def __convert_key(expression):
    """Converts keys in YAML that reference other keys.
        """
    if type(expression) is str and len(expression) > 2 and expression[1
        ] == '!':
        expression = eval(expression[2:-1])
    return expression


def add_source(source):
    """Add a source to the list of all sources where the filter
        looks for items.
        """


def lemma1(N, p):
    """return a value for prime p  which is the sum of int(n/p^i) for all i
    where int(n/p^i) <= n"""
    v = 1
    i = 1
    tosum = []
    _N = float(N)
    while v >= 1:
        v = int(_N / float(p ** i))
        if v < 1:
            break
        tosum.append(v)
        i += 1
    return sum(tosum)


def _longkeysortreverse_direct(accessor, minv, maxv, limit):
    """minv or limit is None: do not optimize"""
    i = 0
    keys = sorted(accessor(min=minv, max=maxv), reverse=True)
    for key in keys:
        yield key
        i += 1
        if i == limit:
            return
    return


def set_line_style(color, width=3, line_style='solid'):
    """
    Defines default styling of scatter graphs with some smoothing.
    Args:
        color: line color
        width: line width
        line_style: line style (solid, dashed, ...)

    Returns: line_style dict parameters

    """
    style = dict(color=color, width=width, dash=line_style)
    return style


def default_compress_command_line():
    """
    Content for compression

    Arguments:
    None

    Return:
    Content items as list
    """
    items = [['WIDGETS MAIN', '5', int, '', 'PLAIN', '', ''], [
        'WIDGETS ADVANCED', '5', int, '', 'PLAIN', '', ''], ['WIDGETS RARE',
        '5', int, '', 'PLAIN', '', ''], ['--command_compress_path',
        'mrc2tif', str, '', 'FILE', 'Main', '',
        'Program used to execute compression.'], [
        '--command_compress_option', '-s -c zip ##INPUT## ##OUTPUT##', str,
        '', 'PLAIN', 'Main', '',
        'Command options used to compress the data. Use ##INPUT## and ##OUTPUT## as variables for the respective files.'
        ], ['--command_compress_extension', 'tiff', str, '', 'PLAIN',
        'Main', '', 'Output extension for the compressed files.'], [
        '--command_uncompress_path', 'tif2mrc', str, '', 'FILE', 'Advanced',
        '', 'Program used to execute uncompression.'], [
        '--command_uncompress_option', '##INPUT## ##OUTPUT##', str, '',
        'PLAIN', 'Advanced', '',
        'Command options used to uncompress the data. Use ##INPUT## and ##OUTPUT## as variables for the respective files.'
        ], ['--command_uncompress_extension', 'mrc', str, '', 'PLAIN',
        'Advanced', '', 'Output extension for the uncompressed files.']]
    return items


def wave_period_tf(frequency):
    """Usage: Calculate wave period (T) using frequency (f)"""
    return 1 / frequency


@classmethod
def get_pseudopotential_type_other_name(cls, calc, **kwargs):
    """Return a list of other pseudopotential type names.

        List MUST be sorted by atom types.
        """
    types = []
    raw_types = cls._get_raw_pseudopotential_type(calc, **kwargs)
    for element in sorted(raw_types):
        if raw_types[element] is None or raw_types[element
            ] in cls._pseudopotential_types:
            types.append(None)
        else:
            types.append(raw_types[element])
    return types


def ShowModalMessageBoxTextAndCaption(*args, **kwargs):
    """ Stub Anduin function."""
    print('ShowModalMessageBoxTextAndCaption', args, kwargs)


def overall_jaccard_index_calc(jaccard_list):
    """
    Calculate overall jaccard index.

    :param jaccard_list : list of jaccard index for each class
    :type jaccard_list : list
    :return: (jaccard_sum , jaccard_mean) as tuple
    """
    try:
        jaccard_sum = sum(jaccard_list)
        jaccard_mean = jaccard_sum / len(jaccard_list)
        return jaccard_sum, jaccard_mean
    except Exception:
        return 'None'


@classmethod
def remove(cls, group, function_):
    """ Remove an existing function

        If your application inherits some unwanted options from a specific
        function, you can unlink this function::

            def foo(opt, default):
                pass

            Configuration.add('create-db', function_=foo)
            Configuration.remove('create-db', function_=foo)

        :param group: group is a set of parser option
        :param function_: function to add
        """
    if group in cls.groups:
        if function_ in cls.groups[group]:
            cls.groups[group].remove(function_)


def match(expression, j, flags=0):
    """match json with lucene like query"""
    matcher = compile(expression, flags)
    return matcher.match(j)


@classmethod
def envkey(cls, key, namespace=None):
    """ Transform a mapping key, along with an optional namespace
            value and the classes’ “appname” value, into an environment-
            variable name. Like e.g., for an appname of “YoDogg” and
            a namespace value of “iheard”, the environment variable
            prefix would work out such that a variable with a key value
            of “youlike” would look like this:

                YODOGG_IHEARD_YOULIKE

                ^^^^^^ ^^^^^^ ^^^^^^^
                   |      |      |
                   |      |      +––––– mapping key (uppercased)
                   |      +–––––––––––– namespace value (uppercased)
                   +––––––––––––––––––– app name (uppercased)
        """
    return cls.prefix(namespace=namespace) + str(key).upper()


@staticmethod
def _get_msisdn_phonenumber(phonenumber):
    """
        convert the phone number to something more msisdn compliant

        from http://www.msisdn.org/:
          In GSM standard 1800, this number is built up as
            MSISDN = CC + NDC + SN
            CC = Country Code
            NDC = National Destination Code
            SN = Subscriber Number

        there are two version of the msisdn: the global definition and
        the local definition, with the difference, that the global definition
        might start with an +CC country code. in this conversion routine, the
        global prefixing is ignored
        """
    msisdn = []
    prefix = False
    if phonenumber.strip()[0] == '+':
        prefix = True
    for character in phonenumber:
        if character.isdigit():
            msisdn.append(character)
    phone = ''.join(msisdn)
    if prefix:
        return '+' + phone
    else:
        return phone


def _isZero(x, fmt):
    """Check is text is formatted 0"""
    fmt = fmt.format(0)
    return x == fmt or x == '-' + fmt


@classmethod
def _get_casing_permutations(cls, input_string):
    """ Takes a string and gives all possible permutations of casing for comparative purposes

        :param input_string: str, name of object
        :return: Generator(str), iterator of all possible permutations of casing for the input_string
        """
    if not input_string:
        yield ''
    else:
        first = input_string[:1]
        for sub_casing in cls._get_casing_permutations(input_string[1:]):
            yield first.lower() + sub_casing
            yield first.upper() + sub_casing


def build_authenticate_header(realm=''):
    """Optional WWW-Authenticate header (401 error)"""
    return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}


@staticmethod
def _dump_condition_name(flow_name, idx):
    """Create condition name for a dump.

        :param flow_name: flow name
        :type flow_name: str
        :param idx: index of condition within the flow
        :type idx: int
        :return: condition function representation
        """
    assert idx >= 0
    return '_condition_{}_{}'.format(flow_name, idx)


def cli_cosmosdb_list(client, resource_group_name=None):
    """ Lists all Azure Cosmos DB database accounts within a given resource group or subscription. """
    if resource_group_name:
        return client.list_by_resource_group(resource_group_name)
    return client.list()


@classmethod
def is_compatible(cls, download_target, osutil):
    """Determines if the target for the download is compatible with manager

        :param download_target: The target for which the upload will write
            data to.

        :param osutil: The os utility to be used for the transfer

        :returns: True if the manager can handle the type of target specified
            otherwise returns False.
        """
    raise NotImplementedError('must implement is_compatible()')


def is_interior_link(link, grid):
    """Return True if both nodes are core; False otherwise."""
    return grid.status_at_node[grid.node_at_link_tail[link]
        ] == grid.BC_NODE_IS_CORE and grid.status_at_node[grid.
        node_at_link_head[link]] == grid.BC_NODE_IS_CORE


def change_numbers(change, incertainty, steps):
    """Handles the computations for generation of data based on
    max change, incertainty of change, and the magnitude of of change.

    change | float or int | a percentile (1 = 100%) of change per period (e.g. month)
    incertainty | float or int | the degree of incertainty with rate of change
    steps | float or int | steps in which growth happens (e.g. deal size)

    """
    import numpy as np
    change_min = change - change * incertainty
    change_max = change + change * incertainty
    change_steps = (change_max - change_min) / steps
    change_outcomes = np.arange(change_min, change_max, change_steps)
    return change_outcomes


@staticmethod
def get_creation_arguments_model():
    """
        This is needed so the BaseConnection can validate the provided
        creation arguments as well as for auto documentation.
        return = {
            'required_creation_arguments': {
                'required_creation_arg_1': type,
                'required_creation_arg_2': type,
            },
            'optional_creation_arguments': {
                'optional_creation_arg_1': type,
                'optional_creation_arg_2': type,
            },
        }
        """
    return {'required_creation_arguments': {'func_to_call': type(lambda **
        kwargs: None)}, 'optional_creation_arguments': {}}


def cycles_integrator_preset_add(name: str='', remove_active: bool=False):
    """Add an Integrator Preset

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


def context_cycle_array(data_path: str='', reverse: bool=False):
    """Set a context array value (useful for cycling the active mesh edit mode)

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param reverse: Reverse, Cycle backwards
    :type reverse: bool
    """
    pass


def get_suffix_from_language(language):
    """Determine suffix from language."""
    if language == 'bash':
        suffix = 'sh'
    elif language == 'python':
        suffix = 'py'
    return suffix


def skeleton_df_to_swc(df, export_path=None):
    """
    Convert a skeleton DataFrame into a the text of an SWC file.

    Args:
        df:
            DataFrame, as returned by :py:meth:`.Client.fetch_skeleton()`

        export_path:
            Optional. Write the SWC file to disk a the given location.

    Returns:
        string
    """
    df['node_type'] = 0
    df = df[['rowId', 'node_type', 'x', 'y', 'z', 'radius', 'link']]
    swc = '# '
    swc += df.to_csv(sep=' ', header=True, index=False)
    if export_path:
        with open(export_path, 'w') as f:
            f.write(swc)
    return swc


def deleteActionProvider(provider_name):
    """ Remove an IActionProvider from the set queried by this tool.

        o Return silently if 'provider_name' is not already registered with
          the tool.

        o Deprecated: In the future, expect to use 'getUtilitiesFor' instead
          (presuming either that ordering either doesn't matter or that
          ordering is supported by the utility registry).

        o Permission:  Manage portal
        """


@classmethod
def get(klass, id):
    """
        Retrieves a object from quanta API and returns an instance

        """
    r = klass.quanta._get(klass.get_route(id))
    return klass(**r[klass.DICT_KEY])


def open_wrapper(*args, **kwargs):
    """
    This is a dumb hack used so that that these specific open calls
    can be used with fudge.patch in the tests without messing up Crypto.
    """
    return open(*args, **kwargs)


def frame_comps_from_set(frame_set):
    """
    A `set` of all component names every defined within any frame class in
    this `TransformGraph`.

    Broken out of the class so this can be called on a temporary frame set to
    validate new additions to the transform graph before actually adding them.
    """
    result = set()
    for frame_cls in frame_set:
        rep_info = frame_cls._frame_specific_representation_info
        for mappings in rep_info.values():
            for rep_map in mappings:
                result.update([rep_map.framename])
    return result


def bookmark_delete(index: int=-1):
    """Delete selected bookmark

    :param index: Index
    :type index: int
    """
    pass


def is_verified(user):
    """Check that a user has verified their email address."""
    verifications = user.email_verifications.filter(verified=True)
    return len(verifications) != 0


def retrieve(history_id, selector, countPurged=True, substitute=True):
    """Return the Version of the Resource with the given History Id

        If ``countPurged`` is ``True`` purged versions are taken into
        account also. If ``False`` purged versions are ignored and not
        taken into account in counting.

        If ``substitute`` is ``True`` a substitute is returned in case
        the requested version was purged before.

        Return a ``IVersionData`` object.
        """


def serve(ip, port, application, **kwargs):
    """
    Serve a wsgi app (any wsgi app) through with either werkzeug's runserver
    or the one that comes with python.
    """
    try:
        from werkzeug.serving import run_simple
        run_simple(ip, port, application, **kwargs)
        return
    except ImportError:
        pass
    from wsgiref.simple_server import make_server
    server = make_server(ip, port, application)
    print('Serving on %s:%s' % (ip, port))
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        pass


def psi_H_K_HCO3_HMW84(T, P):
    """c-c'-a: hydrogen potassium bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def add_sinks(sinks, sinks_to_add, ignore_index=True):
    """
    Add new sinks to the dataframe *sinks*.

    Parameters
    ----------
    sinks: DataFrame
        Dataframe of the sinks.
    sinks_to_add: DataFrame
        Dataframe of the sinks to add.
    ignore_index: bool, optional
        If True, reset the indices to integers, else use the indices provided.
        Default is True.

    Returns
    -------
    DataFrame
        Appended dataframe of the sinks.
    """
    sinks_ = sinks.append(sinks_to_add, ignore_index=ignore_index)
    return sinks_


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


@classmethod
def parse_bytes(cls, data: bytes):
    """
        Parse received Protocol IamUpstream Packet from JSON format and convert it into ProtocolUpstream object
        """
    source = data['SOURCE']
    group = data['GROUP']
    metric = data['METRIC']
    metric_preference = data['METRIC_PREFERENCE']
    sn = data['SN']
    return cls(source, group, metric_preference, metric, sn)


def detect_self_intersection(mesh):
    """ Detect all self-intersections.

    Args:
        mesh (:class:`Mesh`): The input mesh.

    Returns:
        :py:class:`numpy.ndarray`: A n by 2 array of face indices.  Each
            row contains the indices of two intersecting faces. :math:`n` is
            the number of intersecting face pairs.
    """
    try:
        import PyCGAL
    except ImportError:
        raise NotImplementedError(
            'Self intersection detection is not supported')
    detector = PyCGAL.SelfIntersection(mesh.vertices, mesh.faces)
    detector.detect_self_intersection()
    intersecting_faces = detector.get_self_intersecting_pairs()
    return intersecting_faces


def _k_to_fp(k, num_p):
    """ Given the index 'k' (i.e., the 1-d index), find the equivalent index
    in '[f,p]' (i.e., the 2-d index). """
    p = k % num_p + 1
    f = (k + num_p - p + 1) / num_p
    return f, p


def _close_scopes(hierarchy_string, target_depth=0):
    """ The string is hierarchically ordered. This function appends curly brackets to close open scopes.
    It takes the indentation of the last closed bracket as reference for the current level/depth of the hierarchy.
    :param hierarchy_string:
    :type hierarchy_string: str
    :param target_depth: The depth determines the target indentation.
    :type target_depth: int
    :return: string with closed scopes.
    :rtype: str
    """
    last_depth = hierarchy_string[hierarchy_string[:-1].rfind('\n'):].count(
        '  ')
    diff = last_depth - target_depth
    for depth in range(diff):
        hierarchy_string += '{0}}}\n'.format('  ' * (last_depth - depth - 1))
    return hierarchy_string


def to_latex(df, fn):
    """
    write a dataframe as a latex table to a file.
    """
    with open(fn, 'w') as tf:
        tf.write(
            '\\documentclass{article}\t\t\t\t\\usepackage{booktabs}\t\t\t\t\\begin{document}'
            )
        tf.write(df.to_latex())
        tf.write('\\end{document}')


def normal(x, mu, sigma):
    """ Evaluate logarithm of normal distribution (not normalized!!)

    Evaluates the logarithm of a normal distribution at x.

    Inputs
    ------
    x : float
        Values to evaluate the normal distribution at.
    mu : float
        Distribution mean.
    sigma : float
        Distribution standard deviation.

    Returns
    -------
    y : float
        Logarithm of the normal distribution at x
    """
    if sigma < 0:
        return 0.0
    return -0.5 * (x - mu) ** 2 / sigma ** 2


def makePRFfile(data, MEMtype):
    """ makes Dysnomia .prf control file from Dysnomia GUI controls

    :param dict data: GSAS-II phase data
    :param int MEMtype: 1 for neutron data with negative scattering lengths
                        0 otherwise
    :returns str: name of Dysnomia control file
    """
    generalData = data['General']
    pName = generalData['Name'].replace(' ', '_')
    DysData = data['Dysnomia']
    prfName = pName + '.prf'
    prf = open(prfName, 'w')
    prf.write('$PREFERENCES\n')
    prf.write(pName + '.mem\n')
    prf.write(pName + '.out\n')
    prf.write(pName + '.pgrid\n')
    prf.write(pName + '.fba\n')
    prf.write(pName + '_eps.raw\n')
    prf.write('%d\n' % MEMtype)
    if DysData['DenStart'] == 'uniform':
        prf.write('0\n')
    else:
        prf.write('1\n')
    if DysData['Optimize'] == 'ZSPA':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.write('1\n')
    if DysData['Lagrange'][0] == 'user':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.write('%.4f %d\n' % (DysData['Lagrange'][1], DysData['wt pwr']))
    prf.write('%.3f\n' % DysData['Lagrange'][2])
    prf.write('%.2f\n' % DysData['E_factor'])
    prf.write('1\n')
    prf.write('0\n')
    prf.write('%d\n' % DysData['Ncyc'])
    prf.write('1\n')
    prf.write('1 0 0 0 0 0 0 0\n')
    if DysData['prior'] == 'uniform':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.close()
    return prfName


def _seek_generator(f):
    """Yields seek position for each line.

    Args:
        f (file): the file object.

    """
    yield 0
    for line in f:
        yield f.tell()


def is_not_false(*args) ->bool:
    """If all item in args is True, return True."""
    for item in args:
        if not item:
            return False
    return True


@staticmethod
def _classification_function_three(att1, att2, att3):
    """ classification_function_three

        Decides the sample class label based on the sum of att1 and att2,
        and the threshold value of 9.5.

        Parameters
        ----------
        att1: float
            First numeric attribute.

        att2: float
            Second numeric attribute.

        att3: float
            Third numeric attribute.

        Returns
        -------
        int
            Returns the sample class label, either 0 or 1.

        """
    return 0 if att1 + att2 <= 9.5 else 1


@classmethod
def production(cls, *args, **kwargs):
    """
        Returns a client pointing to the production environment.
        This is the default, so you can simply use `Client()` instead.
        """
    return cls(*args, **kwargs)


def pytest_match_skip_reason(request, message):
    """The reason the test was caught by match_skip."""
    pass


def get_default_plot_params(plot_type=''):
    """Return the default parameters used for figure generation.

    Parameter
    ---------
    plot_type : string-optional
        Defines some plot-specific parameters to use by default

    Returns
    -------
    default_plot_params : dictionary
        Dictionary key-value pairs used to define plotting parameters

    """
    default_plot_params = {'autoclose': False, 'autoscale_y': True,
        'axis_bg_color': 'w', 'colormap': 'summer', 'color_order': [
        '#0072b2', '#d55e00', '#009e73', '#cc79a7', '#f0e442', '#56b4e9'],
        'figsize': (8, 6), 'fontsize': 14, 'grid': 'on', 'interactive':
        True, 'line_color': 'default', 'line_style': '-', 'line_width': 2.0,
        'marker': None, 'output_fig_path': 'test', 'output_fig_type': 'png',
        'overlay_average': False, 'overlay_average_color': '#424949',
        'reverse_x': False, 'save_fig': False, 'suppress_fig': False,
        'tick_fontsize': 12, 'title': '', 'use_colormap': False,
        'use_sci_format_xaxis': False, 'use_sci_format_yaxis': True,
        'xlabel': '', 'xlim': None, 'ylabel': '', 'ylim': None}
    if plot_type is 'spectrum':
        default_plot_params.update({'reverse_x': True})
    elif plot_type is 'fid':
        default_plot_params.update({'reverse_x': False})
    elif plot_type is 'spectra':
        default_plot_params.update({'reverse_x': True, 'line_width': 1.0,
            'overlay_average': True})
    elif plot_type is 'fids':
        default_plot_params.update({'reverse_x': False, 'line_width': 1.0,
            'overlay_average': True})
    else:
        pass
    return default_plot_params


def out_edge(graph, node):
    """Follow a single edge from node, returning a tuple:
    (node, dest_node, edge_data)
    """
    edges = graph.out_edges(node, data=True)
    assert len(edges) == 1
    return edges[0]


def _pt_specification_type_to_python_type(specification_type: str) ->str:
    """
    Convert a primitive specification type into its python equivalent.

    :param specification_type: a protocol specification data type
    :return: The equivalent data type in Python
    """
    python_type = specification_type[3:]
    return python_type


def setup_diffview(ax):
    """Builds the scattering profile visualisation pane.

    Parameters
    ----------
    ax: Axes object
        The axes position that the pane should be placed in.
    """
    ax.plot([0], color='#34a5daff')
    ax.set_yticks([])
    ax.set_ylabel('I(q)', fontsize=16)
    ax.set_xlabel('q/m$^{-1}$', fontsize=16)


def p_statement_assign(p):
    """statement : KEY EQUALS value"""
    p[0] = {p[1]: p[3]}


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 bytes2human(size, repr_format='{value:.2f}{symbol}'):
    """
        >>> bytes2human(10000)
        '9K'
        >>> bytes2human(100001221)
        '95M'
        """
    symbols = 'B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'
    prefix = {}
    for i, symbol in enumerate(symbols[1:]):
        prefix[symbol] = 1 << (i + 1) * 10
    for symbol in reversed(symbols[1:]):
        if size >= prefix[symbol]:
            value = float(size) / prefix[symbol]
            return repr_format.format(value=value, symbol=symbol)
    return repr_format.format(symbol=symbols[0], value=size)


@classmethod
def __allow__(cls, name: str) ->bool:
    """Tell if the given name is an allowed python prop name.

        Parameters
        ----------
        name : str
            The name to check.

        Returns
        -------
        bool
            ``True`` if the name is allowed, ie defined as a prop, or starting with ``aria_``
            or ``data_``.  ``False`` otherwise.

        """
    return name in cls.__types__ or name.startswith('data_'
        ) or name.startswith('aria_')


def hlstyle(fg=None, bg=None, attrs=None):
    """Output highlight style string.

		Assuming highlighted string looks like ``{style}{contents}`` this method
		should output ``{style}``. If it is called without arguments this method
		is supposed to reset style to its default.
		"""
    raise NotImplementedError


def is_somatic(var):
    """
    Return whether the variant is somatically acquired
    """
    return var.INFO.get('SOMATIC')


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

    The ".dev0" means dirty.

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


@classmethod
def _init_default(cls, dialect, connection, dbapi_connection):
    """Initialize execution context for a ColumnDefault construct."""
    self = cls.__new__(cls)
    self.root_connection = connection
    self._dbapi_connection = dbapi_connection
    self.dialect = connection.dialect
    self.execution_options = connection._execution_options
    self.cursor = self.create_cursor()
    return self


def put_data(f, data, big=True, isfloat=False):
    """
    Put data to file object with given endianness and data type.
    """
    if isfloat:
        if big:
            f.write(data.astype('>f8').tostring())
        else:
            f.write(data.astype('<f8').tostring())
    elif big:
        f.write(data.astype('>i4').tostring())
    else:
        f.write(data.astype('<i4').tostring())
    return


def get_cache_encrypt_key(key):
    """Prepare key for use with crypto libs.
    :param key: Passphrase used for encryption.
    """
    key += (16 - len(key) % 16) * '-'
    return key.encode('utf-8')


def parse():
    """Parses the body of the hand history, but first parse header if not yet parsed."""


def get_pyqt5_version():
    """Returns the PyQt5 version"""
    from PyQt5.Qt import PYQT_VERSION_STR
    return PYQT_VERSION_STR