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

        :param FileDeleteCommentDetails val:
        :rtype: EventDetails
        """
    return cls('file_delete_comment_details', val)


def rename(from_segments, to_segments):
    """
        Rename file or folder.
        """


def strftime(format):
    """Return a string representing the time.

        This is controlled by an explicit format string.
        """


def _bool(xml_boolean):
    """Converts strings "true" and "false" from XML files to Python bool"""
    assert xml_boolean in ['true', 'false'
        ], 'The boolean string must be "true" or "false"'
    return {'true': True, 'false': False}[xml_boolean]


def get_help_website():
    """Get the URL for the help website."""
    return 'https://help.cloudsmith.io/docs/cli/'


def strip_axis(ax, horizontal='right'):
    """Remove the right and the top axis"""
    if horizontal == 'right':
        anti_horizontal = 'left'
    else:
        anti_horizontal = 'right'
        ax.yaxis.set_label_position('right')
    ax.spines[horizontal].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.yaxis.set_ticks_position(anti_horizontal)
    ax.xaxis.set_ticks_position('bottom')


def _least_squares_function_wrapper(argument):
    """Takes single argument, unpacks it to args and kwargs components, and passes them to func.

    This gets around the fact that mp.Pool.map() and np.apply_along_axis() take one iterable argument. Unfortunately,
    this doesn't allow us to pass multiple args and kwargs which is a problem.  Build a single argument from all input
    args and kwargs and then call func_wrapper.

    arguments = [(args, kwargs) for j in jobs_with_different_args_and_kwargs]

    This wrapper supports the least_squares_objective_function and will return one evaluated element of the objective
    function.  It also checks if either the weight or bootstrapping multipliers is zero before evaluating the func to
    improve efficiency.

    objective_function_element_i = (b_i*w_i)*(func(xi, *theta, *args_i, **kwargs_i) - fx)**2
    """
    func, theta, x, fx, w, b, args, kwargs = argument
    return w * b * (func(x, *theta, *args, **kwargs) - fx
        ) ** 2.0 if w > 0.0 and b > 0.0 else 0.0


@staticmethod
def _classification_function_seven(salary, commission, age, elevel, car,
    zipcode, hvalue, hyears, loan):
    """ classification_function_seven

        Parameters
        ----------
        salary: float
            Numeric feature: Salary.

        commission: float
            Numeric feature: Commission.

        age: int
            Numeric feature: Age.

        elevel: int
            Categorical feature: Education level.

        car: int
            Categorical feature: Car maker.

        zipcode; int
            Categorical feature: Zipcode.

        hvalue: flaot
            Numeric feature: Value of the house.

        hyears: float
            Numeric feature: Years house owned.

        loan: float
            Numeric feature: Total amount of loan.

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

        """
    disposable = 2 * (salary + commission) / 3 - 5000 * elevel - 20000
    return 0 if disposable > 1 else 1


def indexset(n):
    """The orders of the non-zero bits in the binary expansion of n."""
    i = 0
    result = []
    while True:
        mask = 1 << i
        if n & mask:
            result.append(i)
        if n < mask:
            break
        i += 1
    return result


def setprocname(name):
    """Sets current process name.

    :param str|unicode name:

    :rtype: bool
    """
    return False


def _to_float(field):
    """ Transform to float """
    return float(field)


def raise_admixture_incompatability_error(parser, other_option):
    """
    Because of the state dependency within ms, it is messy for us to
    support options that affect all populations in conjunction with
    population splits. For now, raise an error.
    """
    parser.error(
        'Cannot currently use the -es and {} options together. Please open an issue on GitHub if this functionality is important to you.'
        .format(other_option))


def multi_mp_sgd_mom_update(*data, **kwargs):
    """Momentum update function for multi-precision Stochastic Gradient Descent (SGD) optimizer.

    Momentum update has better convergence rates on neural networks. Mathematically it looks
    like below:

    .. math::

      v_1 = \\alpha * \\nabla J(W_0)\\\\
      v_t = \\gamma v_{t-1} - \\alpha * \\nabla J(W_{t-1})\\\\
      W_t = W_{t-1} + v_t

    It updates the weights using::

      v = momentum * v - learning_rate * gradient
      weight += v

    Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.

    Defined in src/operator/optimizer_op.cc:L472

    Parameters
    ----------
    data : Symbol[]
        Weights
    lrs : tuple of <float>, required
        Learning rates.
    wds : tuple of <float>, required
        Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
    momentum : float, optional, default=0
        The decay rate of momentum estimates at each epoch.
    rescale_grad : float, optional, default=1
        Rescale gradient to grad = rescale_grad*grad.
    clip_gradient : float, optional, default=-1
        Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
    num_weights : int, optional, default='1'
        Number of updated weights.

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

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


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

        :param EmmAddExceptionType val:
        :rtype: EventType
        """
    return cls('emm_add_exception', val)


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables. The same goes for tuples, since they are immutable and therefore
    valid entries.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str
        ) and not isinstance(obj, tuple)


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


def _contrib_sign_ste(data=None, name=None, attr=None, out=None, **kwargs):
    """Straight-through-estimator of `sign()`.

    In forward pass, returns element-wise sign of the input (same as `sign()`).

    In backward pass, returns gradients of ``1`` everywhere (instead of ``0`` everywhere as in ``sign()``):
    :math:`\\frac{d}{dx}{sign\\_ste(x)} = 1` vs. :math:`\\frac{d}{dx}{sign(x)} = 0`.
    This is useful for quantized training.

    Reference: Estimating or Propagating Gradients Through Stochastic Neurons for Conditional Computation.

    Example::
      x = sign_ste([-2, 0, 3])
      x.backward()
      x = [-1.,  0., 1.]
      x.grad() = [1.,  1., 1.]

    The storage type of ``sign_ste`` output depends upon the input storage type:
      - round_ste(default) = default
      - round_ste(row_sparse) = row_sparse
      - round_ste(csr) = csr

    Defined in src/operator/contrib/stes_op.cc:L80

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

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

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


def FPE(N, rho, k=None):
    """Final prediction error criterion

    .. math:: FPE(k) = \\frac{N + k + 1}{N - k - 1} \\rho_k

    :validation: double checked versus octave.

    """
    fpe = rho * (N + k + 1.0) / (N - k - 1)
    return fpe


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

        :param MemberSpaceLimitsAddExceptionDetails val:
        :rtype: EventDetails
        """
    return cls('member_space_limits_add_exception_details', val)


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

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

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


@classmethod
def from_dataframes(cls, data_df, sample_meta_df, gene_meta_df):
    """Dataset constructor method from multiple dataframes

        Parameters
        ----------
        data_df : dataframe, shape (n_samples, n_genes)
                Contains the expression data from experiment. Must have
                shared row index with ``sample_meta_df``.

        sample_meta_df : ``dataframe``, shape (n_samples, n_meta_features)
                Contains the metadata for each of the samples in experiment.

        gene_meta_df : dataframe, shape (n_genes, n_gene_features)
                Contains the metadata for each of the genes in experiment.
        """
    data = data_df.join(sample_meta_df)
    return cls(data, gene_meta_df, len(gene_meta_df))


def get_mvarg(size_pos, position='full'):
    """Take xrandrs size&pos and prepare it for wmctrl (MVARG) format

    MVARG: <G>,<X>,<Y>,<W>,<H>
      * <G> - gravity, 0 is default
    """
    allowed = ['left', 'right', 'top', 'bottom', 'full']
    if position not in allowed:
        raise ValueError(f'Position has to be one of {allowed}')
    size, x, y = size_pos.split('+')
    w, h = size.split('x')
    if position == 'left':
        w = int(w) // 2
    if position == 'right':
        w = int(w) // 2
        x = int(x) + w
    return f'0,{x},{y},{w},{h}'


def _right_squeeze(arr, stop_dim=0):
    """
    Remove trailing singleton dimensions

    Parameters
    ----------
    arr : ndarray
        Input array
    stop_dim : int
        Dimension where checking should stop so that shape[i] is not checked
        for i < stop_dim

    Returns
    -------
    squeezed : ndarray
        Array with all trailing singleton dimensions (0 or 1) removed.
        Singleton dimensions for dimension < stop_dim are retained.
    """
    last = arr.ndim
    for s in reversed(arr.shape):
        if s > 1:
            break
        last -= 1
    last = max(last, stop_dim)
    return arr.reshape(arr.shape[:last])


@classmethod
def search(cls, five9, filters):
    """Search for a record on the remote and return the results.

        Args:
            five9 (five9.Five9): The authenticated Five9 remote.
            filters (dict): A dictionary of search parameters, keyed by the
                name of the field to search. This should conform to the
                schema defined in :func:`five9.Five9.create_criteria`.

        Returns:
            list[BaseModel]: A list of records representing the result.
        """
    return cls._name_search(five9.configuration.getDispositions, filters)


def dotted_starts_with(string, prefix):
    """Like string.startswith(prefix), but in the dotted sense.

    That is, abc is a prefix of abc.de but not abcde.ghi.
    """
    return prefix == string or string.startswith('%s.' % prefix)


def attr(obj, *attrs, **kwargs):
    """
        Follow chained attributes and get the value of the last attributes.
        If an attribute error is raised, returns the default value.

        res = attr(data, 'test', 'o', 'bla', default="yeah")

        is the equivalent of

        try:
            res = getattr(getattr(getattr(data, 'test'), 'o'), 'bla')
        except AttributeError:
            res = "yeah"

    """
    try:
        value = getattr(obj, attrs[0])
        for attr in attrs[1:]:
            value = getattr(value, attr)
    except (IndexError, AttributeError):
        return kwargs.get('default', None)
    return value


def empty():
    """ An empty iterator. Other methods include:
		iter(())
		yield from ()
	"""
    return
    yield


def _normalizeName(name: str) ->str:
    """
    Originally a name would be of the form project:name,
    later on we enabled the / to act as path separator
    """
    if '/' in name:
        return name.replace('/', ':')
    return name


def read_token_file(filename):
    """
    Read a token file and return the oauth token and oauth token secret.
    """
    f = open(filename)
    return f.readline().strip(), f.readline().strip()


@staticmethod
def run_func_without_hooks(sess, func):
    """ Executes a function that depends on a raw TensorFlow session without hooks
            :param sess: The wrapped TensorFlow session.
            :param func: A function to execute (args: session [the raw TF session])
        """
    if hasattr(sess, 'run_step_fn'):
        return sess.run_step_fn(lambda step_context: func(step_context.session)
            )
    return func(sess)


def dropTable(ifExists=False, dropJoinTables=True, cascade=False,
    connection=None):
    """
        Drops this table from the database.  If ``ifExists`` is true,
        then it is not an error if the table doesn't exist.

        Join tables (mapping tables for many-to-many joins) are
        dropped if this class comes alphabetically before the other
        join class, and if ``dropJoinTables`` is true.

        ``cascade`` is passed to the connection, and if true tries to
        drop tables that depend on this table.
        """


@staticmethod
def _simplifyLinExpr(lexpr):
    """ simplify the given linear expression by combining coefficients

        This function combines all entries with the same name by adding up the
        corresponding coefficients, preserving the order of the names (first
        occurrence). Terms with coefficient zero are removed.

        Keyword arguments:

        lexpr -- list of (coefficient, name) pairs

        Returns: list of (coefficient, name) pairs with unique name
        """
    firstIndex = {}
    nUniqueNames = 0
    result = []
    for coef, name in lexpr:
        if name not in firstIndex:
            result.append((coef, name))
            firstIndex[name] = nUniqueNames
            nUniqueNames += 1
        else:
            j = firstIndex[name]
            result[j] = result[j][0] + coef, name
    for i in range(len(result) - 1, -1, -1):
        if result[i][0] == 0.0:
            del result[i]
    return result


@classmethod
def from_storage(cls, storage, indexname='THES'):
    """Creates a Thesaurus object from the given storage object,
        which should contain an index created by Thesaurus.to_storage().

        >>> from whoosh.filedb.filestore import FileStorage
        >>> fs = FileStorage("index")
        >>> t = Thesaurus.from_storage(fs)
        >>> t.synonyms("hail")
        ['acclaim', 'come', 'herald']

        :param storage: A :class:`whoosh.store.Storage` object from
            which to load the index.
        :param indexname: A name for the index. This allows you to
            store multiple indexes in the same storage object.
        """
    thes = cls()
    index = storage.open_index(indexname=indexname)
    thes.searcher = index.searcher()
    return thes


def wrapValueInHTML(value):
    """Wrap the data in a valid html construct to remove the missing title error
    """
    return (
        """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
%s
</body>
</html>
"""
         % value)


def cleanString(string, nows=False):
    """*nows* is no white space."""
    if nows:
        return ''.join(string.strip().split())
    else:
        return ' '.join(string.strip().split())


@classmethod
def stop(cls, resources, background=False):
    """Stop a virtual machine."""
    if not isinstance(resources, (list, tuple)):
        resources = [resources]
    opers = []
    for item in resources:
        oper = cls.call('hosting.vm.stop', cls.usable_id(item))
        if isinstance(oper, list):
            opers.extend(oper)
        else:
            opers.append(oper)
    if background:
        return opers
    instance_info = "'%s'" % ', '.join(resources)
    cls.echo('Stopping your Virtual Machine(s) %s.' % instance_info)
    cls.display_progress(opers)


def aliasFont(fontAlias, fontKey):
    """Set a fontAlias as another alias name of fontKey"""
    g = globals()
    g[fontAlias] = g[fontKey]


def cast_int(*, value: str, params: str, shared: dict) ->int:
    """Casts value to integer.

    :param value: Current value.
    :param params: Additional value-related parameters.
    :param shared: Global shared parameters.

    """
    return int(value)


def glCompileShader(shader: int):
    """Compiles a shader object.

    :param shader: Specifies the shader object to be compiled.
    :type shader: int
    """
    pass


def d2BinaryRochedx2(r, D, q, F):
    """
    Computes second derivative of the potential with respect to x.

    @param r:      relative radius vector (3 components)
    @param D:      instantaneous separation
    @param q:      mass ratio
    @param F:      synchronicity parameter
    """
    return (2 * r[0] * r[0] - r[1] * r[1] - r[2] * r[2]) / (r[0] * r[0] + r
        [1] * r[1] + r[2] * r[2]) ** 2.5 + q * (2 * (r[0] - D) * (r[0] - D) -
        r[1] * r[1] - r[2] * r[2]) / ((r[0] - D) * (r[0] - D) + r[1] * r[1] +
        r[2] * r[2]) ** 2.5 + F * F * (1 + q)


def chat(occupantJID, body):
    """
        Send a private chat message to a user in a MUC room.

        See: http://xmpp.org/extensions/xep-0045.html#privatemessage

        @param occupantJID: The Room JID of the other user.
        @type occupantJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
        """


def remove_comments(description):
    """Remove reStructuredText comment lines."""
    description = description.splitlines()
    if description:
        if description[0].startswith('..'):
            description = description[1:]
    while description and description[0].strip() == '':
        description.pop(0)
    return '\n'.join(description)


@classmethod
def icon(cls):
    """
        Return full path to svg icon.
        """
    return None


def visualise(dmrs, format):
    """
    Returns the bytestring of the chosen visualisation representation.
    Supported formats: dot
    """
    if format == 'dot':
        dot_strs = []
        dot_strs.append('digraph g {\n')
        if dmrs.top is not None:
            dot_strs.append('NodeTop [label="top",style=bold];\n')
        dot_strs.append('node[shape=box];\n')
        for nodeid in dmrs:
            node = dmrs[nodeid]
            dot_strs.append(
                'Node{} [label=<{}{}
{}>];\n'
                .format(str(nodeid).replace('-', 'M'), node.pred, '("{}")'.
                format(node.carg) if node.carg else '', node.sortinfo))
        dot_strs.append('edge[fontsize=10];\n')
        if dmrs.top is not None:
            dot_strs.append('NodeTop -> Node{} [style=dotted];\n'.format(
                str(dmrs.top.nodeid).replace('-', 'M')))
        for link in dmrs.links:
            dot_strs.append('Node{} -> Node{} [label="{}"];\n'.format(str(
                link.start).replace('-', 'M'), str(link.end).replace('-',
                'M'), link.labelstring))
        dot_strs.append('}\n')
        dot_str = ''.join(dot_strs)
        return dot_str.encode()
    else:
        raise NotImplementedError


def abs(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise absolute value of the input.

    Example::

       abs([-2, 0, 3]) = [2, 0, 3]

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

       - abs(default) = default
       - abs(row_sparse) = row_sparse
       - abs(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L721

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

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

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


def Children(it):
    """ Return a generator to the children of all the nodes in the passed
  iterable."""
    for n in it:
        for c in n.GetFlattenedChildren():
            if c is not None:
                yield c


def tick_length_pixels(pad, xaxis, yaxis, xlength, ylength=None):
    """
    Set the axes tick lengths in pixels
    """
    if ylength is None:
        ylength = xlength
    xaxis.SetTickLength(xlength / float(pad.height_pixels))
    yaxis.SetTickLength(ylength / float(pad.width_pixels))


def _parse_two_level_dict(dat):
    """Get hierarchical list information from queued message
    Args:
        dat (bytes): received message data
    Returns:
        dict: dictionary of information list
    """
    results = dict()
    count = int.from_bytes(dat[:2], 'big')
    ptr = 2
    for i in range(count):
        first_id = dat[ptr:ptr + 32]
        ptr += 32
        results[first_id] = list()
        count2 = int.from_bytes(dat[ptr:ptr + 2], 'big')
        ptr += 2
        for j in range(count2):
            second_id = dat[ptr:ptr + 32]
            ptr += 32
            results[first_id].append(second_id)
    return results


def normalise_link_name(link: str) ->str:
    """
    Convert i.e. "filter_factory" to "filters"

    :param link: The original link name
    :return: The normalised link name
    """
    if link.endswith('_factory'):
        link = link[:-8] + 's'
    return link


def get_size(bytes_, suffix='B'):
    """
    Scale bytes to its proper format
    e.g:
        1253656 => '1.20MB'
        1253656678 => '1.17GB'
    """
    factor = 1024
    value = ''
    for unit in ['', 'K', 'M', 'G', 'T', 'P']:
        if bytes_ < factor:
            value = f'{bytes_:.2f}{unit}{suffix}'
            break
        bytes_ /= factor
    return value


@classmethod
def change_repr(cls, representation=None):
    """Toggles globally between cycle notation or one-line notation. Note
        that internal representation is still one-line."""
    L = ['oneline', 'cycle', 'both']
    if representation in L:
        cls._REPR = representation
    else:
        k = int(input('1 for oneline, 2 for cycle, 3 for both\n '))
        k -= 1
        cls._REPR = L[k]


@classmethod
def exec_method_event(cls, request_method, ws):
    """
        call by MessageManager
        """
    f = cls.method_to_func[request_method]
    f(cls, ws)


def hello(name=None):
    """Return a friendly greeting string."""
    if name is None:
        name = 'world'
    return 'Hello, {0}!'.format(name)


def is_conda_supported_on_server(connect_details):
    """
    Returns whether or not conda is supported on a Connect server.

    :param connect_details: details about a Connect server as returned by gather_server_details()
    :return: boolean True if supported, False otherwise
    :error: Conda is not supported on the target server.  Try deploying without requesting Conda.
    """
    return connect_details.get('conda', {}).get('supported', False)


def _inactivate_record(record):
    """
    Disables database records by setting the 'active' attribute to False
    The queries in this module filter out inactive records as part of their criteria
    This effectively allows us to soft-delete records so they are not lost forever
    """
    record.active = False
    record.save()


def add_ext_map(sender, instance, created, **kwargs):
    """
    Create an ExtMap and link it to the created map.
    """
    if created:
        from .models import ExtMap
        ExtMap.objects.create(map=instance)


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Alignak realm'
    return 'realm'


@staticmethod
def _generate_checksum(data):
    """ Sum of data & 0b01111111 """
    total = sum(bytearray(data))
    checksum = total & 127
    if __debug__:
        print('Private: Checksum generated: %s' % checksum)
    return checksum


def get_layer(model, idx):
    """ Returns the layer of the corresponding index of the model."""
    return list(model.children())[idx]


def invert_convert_cbaois_to_kpsois_(cbaois, kpsois):
    """Invert the output of :func:`convert_to_cbaois_to_kpsois` in-place.

    This function writes in-place into `cbaois`.

    Added in 0.4.0.

    Parameters
    ----------
    cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or imgaug.augmentables.bbs.BoundingBoxesOnImage or imgaug.augmentables.bbs.PolygonsOnImage or imgaug.augmentables.bbs.LineStringsOnImage
        Original coordinate-based augmentables before they were converted,
        i.e. the same inputs as provided to :func:`convert_to_kpsois`.

    kpsois : list of imgaug.augmentables.kps.KeypointsOnImages or imgaug.augmentables.kps.KeypointsOnImages
        Keypoints to convert back to the types of `cbaois`, i.e. the outputs
        of :func:`convert_cbaois_to_kpsois`.

    Returns
    -------
    list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or imgaug.augmentables.bbs.BoundingBoxesOnImage or imgaug.augmentables.bbs.PolygonsOnImage or imgaug.augmentables.bbs.LineStringsOnImage
        Parameter `cbaois`, with updated coordinates and shapes derived from
        `kpsois`. `cbaois` is modified in-place.

    """
    if not isinstance(cbaois, list):
        assert not isinstance(kpsois, list), (
            'Expected non-list for `kpsois` when `cbaois` is non-list. Got type %s.'
             % type(kpsois.__name__),)
        return cbaois.invert_to_keypoints_on_image_(kpsois)
    result = []
    for cbaoi, kpsoi in zip(cbaois, kpsois):
        cbaoi_recovered = cbaoi.invert_to_keypoints_on_image_(kpsoi)
        result.append(cbaoi_recovered)
    return result


def navmesh_make():
    """Create navigation mesh for selected objects

    """
    pass


def lagrange_basis(indexes, o, x=0):
    """ generates all lagrange basis polynomials """
    l = []
    for i in indexes:
        numerator, denominator = 1, 1
        for j in indexes:
            if j != i:
                numerator = numerator * (x - j) % o
                denominator = denominator * (i - j) % o
        l.append(numerator * denominator.mod_inverse(o) % o)
    return l


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


@staticmethod
def _format_path(path):
    """formats the path to internal format, which is Linux forward slashes
        for path separation
        """
    from stalker import __string_types__
    if not isinstance(path, __string_types__):
        path = path.encode('utf-8')
    return path.replace('\\', '/')


@classmethod
def fromnsec(cls, nsec):
    """Create an instance from an integer in nano-seconds"""
    return cls(nsec // 1000000000.0, nsec % 1000000000.0)


@classmethod
def get_pgpm_db_version(cls, cur, schema_name='_pgpm'):
    """
        returns current version of pgpm schema
        :return: tuple of major, minor and patch components of version
        """
    cls.set_search_path(cur, schema_name)
    cur.execute("SELECT _find_schema('{0}', '{1}')".format(schema_name, 'x'))
    pgpm_v_ext = tuple(cur.fetchone()[0][1:-1].split(','))
    return pgpm_v_ext[2], pgpm_v_ext[3], pgpm_v_ext[4]


def _firstfirst(iterable):
    """
    Given a nested iterable, i.e., list of lists, return the first element
    of the first non-empty element.
    """
    for i in iterable:
        for j in i:
            return j


def put_object_acl(ACL=None, AccessControlPolicy=None, Bucket=None,
    GrantFullControl=None, GrantRead=None, GrantReadACP=None, GrantWrite=
    None, GrantWriteACP=None, Key=None, RequestPayer=None, VersionId=None):
    """
    uses the acl subresource to set the access control list (ACL) permissions for an object that already exists in a bucket
    See also: AWS API Documentation

    :example: response = client.put_object_acl(
        ACL='private'|'public-read'|'public-read-write'|'authenticated-read'|'aws-exec-read'|'bucket-owner-read'|'bucket-owner-full-control',
        AccessControlPolicy={
            'Grants': [
                {
                    'Grantee': {
                        'DisplayName': 'string',
                        'EmailAddress': 'string',
                        'ID': 'string',
                        'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
                        'URI': 'string'
                    },
                    'Permission': 'FULL_CONTROL'|'WRITE'|'WRITE_ACP'|'READ'|'READ_ACP'
                },
            ],
            'Owner': {
                'DisplayName': 'string',
                'ID': 'string'
            }
        },
        Bucket='string',
        GrantFullControl='string',
        GrantRead='string',
        GrantReadACP='string',
        GrantWrite='string',
        GrantWriteACP='string',
        Key='string',
        RequestPayer='requester',
        VersionId='string'
    )

    :type ACL: string
    :param ACL: The canned ACL to apply to the object.

    :type AccessControlPolicy: dict
    :param AccessControlPolicy:
            Grants (list) -- A list of grants.
            (dict) --
            Grantee (dict) --
            DisplayName (string) -- Screen name of the grantee.
            EmailAddress (string) -- Email address of the grantee.
            ID (string) -- The canonical user ID of the grantee.
            Type (string) -- [REQUIRED] Type of grantee
            URI (string) -- URI of the grantee group.
            Permission (string) -- Specifies the permission given to the grantee.

            Owner (dict) --
            DisplayName (string) --
            ID (string) --

    :type Bucket: string
    :param Bucket: [REQUIRED]

    :type GrantFullControl: string
    :param GrantFullControl: Allows grantee the read, write, read ACP, and write ACP permissions on the bucket.

    :type GrantRead: string
    :param GrantRead: Allows grantee to list the objects in the bucket.

    :type GrantReadACP: string
    :param GrantReadACP: Allows grantee to read the bucket ACL.

    :type GrantWrite: string
    :param GrantWrite: Allows grantee to create, overwrite, and delete any object in the bucket.

    :type GrantWriteACP: string
    :param GrantWriteACP: Allows grantee to write the ACL for the applicable bucket.

    :type Key: string
    :param Key: [REQUIRED]

    :type RequestPayer: string
    :param RequestPayer: Confirms that the requester knows that she or he will be charged for the request. Bucket owners need not specify this parameter in their requests. Documentation on downloading objects from requester pays buckets can be found at http://docs.aws.amazon.com/AmazonS3/latest/dev/ObjectsinRequesterPaysBuckets.html

    :type VersionId: string
    :param VersionId: VersionId used to reference a specific version of the object.

    :rtype: dict
    :return: {
        'RequestCharged': 'requester'
    }

    :returns:
    (dict) --
    RequestCharged (string) -- If present, indicates that the requester was successfully charged for the request.

    """
    pass


def sizeof_fmt(num):
    """
    Returns human-friendly file sizes.
    """
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if num < 1024.0:
            return '%3.1f%s' % (num, x)
        num /= 1024.0
    return '%3.1f%s' % (num, 'TB')


def print_script(script):
    """Prints the details of the given script to the console"""
    print('Name: {}'.format(script['name']))
    print('Description: {}'.format(script['description']))
    print('Filename: {}'.format(script['filename']))
    if 'http_method' in script:
        print('HTTP Method: {}'.format(script['http_method']))
    if 'output' in script:
        print('Output Type: {}'.format(script['output']))
    if 'params' in script and len(script['params']) > 0:
        print('Parameters:')
        for param in sorted(script['params']):
            print('  {}: {}'.format(param['name'], param['description']))
    if 'filtered_params' in script and len(script['filtered_params']) > 0:
        print('Filtered parameters:')
        for param in script['filtered_params']:
            print('  {}'.format(param))
    if 'tags' in script and len(script['tags']) > 0:
        print('Tags:')
        for tag in sorted(script['tags']):
            print('  {}'.format(tag))
    print('Lock: {}'.format(script['lock']))


def build_content_type(format, encoding='utf-8'):
    """
    Appends character encoding to the provided format if not already present.
    """
    if 'charset' in format:
        return format
    if format in ('application/json', 'text/javascript'):
        return format
    return '%s; charset=%s' % (format, encoding)


def undofiles():
    """Returns a list of (vfs, path) for files to undo transactions."""


def dict_set_path(dic, path, value):
    """Set the value of a dict using path syntax.
    """
    cur = dic
    path = path.split('.')
    for key in path[:-1]:
        cur = cur.setdefault(key, {})
    cur[path[-1]] = value


def calcRectCenter(l, t, r, b):
    """ returns rect center point -> x,y
        calcRectCenter(l,t,r,b)
    """
    return l + (r - l) * 0.5, t + (b - t) * 0.5


@classmethod
def _get_param_names(cls):
    """ Overwriting BaseEstimator_get_param_names()
        Needed in order to perform clone of the strategy in the orchestrator
        TODO figure out a way to either call the BaseEstimator method here or automate the inpsection of the signature of __init__ in this class.
        """
    return ['build_fn', 'check_input', 'estimator', 'name', 'param_grid']


def pdf_derivative_under_affine_map(pdf_deriv, loc, scale, y):
    """
    Let y=g(x)=x*scale+loc and x = g^{-1}(y) = v(y) = (y-loc)/scale, scale>0
    p_Y(y)=p_X(v(y))*|dv/dy(y)|=p_X((y-loc)/scale))/scale
    dp_Y(y)/dy = dv/dy(y)*dp_X/dx(v(y))/scale = dp_X/dx(v(y))/scale**2
    """
    return pdf_deriv((y - loc) / scale) / scale ** 2


def getMembers():
    """Returns a list of IMember in the hierarchy."""


def _c13_num(pep_query, isolation_mz):
    """
    Counts the number of C13 atoms in a query, based on the mass-error between
    the expected and isolated m/z values.

    Parameters
    ----------
    pep_query : :class:`PeptideQuery<pycamv.pep_query.PeptideQuery>`
    isolation_mz : float

    Returns
    -------
    int
    """
    return int(round(pep_query.pep_exp_z * abs(pep_query.pep_exp_mz -
        isolation_mz)))


def _setup_base_class(cls, only_one_registered=False):
    """
        Do any setup required specifically if this class is being setup as a hook definition
        abstract base class.
        """
    cls._registered_hooks = {}
    cls._only_one_registered = only_one_registered


@classmethod
def stopScreencast(cls):
    """Stops sending each frame in the `screencastFrame`.
        """
    return cls.build_send_payload('stopScreencast', {}), None


def update_time_range(form_data):
    """Move since and until to time_range."""
    if 'since' in form_data or 'until' in form_data:
        form_data['time_range'] = '{} : {}'.format(form_data.pop('since',
            '') or '', form_data.pop('until', '') or '')


def ref_type(ref):
    """Return branch, tag, sha, or unknown ref type

    :param str ref: Full pathspec
    :return: 'branch', 'tag', 'sha', or 'unknown'
    :rtype: str
    """
    git_branch = 'refs/heads/'
    git_tag = 'refs/tags/'
    if ref.startswith(git_branch):
        return 'branch'
    elif ref.startswith(git_tag):
        return 'tag'
    elif len(ref) == 40:
        return 'sha'
    return 'unknown'


def _get_size_for_dev(device):
    """
    @param device: the device
    @type device: pyudev.Device
    @return: the size in logical blocks, 0 if none found
    @rtype: int
    """
    attributes = device.attributes
    try:
        sect_size = attributes.asint('size')
    except (KeyError, UnicodeDecodeError, ValueError):
        return 0
    if device['DEVTYPE'] == 'partition':
        attributes = device.parent.attributes
    try:
        logical_block_size = attributes.asint('queue/logical_block_size')
    except (KeyError, UnicodeDecodeError, ValueError):
        return 0
    return sect_size * 512 // logical_block_size


def get_app():
    """
        Return the IAppContainer this content is contained in, or None.
        """


@staticmethod
def on_parsing(options, args):
    """Plugin hook to manipulate the command line parsing results.
        A tuple of values can be returned, which will replace (options, args).
        """


def p_option_querystring(p):
    """ OPTION :  QUERYSTRINGVALUE """
    p[0] = p[1]


@classmethod
def equalsInterface(cls, it, ic):
    """Check is interface included to standard."""
    if int(ic) == 0 or it.interfaces == '*':
        return True
    return str(int(ic)) in it.interfaces.split(',')


def get_github_text():
    """
    Return GitHub text
    """
    return """
Go here to generate a GitHub personal access token:
https://github.com/settings/tokens
Required scopes are:
• read:org
• read:user
• user:email
• repo
"""


def not_found_xml(item):
    """
    Return XML representation of CLB item not found.
    """
    return (
        '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><itemNotFound xmlns="http://docs.openstack.org/loadbalancers/api/v1.0" code="404"><message>{0} not found</message></itemNotFound>'
        .format(item), 404)


def edit(text=None, editor=None, env=None, require_save=True, extension=
    '.txt', filename=None):
    """Edits the given text in the defined editor.  If an editor is given
    (should be the full path to the executable but the regular operating
    system search path is used for finding the executable) it overrides
    the detected editor.  Optionally, some environment variables can be
    used.  If the editor is closed without changes, `None` is returned.  In
    case a file is edited directly the return value is always `None` and
    `require_save` and `extension` are ignored.

    If the editor cannot be opened a :exc:`UsageError` is raised.

    Note for Windows: to simplify cross-platform usage, the newlines are
    automatically converted from POSIX to Windows and vice versa.  As such,
    the message here will have ``\\n`` as newline markers.

    :param text: the text to edit.
    :param editor: optionally the editor to use.  Defaults to automatic
                   detection.
    :param env: environment variables to forward to the editor.
    :param require_save: if this is true, then not saving in the editor
                         will make the return value become `None`.
    :param extension: the extension to tell the editor about.  This defaults
                      to `.txt` but changing this might change syntax
                      highlighting.
    :param filename: if provided it will edit this file instead of the
                     provided text contents.  It will not use a temporary
                     file as an indirection in that case.
    """
    from ._termui_impl import Editor
    editor = Editor(editor=editor, env=env, require_save=require_save,
        extension=extension)
    if filename is None:
        return editor.edit(text)
    editor.edit_file(filename)


def utc(dateString):
    """ ISO 8601の、UTCを示す末尾の 'Z' を、'+0000' に置き換える
    """
    if dateString.endswith('Z'):
        dateString = dateString.replace('Z', '+0000')
    return dateString


def values_in_acceptable_entries(sequence, allowed_values) ->bool:
    """Each value in the sequence must be an allowed values. Otherwise, False."""
    if len(sequence) == 0:
        return True
    for item in sequence:
        if item not in allowed_values:
            return False
    return True


def post_file(tbl, type, file_path=None, **file_storage_args):
    """
    This utility method is a generalizable method for moving files to an
    online file storage class. It is used by methods that require access
    to a file via a public url (e.g. VAN).

    **S3 is the only option allowed.**

    `Args:`
        tbl: object
            parsons.Table
        type: str
            ``S3``
        file_path: str
            The file path to store the file. Not required if provided with
            the **file_storage_args.
        **kwargs: kwargs
                Optional arguments specific to the file storage.
    `Returns:`
        ``None``
    """
    if type.capitalize() == 'S3':
        if 'key' in file_storage_args:
            file_storage_args['key'] = file_path
        return tbl.to_s3_csv(public_url=True, key=file_path, **
            file_storage_args)
    else:
        raise ValueError('Type must be S3.')


def minimal_spanning_tree(edges, weights, num_nodes):
    """
    Find the minimal spanning tree of a graph.
    :param edges: ndarray dim=(m,2) -- edges of the graph.
    :param weights: ndarray dim=(m,)  -- weights of the graph.
    :param num_nodes: int, number of nodes in the graph.
    :return: (the edge indices of the spanning tree)
    """
    try:
        from proj_module import mst
    except ImportError:
        print('cannot find this functions: proj_pcst')
        exit(0)
    select_indices = mst(edges, weights, num_nodes)
    return select_indices


def _diff_queryset(reference, qs1, qs2):
    """Compares two QuerySets by their primary keys."""
    if qs1 and qs2:
        pks1 = qs1.values_list('pk', flat=True)
        pks2 = qs2.values_list('pk', flat=True)
        if set(pks1) != set(pks2):
            return qs2
    elif qs1:
        if qs1.count():
            return qs2
    elif qs2:
        if qs2.count():
            return qs2


def counter(items):
    """
    Simplest required implementation of collections.Counter. Required as 2.6
    does not have Counter in collections.
    """
    results = {}
    for item in items:
        results[item] = results.get(item, 0) + 1
    return results


@staticmethod
def get_image_keys():
    """Return an iterable containing all image-keys"""
    return []


def disable_debug_messages():
    """
    Disable debugging message printing.
    """
    global debug_enabled
    debug_enabled = False


def solve_camera():
    """Solve camera motion from tracks

    """
    pass


def strip_figures(figure):
    """
	Strips a figure into multiple figures with a trace on each of them

	Parameters:
	-----------
		figure : Figure
			Plotly Figure
	"""
    fig = []
    for trace in figure['data']:
        fig.append(dict(data=[trace], layout=figure['layout']))
    return fig


@classmethod
def get_counterparty_addresses(cls, cp_ref, cp_type='Sender'):
    """
        Method for fetching counterparty's addresses.

        :example:
            ``Counterparty.get_counterparty_addresses('f70f1bee-55fd-11e5-8d8d-005056887b8d', cp_type='Recipient')``
        :param cp_ref:
            ID of the counterparty
        :type cp_ref:
            str or unicode
        :param cp_type:
            type of the counterparty: can be either `Sender` or `Recipient` (`Sender` used as default)
        :type cp_type:
            str or unicode
        :return:
            dictionary with info about counterparty's addresses
        """
    return cls.send(method='getCounterpartyAddresses', method_props={'Ref':
        cp_ref, 'CounterpartyProperty': cp_type})


def atse_updateManagedSchema(portal_type, schema_template, REQUEST=None,
    RESPONSE=None):
    """
        Update stored issue schema for all managed schemas.
        That can only done, if an complete object was registered.
        """


def trapped_rainwater(arr_tank):
    """
    The elements of the array are heights of walls.
    If it rains, how much rain water will be trapped?
    I will answer this question for any array you give me.
    """
    prev_ht = arr_tank[0]
    drops = []
    goingdown = True
    area = 0
    for ht in arr_tank[1:]:
        for i in range(len(drops)):
            drops[i] += 1
        if ht < prev_ht:
            goingdown = True
            for _ in range(prev_ht - ht):
                drops.append(0)
        elif ht > prev_ht:
            goingdown = False
            for _ in range(ht - prev_ht):
                if len(drops) > 0:
                    area += drops.pop()
        prev_ht = ht
        print(str(drops))
    return area


def __get_sc_executors_instances(sc):
    """Discover the location of the sparkonda module
    """
    sc.getConf()


def decoratorFactory(node):
    """Inject any additional keys in the node that are needed and return
        the new node.
        """


def determine_mapping_type(gene_table, pathways_to_genes, pathways_to_ecs):
    """
    Determine if the input file is of gene families or EC abundance type
    """
    all_genes = set()
    all_ecs = set()
    for pathway, genes in pathways_to_genes.items():
        all_genes.update(genes)
        all_ecs.update(pathways_to_ecs[pathway])
    for gene in gene_table:
        if gene in all_genes:
            return pathways_to_genes
        elif gene in all_ecs:
            return pathways_to_ecs


def dbs_has_min_columns(column_name_list):
    """
    Function determines if DBS headers passed contain the required
    columns.
    """
    compulsory_header_cols = set(['runtype', 'station', 'cast', 'niskin',
        'depth', 'bottle', 'date', 'time', 'temp', 'salt', 'po4', 'sio4',
        'acidconcL', 'pipVol', 'aciddens', 'pKchoice', 'CRMCT', 'CRMAT',
        'calcID', 'DIC'])
    missing_header_cols = compulsory_header_cols - set(column_name_list)
    if any(missing_header_cols):
        raise UserWarning(
            'The header is missing compulsory header columns: ' + str(
            missing_header_cols).replace('{', '').replace('}', ''))
    else:
        return True


def _get_field_length(bit_config):
    """
    Determine length of iso8583 style field

    :param bit_config: dictionary of bit config data
    :return: length of field
    """
    length_size = 0
    if bit_config['field_type'] == 'LLVAR':
        length_size = 2
    elif bit_config['field_type'] == 'LLLVAR':
        length_size = 3
    return length_size


def format_time(t):
    """Format seconds into a human readable form.

    >>> format_time(10.4)
    '10.4s'
    >>> format_time(1000.4)
    '16min 40.4s'
    """
    m, s = divmod(t, 60)
    h, m = divmod(m, 60)
    if h:
        return '{0:2.0f}hr {1:2.0f}min {2:4.1f}s'.format(h, m, s)
    elif m:
        return '{0:2.0f}min {1:4.1f}s'.format(m, s)
    else:
        return '{0:4.1f}s'.format(s)


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


def parse_length(int_or_string):
    """
    Parses length value or keywords into value.

    Args:
        int_or_string: string with number or keyword.
    Returns:
        A integer.
    """
    try:
        return int(int_or_string)
    except:
        pass
    try:
        dictionary = {'day': 1, 'week': 7, 'month': 30, 'year': 365, 'inf':
            365 * 1000000, 'infinite': 365 * 1000000, 'max': 365 * 1000000}
        return dictionary[int_or_string.lower()]
    except:
        pass
    raise Exception('Invalid period: ' + int_or_string)


def _convert_pandas_csv_options(pandas_options, columns):
    """ Translate `pd.read_csv()` options into `pd.DataFrame()` especially for header.

    Args:
        pandas_options (dict):
            pandas options like {'header': None}.
        columns (list):
            list of column name.
    """
    _columns = pandas_options.pop('names', columns)
    header = pandas_options.pop('header', 'infer')
    pandas_options.pop('encoding', None)
    if header == 'infer':
        header_line_number = 0 if not bool(_columns) else None
    else:
        header_line_number = header
    return _columns, header_line_number


@staticmethod
def set_fold_trigger(block, val):
    """
        Set the block fold trigger flag (True means the block is a fold
        trigger).

        :param block: block to set
        :param val: value to set
        """
    if block is None:
        return
    state = block.userState()
    if state == -1:
        state = 0
    state &= 2080374783
    state |= int(val) << 26
    block.setUserState(state)


def bmesh_to_mesh(bm: 'bmesh.types.BMesh', mesh: 'bpy.types.Mesh', object:
    'bpy.types.Object', skip_tessface: bool):
    """Converts a bmesh to a Mesh. This is reserved for exiting editmode.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param mesh: Undocumented.
    :type mesh: 'bpy.types.Mesh'
    :param object: Undocumented.
    :type object: 'bpy.types.Object'
    :param skip_tessface: don’t calculate mfaces
    :type skip_tessface: bool
    """
    pass


def pairs(seq):
    """Return a list of all adjacent elements."""
    if seq:
        iterable = iter(seq)
        prev = next(iterable)
        for _ in iterable:
            yield prev, _
            prev = _


def predict_bacteria(genome_id, bac_seqs, ar_seqs):
    """Check that domain assignment agrees with GTDB and NCBI taxonomy.

    Parameters
    ----------
    genome_id : str
        Genome of interest.
    bac_seqs : dict
        Bacterial sequences for all genomes.
    ar_seqs : dict
        Archaea sequences for all genomes.
    rep_is_bacteria : boolean
        Flag indicating if genome was classified as a Bacteria (True) or  Archaea (False).

    Returns
    -------
    boolean
        True if predicted domain is Bacteria, else False for Archaea.
    """
    rep_bac_seq = bac_seqs[genome_id]
    rep_ar_seq = ar_seqs[genome_id]
    per_bac_aa = float(len(rep_bac_seq) - rep_bac_seq.count('-')) / len(
        rep_bac_seq)
    per_ar_aa = float(len(rep_ar_seq) - rep_ar_seq.count('-')) / len(rep_ar_seq
        )
    is_bac = per_bac_aa >= per_ar_aa
    return is_bac, per_bac_aa, per_ar_aa


def get_health_check_count():
    """
    Retrieves the number of health checks that are associated with the current AWS account.
    See also: AWS API Documentation

    :example: response = client.get_health_check_count()

    :rtype: dict
    :return: {
        'HealthCheckCount': 123
    }

    """
    pass


def exists(env):
    """Standard library tar function should always exist."""
    return True


def reaction_box_width(n, params):
    """ Calculate the width of the boxes containing reactions

    Parameters
    ----------
    n: int,
        Number of reactions in the box
    params: dict,
        Layout parameters

    Returns
    -------
    float or int,
        Width of the reaction box
    """
    if n == 0:
        return 0
    else:
        width = params['reaction_width']
        return n * width + (n - 1) * params['reaction_x_padding']


def register_ad_cb():
    """Advertisement registration callback."""
    print('Advertisement registered')


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

    The ".dev0" means dirty.

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


def get_decoded_str(root, encoded_string):
    """Decode encoded string and return it"""
    decoded_data = []
    current = root
    for code in encoded_string:
        if code == '0':
            current = current.left
        if code == '1':
            current = current.right
        if current.is_leaf():
            char = current.char
            decoded_data.append(char)
            current = root
    return ''.join(decoded_data)


def match_events(port, label):
    """ Find the given label in an event DataFrame

    Args:
        port (Port): The event port.
        label (str): The string to look for in the label column.

    Returns:
        DataFrame: The list of matched events, or `None` if there is no match.

    """
    matches = None
    if port.ready():
        matches = port.data[port.data['label'] == label]
        if matches.empty:
            matches = None
    return matches


@staticmethod
def truncate(coord):
    """
        Formats a coordinate to within an acceptable degree of accuracy (i.e. 2
        decimal places for mercator).
        """
    raise NotImplementedError()


def iindex(x, iterable):
    """Like list.index, but for a general iterable.

    Note that just like ``x in iterable``, this will not terminate if ``iterable``
    is infinite, and ``x`` is not in it.

    Note that as usual when working with general iterables, the iterable will
    be consumed, so this only makes sense for memoized iterables (and even then
    it may be better to extract the desired part as a list and then search there).
    """
    for j, elt in enumerate(iterable):
        if elt == x:
            return j
    raise ValueError('{} is not in iterable'.format(x))


def list_directory(directory_path):
    """ List the contents of a directory stored in a Dropbox folder.

    Keyword arguments:
    directory_path -- Path and name of directory to upload.
    """
    pass


@staticmethod
def splitCmd(cmdTemplate, content):
    """
        Chose from an optionful and optionless version of a command
        e.g. oo{content} vs oo[opts]{content}
        :param cmdTemplate: Tuple of optionful and optionless versions
        :param content: Comma-separated list of options, the last (possibly only) one being the content
        """
    i = content.rfind(',')
    if i > -1:
        return cmdTemplate[0] % (content[:i], content[i + 1:]) + '\n'
    else:
        return cmdTemplate[1] % content + '\n'


def add_repo_args(parser):
    """Add arguments related to adding repositories to the command line"""
    group = parser.add_argument_group('repositories')
    group.add_argument('-n', '--solution', action='append', dest=
        'solutions', default=[], metavar='solution_file', help=
        'Existing fully-pinned constraints file to use as a baseline when compiling'
        )
    group.add_argument('-s', '--source', action='append', dest='sources',
        default=[], metavar='project_dir', help=
        'Search for projects in the provided directory recursively')
    group.add_argument('-x', '--exclude-source', action='append', dest=
        'excluded_sources', default=[], help=
        'Directories to exclude when searching for projects. Applies recursively'
        )
    group.add_argument('-f', '--find-links', action='append', default=[],
        metavar='directory', help=
        'Directory to search for wheel and source distributions')
    group.add_argument('-i', '--index-url', action='append', dest=
        'index_urls', default=[], metavar='index_url', help=
        'Link to a remote index of python distributions (http or https)')
    group.add_argument('-w', '--wheel-dir', type=str, default=None, metavar
        ='wheel_dir', help=
        'Directory to which to download wheel and source distributions from remote index'
        )
    group.add_argument('--no-index', action='store_true', default=False,
        help='Do not connect to the internet to compile')


@classmethod
def fromElement(Class, element):
    """
        Create a stanza from a L{domish.Element}.
        """
    stanza = Class()
    stanza.parseElement(element)
    return stanza


def auto_undent(string):
    """
    Unindent a docstring.
    """
    lines = string.splitlines()
    while lines[0].strip() == '':
        lines = lines[1:]
        if not lines:
            return []
    spaces = len(lines[0]) - len(lines[0].lstrip(' '))
    out = []
    for line in lines:
        num_spaces = len(line) - len(line.lstrip(' '))
        out.append(line[min(spaces, num_spaces):])
    return out


def base_quote_short_from_asset_pair(ap_str):
    """Try to identify the short version of the base and quote of the asset pair"""
    ap_str = ap_str.upper()
    if len(ap_str) == 8:
        base = ap_str[1:4] if ap_str[0] in ['Z', 'X'] else ap_str[:4]
        quote = ap_str[5:] if ap_str[4] in ['Z', 'X'] else ap_str[4:]
    elif len(ap_str) == 6:
        base = ap_str[:3]
        quote = ap_str[3:]
    elif len(ap_str) == 7:
        if ap_str[-4] in ['Z', 'X']:
            base = ap_str[:3]
            quote = ap_str[4:]
        elif ap_str[0] in ['Z', 'X']:
            base = ap_str[1:4]
            quote = ap_str[4:]
        else:
            base = ap_str[:4]
            quote = ap_str[4:]
    return base, quote


def update_problem(user):
    """Persists given problem and returns it."""


def _related(f1, f2):
    """return True if f1 and f2 filectx have a common ancestor

    Walk back to common ancestor to see if the two files originate
    from the same file. Since workingfilectx's rev() is None it messes
    up the integer comparison logic, hence the pre-step check for
    None (f1 and f2 can only be workingfilectx's initially).
    """
    if f1 == f2:
        return True
    g1, g2 = f1.ancestors(), f2.ancestors()
    try:
        f1r, f2r = f1.linkrev(), f2.linkrev()
        if f1r is None:
            f1 = next(g1)
        if f2r is None:
            f2 = next(g2)
        while True:
            f1r, f2r = f1.linkrev(), f2.linkrev()
            if f1r > f2r:
                f1 = next(g1)
            elif f2r > f1r:
                f2 = next(g2)
            else:
                return f1 == f2
    except StopIteration:
        return False


def example_transform(v, row, row_n, i_s, i_d, header_s, header_d, scratch,
    errors, accumulator):
    """ An example column transform.

    This is an example of a column transform with all of the arguments listed. An real transform
    can omit any ( or all ) of these, and can supply them in any order; the calling code will inspect the
    signature.

    When the function is listed as a transform for a column, it is called for every row of data.

    :param v: The current value of the column
    :param row: A RowProxy object for the whiole row.
    :param row_n: The current row number.
    :param i_s: The numeric index of the source column
    :param i_d: The numeric index for the destination column
    :param header_s: The name of the source column
    :param header_d: The name of the destination column
    :param scratch: A dict that can be used for storing any values. Persists between rows.
    :param errors: A dict used to store error messages. Persists for all columns in a row, but not between rows.
    :param accumulator: A dict for use in accumulating values, such as computing aggregates.
    :return: The final value to be supplied for the column.
    """
    return str(v) + '-foo'


def mask_characters(expression, search_text, target_text, mask_char):
    """Mask characters found by a regular expression with mask character. Mask characters will equal length of masked
    string.
    A different target text to search text may be used, but the developer must ensure that they are compatible.
    This feature may be used to handle combinations of N mask_char(s) differently

    :param expression: regex expression
    :param search_text: text to search for matches
    :param target_text: text to apply mask to
    :param mask_char: character to replace masked characters
    """
    matches = []
    pos = 0
    masked_text = ''
    for match in expression.finditer(search_text):
        matches.append(match)
        masked_text += target_text[pos:match.start()] + mask_char * (match.
            end() - match.start())
        pos = match.end()
    masked_text += target_text[pos:]
    return masked_text, matches


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

        :param FileLikeCommentDetails val:
        :rtype: EventDetails
        """
    return cls('file_like_comment_details', val)


@staticmethod
def parse_schema(schemas):
    """
        Convert list of FieldSchema objects in a list of name:typ strings

        :param schemas:
        :type schemas: list[FieldSchema]
        :return:
        """
    return map(lambda s: '{}\t{}'.format(s.name, s.type), schemas)


def find_range_ix_in_point_list(start, end, point_list):
    """Returns the index range all points inside the given range.

    Parameters
    ---------
    start : float
        The start of the desired range.
    end : float
        The end of the desired range.
    point_list : sortedcontainers.SortedList
        A list of points.

    Returns
    -------
    iterable
        The index range of all points inside the given range.

    Example
    -------
    >>> from sortedcontainers import SortedList
    >>> point_list = SortedList([5, 8, 15])
    >>> find_range_ix_in_point_list(3, 4, point_list)
    [0, 0]
    >>> find_range_ix_in_point_list(3, 7, point_list)
    [0, 1]
    >>> find_range_ix_in_point_list(3, 8, point_list)
    [0, 2]
    >>> find_range_ix_in_point_list(4, 15, point_list)
    [0, 3]
    >>> find_range_ix_in_point_list(4, 321, point_list)
    [0, 3]
    >>> find_range_ix_in_point_list(6, 321, point_list)
    [1, 3]
    """
    return [point_list.bisect_left(start), point_list.bisect_right(end)]


def get_block_coordinate_range(block_number, block_size, overlap_size,
    image_size):
    """
    Returns the minimum and maximum coordinate values in one dimension for
    an image block, where the dimension length image_size is to be split into
    the number of blocks specified by block_size with an overlap of
    overlap_size voxels at each boundary, and the current block_number is
    specified. There is no overlap at the outer border of the image, and the
    length of the final block is reduced if necessary so there is no padding
    """
    if block_number == 0:
        min_coord = 0
        start_border = 0
    else:
        min_coord = block_number * block_size - overlap_size
        start_border = overlap_size
    end_border = overlap_size
    max_coord = int((block_number + 1) * block_size - 1 + overlap_size)
    if max_coord >= image_size:
        max_coord = image_size - 1
        end_border = 0
    return [min_coord, max_coord, start_border, end_border]


def disp_notfound():
    """ Display 'bad request -/- not found in red. """
    from x84.bbs import getterminal, echo
    term = getterminal()
    echo(u'\r\n\r\n{bad_req} {decorator} {not_found}'.format(bad_req=term.
        bold(u'bad request'), decorator=term.bold_red(u'-/-'), not_found=
        term.bold(u'not found.')))


def Dequiv(fsm, states, agents):
    """
    Return the set of fsm that equivalent to states w.r.t. distributed
    knowledge of agents.

    fsm -- a MAS representing the system
    states -- a BDD representing a set of states of fsm
    agents -- a set of agents names of fsm.
    """
    return fsm.equivalent_states(states, frozenset({agents}))


def get_translation(language):
    """
        get translation (translated object) if exists
        """


def notebooks(args):
    """Allows you to download or upload notebooks"""
    pass


def get_pyaudio():
    """
    Source: https://github.com/Uberi/speech_recognition/blob/master/speech_recognition/__init__.py

    Imports the pyaudio module and checks its version. Throws exceptions if pyaudio can't be found or a
    wrong version is installed
    """
    try:
        import pyaudio
    except ImportError:
        raise AttributeError('Could not find PyAudio; check installation')
    from distutils.version import LooseVersion
    if LooseVersion(pyaudio.__version__) < LooseVersion('0.2.11'):
        raise AttributeError(
            'PyAudio 0.2.11 or later is required (found version {})'.format
            (pyaudio.__version__))
    return pyaudio


def _esc_double_quotes(str1):
    """ Escapes double quotes.
    """
    return str1.replace('"', '\\"').replace('\\\\\\"', '\\"').replace('\\\\"',
        '\\"')


def _clipSeq(seq, quals, sep='.'):
    """Clip sequence at first sep base (. or N). Clip quals accordingly."""
    if sep in seq:
        pos = seq.index(sep)
        seq, quals = seq[:pos], quals[:pos]
    return seq, quals


def approximate_pubo_extrema(P):
    """approximate_pubo_extrema.

    Find the approximate minimum and maximum possible values that a PUBO can
    take. This is very approximate! The estimated minimum value that this
    function returns will definitely be less than or equal to the true
    minimum (most likely, it will be much less). Similarly, the estimated
    maximum value that this function returns will definitely be greater than or
    equal to the true maximum (most likely, it will be much more).

    Parameters
    ----------
    P : dict, PUBO, or PUBOMatrix object.
        ``P`` represents a PUBO. Please see ``qubovert.PUBO`` or
        ``qubovert.utils.PUBOMatrix``.

    Return
    ------
    bounds : tuple (min, max).
        The approximate minimum and maximum of the PUBO.

    """
    min_, max_ = 0, 0
    for k, v in P.items():
        if not k:
            min_ += v
            max_ += v
        elif v < 0:
            min_ += v
        else:
            max_ += v
    return min_, max_


def stringify_value(value):
    """Convert any value to string.
    """
    if value is None:
        return u''
    isoformat = getattr(value, 'isoformat', None)
    if isoformat is not None:
        value = isoformat()
    return type(u'')(value)


def default_key_func(key, key_prefix, version):
    """
    Default function to generate keys.

    Constructs the key used by all other methods. By default it prepends
    the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
    function with custom key making behavior.
    """
    return '%s:%s:%s' % (key_prefix, version, key)


@classmethod
def _ignore_path(cls, path, ignore_list=None, white_list=None):
    """Returns a whether a path should be ignored or not."""
    ignore_list = ignore_list or []
    white_list = white_list or []
    return cls._matches_patterns(path, ignore_list
        ) and not cls._matches_patterns(path, white_list)


def interleave(seq1, seq2):
    """
    Interleave elements of `seq2` between consecutive elements of `seq1`.

        >>> list(interleave([1, 3, 5], [2, 4]))
        [1, 2, 3, 4, 5]

    """
    iterator1, iterator2 = iter(seq1), iter(seq2)
    leading = next(iterator1)
    for element in iterator1:
        yield leading
        yield next(iterator2)
        leading = element
    yield leading


@staticmethod
def search_svc_object_by_name(service, svc_obj_name=None):
    """
        Return service object by name
        Args:
            service: Service object
            svc_obj_name: Name of service object to find

        Returns: Service object if found else None

        """
    if not svc_obj_name:
        return None
    for svc_object in service.list():
        svc_obj = service.get(svc_object)
        if svc_obj.name == svc_obj_name:
            return svc_obj
    return None


@classmethod
def get_real_child_model(cls, data):
    """Returns the real base class specified by the discriminator"""
    discriminator_value = data[cls.json_discriminator_key]
    return cls.discriminator_value_class_map.get(discriminator_value)


def resolve_name(name):
    """Resolve a name like ``module.object`` to an object and return it.

    Raise `ImportError` if the module or name is not found.
    """
    parts = name.split('.')
    cursor = len(parts) - 1
    module_name = parts[:cursor]
    attr_name = parts[-1]
    while cursor > 0:
        try:
            ret = __import__('.'.join(module_name), fromlist=[attr_name])
            break
        except ImportError:
            if cursor == 0:
                raise
            cursor -= 1
            module_name = parts[:cursor]
            attr_name = parts[cursor]
            ret = ''
    for part in parts[cursor:]:
        try:
            ret = getattr(ret, part)
        except AttributeError:
            raise ImportError(name)
    return ret


def levenshtein_distance(text_1, text_2, ignore_space=True):
    """
	Get Levenshtein distance between two lines of text.
	"""
    s1 = text_1.replace(' ', '').lower() if ignore_space else text_1.lower()
    s2 = text_2.replace(' ', '').lower() if ignore_space else text_2.lower()
    len_1, len_2 = len(s1), len(s2)
    if len_1 == 0 or len_2 == 0:
        return max(len_1, len_2)
    manipulation = [[(0) for _ in range(len_2 + 1)] for _ in range(len_1 + 1)]
    for row in range(len_1 + 1):
        manipulation[row][0] = row
    for col in range(len_2 + 1):
        manipulation[0][col] = col
    for i in range(1, len_1 + 1):
        for j in range(1, len_2 + 1):
            cost = 1 if s1[i - 1] != s2[j - 1] else 0
            manipulation[i][j] = min(manipulation[i - 1][j - 1] + cost,
                manipulation[i - 1][j] + 1, manipulation[i][j - 1] + 1)
    distance = manipulation[-1][-1]
    return distance


def get_format_label(_ns, fmt):
    """
    Return short text description of the format, ready for printing.

    :type fmt: LMIInstance/CIM_LocalFileSystem or LMIInstance/LMI_DataFormat
    :param fmt: Format to describe.

    :rtype: string
    """
    if 'FormatType' in fmt.properties():
        return fmt.FormatTypeDescription
    elif 'FileSystemType' in fmt.properties():
        return fmt.FileSystemType
    else:
        return 'Unknown'


def delete_file(filename):
    """ Deletes a specified file from a user's Dropbox account.

    Keyword arguments:
    filename -- Name of file to delete from Dropbox account.
    """
    pass


def _LDRH_immediate(cpu, reg_op, mem_op, mimm_op):
    """
        LDRH (immediate).

        :param reg_op: destination register.
        :param mem_op: memory.
        :param mimm_op: None or immediate.
        """
    cpu._ldr_str_immediate(reg_op, mem_op, mimm_op, ldr=True, size=16)


def if_json_contain(left_json, right_json, op='strict'):
    """
    判断一个 json 是否包含另外一个 json 的 key，并且 value 相等；

    :param:
        * left_json: (dict) 需要判断的 json，我们称之为 left
        * right_json: (dict) 需要判断的 json，我们称之为 right，目前是判断 left 是否包含在 right 中
        * op: (string) 判断操作符，目前只有一种，默认为 strict，向后兼容
    :return:
        * result: (bool) right json 包含 left json 的 key，并且 value 一样，返回 True，否则都返回 False

    举例如下::

        print('--- json contain demo ---')
        json1 = {"id": "0001"}
        json2 = {"id": "0001", "value": "File"}
        print(if_json_contain(json1, json2))
        print('---')

    执行结果::

        --- json contain demo ---
        True
        ---

    """
    key_list = left_json.keys()
    if op == 'strict':
        for key in key_list:
            if not right_json.get(key) == left_json.get(key):
                return False
        return True


def generate_sql_insert(tablename, columns, placeholder="'%s'"):
    """ Generate the sql statment template for all the inserts """
    fields = ','.join(columns)
    places = ','.join([placeholder] * len(columns))
    sql = 'insert into %s (%s) values (%s);' % (tablename, fields, places)
    return sql


def mapkey(client, script):
    """Run a Mapkey script in Creo.

    Make sure to remove any `mapkey(continued)` clauses from the script
    argument. The tilde at the start of a line should occur immediately
    after the semicolon at the end of the previous line.

    Args:
        client (obj): creopyson Client.
        script (str): The mapkey script to run.

    Returns: None

    """
    data = {'script': script}
    return client._creoson_post('interface', 'mapkey', data)


def isfile():
    """
        Check if this file path refers to a regular file.

        @return: C{True} if the file at this file path is a regular file,
            C{False} otherwise.
        """


def get_max_delta_mags(model):
    """Largest value minus second largest value of fitted Lomb Scargle model."""
    return model['max_delta_mags']


def gen_slices(start, stop, blocksize):
    """
    Yields slices of lenght at most block_size.

    >>> list(gen_slices(1, 6, 2))
    [slice(1, 3, None), slice(3, 5, None), slice(5, 6, None)]
    """
    assert start <= stop, (start, stop)
    assert blocksize > 0, blocksize
    while True:
        yield slice(start, min(start + blocksize, stop))
        start += blocksize
        if start >= stop:
            break


def _update_pulled_fields(instance, imported_instance, fields):
    """ Update instance fields based on imported from backend data.

        Save changes to DB only one or more fields were changed.
    """
    modified = False
    for field in fields:
        pulled_value = getattr(imported_instance, field)
        if getattr(instance, field) != pulled_value:
            setattr(instance, field, pulled_value)
            modified = True
    if modified:
        instance.save()


def wrap_unsafe_or_pattern(pattern):
    """
    Wraps any pattern that contains an unsafe or operator inside an (?:...)
    """
    if '|' in pattern:
        return '(?:%s)' % pattern
    else:
        return pattern


def trunc(data=None, name=None, attr=None, out=None, **kwargs):
    """Return the element-wise truncated value of the input.

    The truncated value of the scalar x is the nearest integer i which is closer to
    zero than x is. In short, the fractional part of the signed number x is discarded.

    Example::

       trunc([-2.1, -1.9, 1.5, 1.9, 2.1]) = [-2., -1.,  1.,  1.,  2.]

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

       - trunc(default) = default
       - trunc(row_sparse) = row_sparse
       - trunc(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_basic.cc:L857

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

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

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


@classmethod
def from_file(cls, filepath):
    """Initialize the object from a netcdf_ file."""
    return cls(filepath)


def is_contained(trace, dt1, dt2, timestamp_key):
    """
    Check if a trace is contained in the given interval

    Parameters
    -----------
    trace
        Trace to check
    dt1
        Lower bound to the interval
    dt2
        Upper bound to the interval
    timestamp_key
        Timestamp attribute

    Returns
    -----------
    boolean
        Is true if the trace is contained
    """
    if trace:
        if trace[0][timestamp_key].replace(tzinfo=None) > dt1 and trace[-1][
            timestamp_key].replace(tzinfo=None) < dt2:
            return True
    return False


def channel_to_freq(channel):
    """
    freq -- frequqncy in Hz
    return -- channel number
    """
    if 1 <= channel <= 13:
        return 2407000000 + channel * 5 * 1000000
    if channel == 14:
        return 2484000000
    if channel >= 15:
        return 5035000000 + (channel - 7) * 5 * 1000000
    return None


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 reset(cls):
    """Reset to default state."""
    cls.notes_number = 0
    return


def compute_fasta_offset(sequence_location, header_size, line_size,
    cr_lf_size=1):
    """
    Given a location on a FASTA sequence (assuming one sequence per file),
    the length of the header line and a line length (including CR/LF),
    (assumes the line size is constant throughout the file),
    returns the file location of the specified sequence location
    """
    num_lines = int(sequence_location / (line_size - cr_lf_size))
    line_offset = sequence_location % (line_size - cr_lf_size)
    return num_lines * line_size + line_offset + header_size


def delete_subscriber(AccountId=None, BudgetName=None, Notification=None,
    Subscriber=None):
    """
    Delete a Subscriber for a notification
    See also: AWS API Documentation

    :example: response = client.delete_subscriber(
        AccountId='string',
        BudgetName='string',
        Notification={
            'NotificationType': 'ACTUAL'|'FORECASTED',
            'ComparisonOperator': 'GREATER_THAN'|'LESS_THAN'|'EQUAL_TO',
            'Threshold': 123.0
        },
        Subscriber={
            'SubscriptionType': 'SNS'|'EMAIL',
            'Address': 'string'
        }
    )

    :type AccountId: string
    :param AccountId: [REQUIRED] Account Id of the customer. It should be a 12 digit number.

    :type BudgetName: string
    :param BudgetName: [REQUIRED] A string represents the budget name. No ':' character is allowed.

    :type Notification: dict
    :param Notification: [REQUIRED] Notification model. Each budget may contain multiple notifications with different settings.
            NotificationType (string) -- [REQUIRED] The type of a notification. It should be ACTUAL or FORECASTED.
            ComparisonOperator (string) -- [REQUIRED] The comparison operator of a notification. Currently we support less than, equal to and greater than.
            Threshold (float) -- [REQUIRED] The threshold of the a notification. It should be a number between 0 and 100.

    :type Subscriber: dict
    :param Subscriber: [REQUIRED] Subscriber model. Each notification may contain multiple subscribers with different addresses.
            SubscriptionType (string) -- [REQUIRED] The subscription type of the subscriber. It can be SMS or EMAIL.
            Address (string) -- [REQUIRED] A generic String.

    :rtype: dict
    :return: {}

    :returns:
    (dict) -- Response of DeleteSubscriber

    """
    pass


@classmethod
def has_resuming(cls):
    """Returns whether it supports to resume the fetch process.

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


def fmt_datetime(d, fmt='', local=True):
    """
    format date with local support
    ``d``: datetime to format
    ``fmt``: format, default is '%Y-%m-%d %H-%M'
    ``local``: format as local time
    """
    if not d:
        return ''
    if local:
        from django.templatetags.tz import localtime
        d = localtime(d)
    if not fmt:
        fmt = '%Y-%m-%d %H-%M'
    return d.strftime(fmt)


def collection_add():
    """Add an object to a new collection

    """
    pass


@classmethod
def _setupModel(cls):
    """
            _setupModel - Class method called once to validate and ensure class is setup right.

                Afer called once this function will replace itself with the dummy _setupModel_Finished
        """
    if cls.PRIMARY_KEY not in cls.FIELDS:
        cls.FIELDS = [cls.PRIMARY_KEY] + list(cls.FIELDS)
    cls._setupModel = cls._setupModel_Finished


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


def order_case_queryset(cases, field, asc=False):
    """
    Annotate the TestCase queryset by calling order_by on it.
    """
    orderable_fields = ('case_id', 'summary', 'author__username',
        'default_tester__username', 'priority', 'is_automated',
        'category__name', 'case_status', 'create_date')
    if field in orderable_fields:
        order_by = field
        if not asc:
            order_by = '-%s' % order_by
        cases = cases.order_by(order_by)
    return cases


def numatoms(mol) ->int:
    """
    Number of atoms.

    Parameters
    ----------
    mol:
        Molecule

    Returns
    -------
    int
        Number of atoms
    """
    return mol.GetNumAtoms()


@staticmethod
def process_sql(_query_name, _op_type, sql):
    """Pass through function because the ``sqlite3`` driver already handles the :var_name
        "named style" syntax used by aiosql variables. Note, it will also accept "qmark style"
        variables.

        Args:
            _query_name (str): The name of the sql query. Unused.
            _op_type (aiosql.SQLOperationType): The type of SQL operation performed by the sql.
            sql (str): The sql as written before processing.

        Returns:
            str: Original SQL text unchanged.
        """
    return sql


def jacobi(a, n):
    """
    Return Jacobi symbol (or Legendre symbol if n is prime)
    """
    s = 1
    while True:
        if n < 1:
            raise ValueError('Too small module for Jacobi symbol: ' + str(n))
        if n & 1 == 0:
            raise ValueError('Jacobi is defined only for odd modules')
        if n == 1:
            return s
        a = a % n
        if a == 0:
            return 0
        if a == 1:
            return s
        if a & 1 == 0:
            if n % 8 in (3, 5):
                s = -s
            a >>= 1
            continue
        if a % 4 == 3 and n % 4 == 3:
            s = -s
        a, n = n, a
    return


@classmethod
def get_transitions(cls) ->list:
    """
        Returns default status transitions.
        """
    return {'NEW': [cls.CREATED], 'CREATED': [cls.HOLD, cls.FAILED, cls.
        CANCELLED, cls.PROCESSING], 'HOLD': [cls.FAILED, cls.CANCELLED, cls
        .PROCESSING], 'FAILED': [cls.CANCELLED, cls.PROCESSING],
        'CANCELLED': [], 'PROCESSING': [cls.SHIPPED, cls.COMPLETED, cls.
        REFUNDED], 'SHIPPED': [cls.COMPLETED, cls.REFUNDED], 'COMPLETED': [
        cls.REFUNDED], 'REFUNDED': []}


def Type(TName, TType):
    """
	Return code for type declaration.
	"""
    return '\ntype {0} is {1};'.format(TName, TType)


def aps09_f(x, n):
    """Upside down quartic with parametrizable height"""
    return (1 + (1 - n) ** 4) * x - (1 - n * x) ** 4


def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
    """Unsets a cookie by name, by default over all domains and paths.

    Wraps CookieJar.clear(), is O(n).
    """
    clearables = []
    for cookie in cookiejar:
        if cookie.name != name:
            continue
        if domain is not None and domain != cookie.domain:
            continue
        if path is not None and path != cookie.path:
            continue
        clearables.append((cookie.domain, cookie.path, cookie.name))
    for domain, path, name in clearables:
        cookiejar.clear(domain, path, name)


@classmethod
def from_bytes(cls, bytes):
    """ Fixed-length recreation.
        """
    plain_int = super().from_bytes(bytes, 'big', signed=False)
    return cls(plain_int)


def error_views():
    """Return views of any errors.

        The errors are returned as an iterable.
        """


def dict_strs_to_dict(*dict_strs):
    """
    Parses a list of key:value strings into a dict. Used to go from CLI->Python.
    """
    d = {}
    for dict_str in dict_strs:
        try:
            k, v = dict_str.split(':', 1)
        except ValueError:
            raise ValueError(
                "can't parse string '{0}': must have format 'key:value'".
                format(dict_str))
        d[k] = v
    return d


def removeSchema(schema_id):
    """ Remove an existing schema with the given ID.

        o Raise KeyError if no such schema exists.
        """


def _iterate_sagittal_slices(array, limits=None):
    """Iterate sagittal slices."""
    shape = array.shape[0]
    for ind in range(shape):
        if limits and ind not in limits:
            continue
        yield ind, array[(ind), :, :]


@classmethod
def RegisterOutput(cls, output_class, disabled=False):
    """Registers an output class.

    The output classes are identified based on their NAME attribute.

    Args:
      output_class (type): output module class.
      disabled (Optional[bool]): True if the output module is disabled due to
          the module not loading correctly or not.

    Raises:
      KeyError: if output class is already set for the corresponding name.
    """
    output_name = output_class.NAME.lower()
    if disabled:
        class_dict = cls._disabled_output_classes
    else:
        class_dict = cls._output_classes
    if output_name in class_dict:
        raise KeyError('Output class already set for name: {0:s}.'.format(
            output_class.NAME))
    class_dict[output_name] = output_class


def item_name_from_object(obj):
    """Return plot item class name from instance"""
    return obj.__class__.__name__


def _auto_add_extension(file_name, engine):
    """Make sure a file name has an extension that reflects its
    file type.
    """
    if '.h5' not in file_name and '.nc' not in file_name:
        extension = '.h5' if engine == 'h5netcdf' else '.nc'
        file_name += extension
    return file_name


def print_DBG(txt):
    """Prints debug information on stdout."""
    print('[DBG] ' + txt)


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

        :param FolderOverviewItemUnpinnedDetails val:
        :rtype: EventDetails
        """
    return cls('folder_overview_item_unpinned_details', val)


@classmethod
def silent(cls, duration=1000, frame_rate=11025):
    """
        Generate a silent audio segment.
        duration specified in milliseconds (default duration: 1000ms, default frame_rate: 11025).
        """
    frames = int(frame_rate * (duration / 1000.0))
    data = b'\x00\x00' * frames
    return cls(data, metadata={'channels': 1, 'sample_width': 2,
        'frame_rate': frame_rate, 'frame_width': 2})


def job_outputs(job):
    """return vars that are produced by the job"""
    return job['output'].values()


def cross_vectors(u, v):
    """Compute the cross product of two vectors.

    Parameters
    ----------
    u : tuple, list, Vector
        XYZ components of the first vector.
    v : tuple, list, Vector
        XYZ components of the second vector.

    Returns
    -------
    cross : list
        The cross product of the two vectors.

    Notes
    -----
    The xyz components of the cross product of two vectors :math:`\\mathbf{u}`
    and :math:`\\mathbf{v}` can be computed as the *minors* of the following matrix:

    .. math::
       :nowrap:

        \\begin{bmatrix}
        x & y & z \\\\
        u_{x} & u_{y} & u_{z} \\\\
        v_{x} & v_{y} & v_{z}
        \\end{bmatrix}

    Therefore, the cross product can be written as:

    .. math::
       :nowrap:

        \\mathbf{u} \\times \\mathbf{v}
        =
        \\begin{bmatrix}
        u_{y} * v_{z} - u_{z} * v_{y} \\\\
        u_{z} * v_{x} - u_{x} * v_{z} \\\\
        u_{x} * v_{y} - u_{y} * v_{x}
        \\end{bmatrix}

    Examples
    --------
    >>> cross_vectors([1.0, 0.0, 0.0], [0.0, 1.0, 0.0])
    [0.0, 0.0, 1.0]

    """
    return [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[
        1] - u[1] * v[0]]


def wrapstring(str_, rowstart, rowend, padfirst=True):
    """
    wraps the provided string in lines of length rowend-rowstart
    and padded on the left by rowstart.
    -> if padfirst is false the first line is not padded
    """
    rowlen = rowend - rowstart
    leftpad = rowstart
    wrappedstr = ''
    if len(str_) / rowlen < 1:
        if padfirst:
            return leftpad * ' ' + str_ + '\n'
        else:
            return str_ + '\n'
    for linenum in range(1 + int(len(str_) / rowlen)):
        if linenum == 0 and not padfirst:
            wrappedstr += str_[linenum * rowlen:(linenum + 1) * rowlen] + '\n'
        else:
            wrappedstr += ' ' * leftpad + str_[linenum * rowlen:(linenum +
                1) * rowlen] + '\n'
    return wrappedstr


def _delist(series):
    """ turn listed cols into tuples, or extract their single element """
    series = series.copy(deep=True)
    lens = series.dropna().apply(len).unique()
    if len(lens) > 1:
        series[~series.isnull()] = series.dropna().apply(tuple)
    elif len(lens) == 1 and lens.item() == 1:
        series[~series.isnull()] = series.dropna().apply(lambda x: x[0])
    return series


def is_bad_hostname(domain):
    """
    Domain has a bad hostname if its canonical https endpoint fails
    hostname validation
    """
    canonical, https, httpswww = (domain.canonical, domain.https, domain.
        httpswww)
    if canonical.host == 'www':
        canonical_https = httpswww
    else:
        canonical_https = https
    return canonical_https.https_bad_hostname


def _set_graph_edge(graph, tokens, word_a, word_b):
    """Sets an edge between nodes named word_a and word_b if they exists in `tokens` and `graph`, inplace.

    Parameters
    ----------
    graph : :class:~gensim.summarization.graph.Graph
        Given graph.
    tokens : dict
        Original units (words) as keys and processed units (tokens) as values.
    word_a : str
        First word, name of first node.
    word_b : str
        Second word, name of second node.

    """
    if word_a in tokens and word_b in tokens:
        lemma_a = tokens[word_a].token
        lemma_b = tokens[word_b].token
        edge = lemma_a, lemma_b
        if graph.has_node(lemma_a) and graph.has_node(lemma_b
            ) and not graph.has_edge(edge):
            graph.add_edge(edge)


def int_to_be_bytes(value, size=None):
    """Converts an integer to a big-endian sequence of bytes"""
    if size is None:
        size = (value.bit_length() + 7) // 8
    return value.to_bytes(size, 'big')


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['type']
    if type == 'INTERNAL_COMPUTE':
        return 'InternalSourceDetails'
    if type == 'OCIC':
        return 'OcicSourceDetails'
    else:
        return 'SourceDetails'


def endswith_str(text, suffix, start=None, end=None):
    """
    Determines if ``text`` ends with the specified suffix.

    The suffix can also be a tuple of suffixes to look for. With optional parameter ``start``,
    the test will begin at that position. With optional parameter ``end``, the test will
    stop comparing at that position.

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

    :param suffix: The suffix to search for
    :type suffix:  ``str`` or ``tuple`` of ``str``

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

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

    :return: True if ``text`` ends with the specified suffix, otherwise return False.
    :rtype:  ``int``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.endswith(suffix, start, end)


@classmethod
def _base_query_drop(cls, type: str, if_exists: bool=True, cascade: bool=False
    ) ->str:
    """Generates a DROP stub."""
    builder = ['DROP']
    builder.append(type)
    if if_exists:
        builder.append('IF EXISTS')
    builder.append(cls._name)
    if cascade:
        builder.append('CASCADE')
    return ' '.join(builder)


def get_element_counts(basis):
    """
    Returns chemical elements with their count wrt their original order in the basis.
    Note: entries for the same element separated by another element are considered separately.
    [{"count":1, "value":"Zr"}, {"count":23, "value":"H"}, {"count":11, "value":"Zr"}, {"count":1, "value":"H"}]
    """
    element_counts = []
    previous_element = None
    for index, element in enumerate(basis['elements']):
        if previous_element and previous_element['value'] == element['value']:
            element_counts[-1]['count'] += 1
        else:
            element_counts.append({'count': 1, 'value': element['value']})
        previous_element = basis['elements'][index]
    return element_counts


def get_non_optional_settings(bears):
    """
    From the bear dict, get the non-optional settings.

    :param bears:
        A dict with language name as key and bear classes as value.
    :return:
        A dict with Bear class as key and bear non-optional settings as value.
    """
    non_optional_settings = {}
    for language in bears:
        for bear in bears[language]:
            if bear not in non_optional_settings:
                needed = bear.get_non_optional_settings()
                for bear_dep in bear.BEAR_DEPS:
                    needed.update(bear_dep.get_non_optional_settings())
                non_optional_settings[bear] = needed
    return non_optional_settings


def print_db(text, debug):
    """Print text if debug is True."""
    if debug:
        print(text)


@classmethod
def validate_descriptions_size(cls, descriptions, max_size):
    """
        Validate that all the clues can fit into the grid
        """
    raise NotImplementedError()


def transpose_3D(dic, data, axes=(2, 1, 0)):
    """
    Transpose pipe_3d object and dictionary
    """
    a1, a2, a3 = axes
    rdic = dict(dic)
    data = data.transpose((a1, a2, a3))
    s3 = 'FDDIMORDER' + str(int(3 - a1))
    s2 = 'FDDIMORDER' + str(int(3 - a2))
    s1 = 'FDDIMORDER' + str(int(3 - a3))
    rdic['FDDIMORDER1'] = dic[s1]
    rdic['FDDIMORDER2'] = dic[s2]
    rdic['FDDIMORDER3'] = dic[s3]
    rdic['FDDIMORDER'] = [rdic['FDDIMORDER1'], rdic['FDDIMORDER2'], rdic[
        'FDDIMORDER3'], rdic['FDDIMORDER4']]
    fn = 'FDF' + str(int(rdic['FDDIMORDER1']))
    if rdic[fn + 'QUADFLAG'] != 1.0:
        rdic['FDSIZE'] = data.shape[2] / 2.0
    else:
        rdic['FDSIZE'] = data.shape[2]
    rdic['FDSLICECOUNT'] = data.shape[1]
    rdic['FDSPECNUM'] = rdic['FDSLICECOUNT']
    return rdic, data


def boolean_flag(name, configurable, set_help='', unset_help=''):
    """Helper for building basic --trait, --no-trait flags.

    Parameters
    ----------

    name : str
        The name of the flag.
    configurable : str
        The 'Class.trait' string of the trait to be set/unset with the flag
    set_help : unicode
        help string for --name flag
    unset_help : unicode
        help string for --no-name flag

    Returns
    -------

    cfg : dict
        A dict with two keys: 'name', and 'no-name', for setting and unsetting
        the trait, respectively.
    """
    set_help = set_help or 'set %s=True' % configurable
    unset_help = unset_help or 'set %s=False' % configurable
    cls, trait = configurable.split('.')
    setter = {cls: {trait: True}}
    unsetter = {cls: {trait: False}}
    return {name: (setter, set_help), ('no-' + name): (unsetter, unset_help)}


def _filter_for_numa_threads(possible, wantthreads):
    """Filter topologies which closest match to NUMA threads.

    Determine which topologies provide the closest match to the number
    of threads desired by the NUMA topology of the instance.

    The possible topologies may not have any entries which match the
    desired thread count. This method will find the topologies which
    have the closest matching count. For example, if 'wantthreads' is 4
    and the possible topologies has entries with 6, 3, 2 or 1 threads,
    the topologies which have 3 threads will be identified as the
    closest match not greater than 4 and will be returned.

    :param possible: list of objects.VirtCPUTopology instances
    :param wantthreads: desired number of threads

    :returns: list of objects.VirtCPUTopology instances
    """
    mostthreads = 0
    for topology in possible:
        if topology.threads > wantthreads:
            continue
        if topology.threads > mostthreads:
            mostthreads = topology.threads
    bestthreads = []
    for topology in possible:
        if topology.threads != mostthreads:
            continue
        bestthreads.append(topology)
    return bestthreads


def kpss(data, column):
    """
    This functions applies Kwiatkowski-Phillips-Schmidt-Shin (KPSS) Test
    H0:data is not stationary
    HA:data is stationary

    Parameters:
    data: raw data
    column: timeseries data

    Output:
    Prints out if the data is stationary

    """
    from pandas import Series
    from statsmodels.tsa.stattools import kpss
    result = kpss(data[column])
    if result[0] >= result[3]['1%']:
        print('Significant @ 1%')
        print('p-value: %f' % result[1])
        print('data is NOT stationary!')
    elif result[0] >= result[3]['1%']:
        print('Significant @ 5%')
        print('p-value: %f' % result[1])
        print('data is NOT stationary!')
    elif result[0] >= result[3]['1%']:
        print('Significant @ 10%')
        print('p-value: %f' % result[1])
        print('data is NOT stationary!')
    else:
        print('data is stationary!')
        print('p-value: %f' % result[1])
    return result


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

    The ".dev0" means dirty.

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


def _trim(_vector):
    """Return _vector with all trailing zeros removed."""
    if not _vector or len(_vector) == 1:
        return _vector
    ind = len(_vector)
    while _vector[ind - 1] == 0 and ind > 0:
        ind -= 1
    return _vector[:ind]