def _check_dtype(Q):
    """ Change type if necessary to float32

    Due to an unresolved issue with swig and numpy, I have to convert the type.

    Parameters
    ----------
    Q : list of nympy.ndarrays of float
        A list with the possible joint positions for every trajectory point
        along a path.

    Returns
    -------
    list of nympy.ndarrays of float32
    """
    if Q[0].dtype != 'float32':
        print('converting type of Q')
        for i in range(len(Q)):
            Q[i] = Q[i].astype('float32')
    return Q


@staticmethod
def __calltipDisplayable(calltip):
    """True if calltip is displayable"""
    if calltip is None:
        return False
    if calltip.strip() == '':
        return False
    return True


def unique_color_from_identifier(identifier):
    """Return unique color as RGB tuple.

    Useful for creating PNG images where each color is used as an identifier.

    Raises TypeError if the identifier is not an integer.

    Raises ValueError if the identifier is not in the range 0 to 16777215
    inclusive.

    :param identifier: positive integer in range from 0 to 16777215 inclusive
    :raises: TypeError, ValueError
    :returns: RGB tuple
    """
    if not isinstance(identifier, int):
        raise TypeError('Identifier is not an integer {}'.format(identifier))
    if identifier < 0:
        raise ValueError('Negative identifier not allowed')
    if identifier >= 256 * 256 * 256:
        raise ValueError('Identifier {} >= {}'.format(identifier, 256 * 256 *
            256))
    blue = identifier % 256
    green = identifier // 256 % 256
    red = identifier // (256 * 256) % 256
    return red, green, blue


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

        :param OrganizationName val:
        :rtype: FederationStatusChangeAdditionalInfo
        """
    return cls('organization_name', val)


@classmethod
def load_from_options(cls, **kwargs):
    """Create a plugin from the arguments retrieved from get_options.

        A client can override this function to do argument validation or to
        handle differences between the registered options and what is required
        to create the plugin.
        """
    return cls(**kwargs)


def parse_species(species_data):
    """Iterate over list of species at each site."""
    parsed_species_data = []
    quality_list = []
    for species in species_data:
        if species['@AirQualityBand'] != 'No data':
            species_dict = {}
            species_dict['description'] = species['@SpeciesDescription']
            species_dict['code'] = species['@SpeciesCode']
            species_dict['quality'] = species['@AirQualityBand']
            species_dict['index'] = species['@AirQualityIndex']
            species_dict['summary'] = species_dict['code'
                ] + ' is ' + species_dict['quality']
            parsed_species_data.append(species_dict)
            quality_list.append(species_dict['quality'])
    return parsed_species_data, quality_list


def select_residues(fhandle, residue_range):
    """Outputs residues within a certain numbering range.
    """
    prev_res = None
    records = 'ATOM', 'HETATM', 'TER', 'ANISOU'
    for line in fhandle:
        if line.startswith(records):
            res_id = line[21:26]
            if res_id != prev_res:
                prev_res = res_id
            if int(line[22:26]) not in residue_range:
                continue
        yield line


@classmethod
def _verify(cls, public, signature, data):
    """ Verifies an author's signature against bites. Errors out if
        unsuccessful. Returns True if successful.

        Data must be bytes-like. public_key should be a dictionary
        formatted with all necessary components for a public key (?).
        Signature must be bytes-like.
        """
    cls._typecheck_2ndparty(public)
    return True


@staticmethod
def equals_match_case(string1, string2):
    """
        Compares 2 given strings for equality.

        :param string1: String to be compared for equality.
        :param string2: String to be compared for equality.

        :return: True, if matching, False otherwise
        :rtype: bool
        """
    return string1 == string2


def enable_cache():
    """
    Allow caching of registered variables that explicitly have
    caching enabled.

    """
    global _CACHING
    _CACHING = True


def file_linear_byte_offset(image_size, bytes_per_voxel, start_coords):
    """
    Return the file byte offset corresponding to the given coordinates.
    Files generally assumed to have the first dimension most rapidly changing

    Assumes you have a stream of bytes representing a multi-dimensional image,
    """
    offset = 0
    offset_multiple = bytes_per_voxel
    for coord, image_length in zip(start_coords, image_size):
        offset += coord * offset_multiple
        offset_multiple *= image_length
    return offset


def print_meta(ds, ds_path=None):
    """Prints meta data for subjects in given dataset."""
    print('\n#' + ds_path)
    for sub, cls in ds.classes.items():
        print('{},{}'.format(sub, cls))
    return


def x_inbetween_range(x, rng):
    """
    Determining if the input is inbetween a range.
    :param x:
    :param rng:
    :return:
    """
    start_rng = min(list(rng))
    stop_rng = max(list(rng))
    return x >= start_rng and x <= stop_rng


def dist(ctx):
    """makes a tarball for redistributing the sources"""
    pass


def fix_url(url):
    """Prefix a schema-less URL with http://."""
    if '://' not in url:
        url = 'http://' + url
    return url


def nested_dict(key, value):
    """Create a nested dict if the key is a list of keywords"""
    if isinstance(key, list):
        d = {}
        ref = d
        for key_value in key:
            if key_value == key[-1]:
                d[key_value] = value
            else:
                d[key_value] = {}
                d = d[key_value]
    else:
        ref = {key: value}
    return ref


@staticmethod
def _cleanup_phone_number(value):
    """
        remove unneeded characters from phone numbers
        :param value: phone number
        :return: clean phone number
        """
    for rep in '()-\xa0 ':
        value = value.replace(rep, '')
    return value


def to_jpeg_bytes(arr, quality=100):
    """Given a numpy array image `arr`, return the image encoded as a
  jpeg buffer."""
    import io
    import imageio
    buf = io.BytesIO()
    imageio.imwrite(buf, arr, 'jpg', quality=quality)
    return buf.getvalue()


def convert_to_raw(string, exceptions=''):
    """
    Converts a string to its raw form, converting all backslash to double
    backslash except when the backslash escapes a character given in
    exceptions.

    :param string:     The given string that needs to be converted
    :param exceptions: A list of characters that if escaped with backslash
                       should not be converted to double backslash.
    :return:           Returns the corresponding raw string.
    """
    i = 0
    length = len(string)
    output = ''
    while i < length:
        if string[i] == '\\' and i + 1 < length and string[i + 1
            ] not in exceptions:
            output += '\\'
            if string[i + 1] == '\\':
                i += 1
        output += string[i]
        i += 1
    return output


def add_cubic_gather_for_mode(m, Fr, Ft, Fz, exptheta_m, Fr_grid, Ft_grid,
    Fz_grid, ir_lowest, iz_lowest, Sr_arr, Sz_arr, Nr, Nz):
    """
    Add the contribution of the gathered field from azimuthal mode `m` to the
    fields felt by one macroparticle (`Fr`, `Ft`, `Fz`), using cubic weights.

    Parameters:
    -----------
    m: int
        The index of the azimuthal mode that is added.

    Fr, Ft, Fz: floats
        The fields felt by one macroparticle, which represent either E or B
        (before the contribution of mode `m` has been added)

    exptheta_m: complex
        The complex azimuthal factor $e^{-i m 	heta}$ where $	heta$ is
        the azimuthal position of the macroparticle considered.

    Fr_grid, Ft_grid, Fz_grid: 2darrays of complexs
        The fields on the interpolation grid for mode `m`

    ir_lowest, iz_lowest: ints
        The lowest indices in r and z from which the macroparticle
        considered should gather the fields (in the arrays F*_grid)
        These indices can in fact be negative and out-of-bound
        (e.g. for particles close to the axis) but get corrected within
        this function.

    Sr_arr, Sz_arr: 1darrays containing 4 floats
        The weights in r and z with which the macroparticle
        considered should gather the fields (in the arrays F*_grid)

    Nr, Nz: ints
        Dimensions of the field arrays.

    Returns:
    --------
    Fr, Ft, Fz: floats
        The fields felt by one macroparticle, which represent either E or B
        (after the contribution of mode `m` has been added)
    """
    Fr_m = 0.0j
    Ft_m = 0.0j
    Fz_m = 0.0j
    for index_r in range(4):
        ir = ir_lowest + index_r
        Sr_long = Sr_arr[index_r]
        Sr_perp = Sr_long
        if ir < 0:
            Sr_long *= (-1) ** m
            Sr_perp *= -(-1) ** m
        if ir < 0:
            ir = abs(ir) - 1
        elif ir > Nr - 1:
            ir = Nr - 1
        for index_z in range(4):
            iz = iz_lowest + index_z
            Sz = Sz_arr[index_z]
            if iz < 0:
                iz += Nz
            elif iz > Nz - 1:
                iz -= Nz
            Fr_m += Sz * Sr_perp * Fr_grid[iz, ir]
            Ft_m += Sz * Sr_perp * Ft_grid[iz, ir]
            Fz_m += Sz * Sr_long * Fz_grid[iz, ir]
    if m == 0:
        factor = 1.0
    else:
        factor = 2.0
    Fr += factor * (Fr_m * exptheta_m).real
    Ft += factor * (Ft_m * exptheta_m).real
    Fz += factor * (Fz_m * exptheta_m).real
    return Fr, Ft, Fz


def cmd_rest(args):
    """Restart incomplete transfer.
        """


def extrude_move(GPENCIL_OT_extrude=None, TRANSFORM_OT_translate=None):
    """Extrude selected points and move them

    :param GPENCIL_OT_extrude: Extrude Stroke Points, Extrude the selected Grease Pencil points
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def geoIsClockWise(loc1, loc2, loc3):
    """
	Determine if three locs are clockwised

	Parameters
	----------
	loc1: list
		First location, in [lat, lon] format
	loc2: list
		Second location, in [lat, lon] format
	loc3: list
		Third location, in [lat, lon] format

	Return
	------
	boolean
		True if three given locs are clockwised, false if three given locs are collinear or counter-clockwised

	"""
    [x1, y1] = [loc1[0], loc1[1]]
    [x2, y2] = [loc2[0], loc2[1]]
    [x3, y3] = [loc3[0], loc3[1]]
    val = x2 * y3 + x3 * y1 + x1 * y2 - (x2 * y1 + x3 * y2 + x1 * y3)
    if val >= 0:
        clockWise = True
    else:
        clockWise = False
    return clockWise


@classmethod
def create(cls, server, title, items=None, section=None, limit=None, smart=
    False, **kwargs):
    """Create a playlist.

        Parameters:
            server (:class:`~plexapi.server.PlexServer`): Server your connected to.
            title (str): Title of the playlist.
            items (Iterable): Iterable of objects that should be in the playlist.
            section (:class:`~plexapi.library.LibrarySection`, str):
            limit (int): default None.
            smart (bool): default False.

            **kwargs (dict): is passed to the filters. For a example see the search method.

        Returns:
            :class:`plexapi.playlist.Playlist`: an instance of created Playlist.
        """
    if smart:
        return cls._createSmart(server, title, section, limit, **kwargs)
    else:
        return cls._create(server, title, items)


@classmethod
def dims(cls, value):
    """Produce iterable of all dimensions"""
    for base in cls.types(value):
        length = getattr(base, '_length_', None)
        if length is not None:
            yield length


@staticmethod
def is_mention(cell_val):
    """
        Nonnegative values in grid cells are reserved for mention ids
        """
    return cell_val >= 0


def _alpha(n, threshold=30, scale=2000):
    """
    Calculate a rough guess for the best alpha value for a default scatterplot.

    This is calculated with the equation

    .. math::
        \\alpha = \\frac{0.99}{1 + \\frac{n}{\\text{scale}}}

    This is done so that is ranges from nearly 1 for small values of n to 0.01
    for very large datasets. Note that very large datasets should probably use
    a contour plot, but this is avaiable.

    :param n: Length of the dataset that will be plotted in the scatterplot.
    :type n: int
    :param threshold: For the size of the dataset below this, the points will
                      be 100% opaque.
    :param scale: Parameter in the function that determines the alpha value.
                  Defaults to 2000. The larger the value, the more opaque
                  points will be for a given n.
    :type scale: float
    :return: Guess at an alpha value for a scatterplot.
    :rtype: float

    """
    if n < threshold:
        return 1.0
    return 0.99 / (1.0 + n / float(scale))


@staticmethod
def vertex_count(pos=None, **kwargs):
    """Take the output of validate() as input."""
    return sum(map(len, kwargs['text'])) * 6


def fit(model, training, optimizer, loss_func, n_epochs):
    """trains a network when given features (x) and labels (y).
   """
    for e in range(n_epochs):
        for x, y in training:
            optimizer.zero_grad()
            loss = loss_func(model(x), y)
            loss.backward()
            optimizer.step()
    print('Finished Training')


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


@classmethod
def maptag(cls, tag, fn):
    """
        Map (override) tag => I{class} mapping.

        @param tag: An XSD tag name.
        @type tag: str
        @param fn: A function or class.
        @type fn: fn|class.

        """
    cls.tags[tag] = fn


def ruler():
    """Interactive ruler

    """
    pass


def clearTag(tag):
    """ #TODO: docstring
    eg "{http://psi.hupo.org/ms/mzml}mzML" returns "mzML"

    :param tag: #TODO docstring
    :returns:
    """
    return tag.split('}')[-1]


def authorizations(auth_url, **scopes) ->dict:
    """
    Return all security definitions.
    Contains only one OAuth2 implicit flow definition.

    :param auth_url: Authorization URL.
    :param scopes: All scopes that should be available (scope_name = 'description as a string').
    """
    return {'oauth2': {'scopes': scopes, 'flow': 'implicit',
        'authorizationUrl': auth_url, 'type': 'oauth2'}}


def generateParing(xi, yi):
    """Cantor pairing function"""
    if xi < yi:
        x = yi
        y = xi
    else:
        x = xi
        y = yi
    if x >= y:
        return x * x + x + y
    else:
        return y * y + x


@staticmethod
def strip_comment(line):
    """Remove comments from source line"""
    i = line.rfind('#')
    if i >= 0:
        line = line[:i].strip()
    return line


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

        :param ShowcaseViewDetails val:
        :rtype: EventDetails
        """
    return cls('showcase_view_details', val)


def binary_column_as_state_type(db_column_data):
    """
        Turn *db_column_data* into something that's a valid pickle
        state.

        Valid pickle states should be acceptable to
        `io.BytesIO` and `pickle.UnPickler`.

        *db_column_dat* came from a column of data declared to be of the
        type that we store state information in (e.g., a BLOB on MySQL
        or Oracle).
        """


def get_url(config):
    """Retrieves the url from configuration, else uses the default cloco url"""
    url = config['settings']['url']
    if not url:
        url = 'https://api.cloco.io'
    return url


def setPyFlakesFilter(func):
    """
	Set a filter for PyFlake warning messages. This filter should be a function
	that takes a single message, and returns False if the message should be
	ignored (True otherwise.)

	Argument:
	func	--	The filter function.
	"""
    global _filter
    _filter = func


def _is_section_key(key):
    """Is a Config key a section name (does it start with a capital)?"""
    if key and key[0].upper() == key[0] and not key.startswith('_'):
        return True
    else:
        return False


def select_linked():
    """Select all control points linked to active one

    """
    pass


def precision(y_true, y_pred):
    """Precision metric.

    Only computes a batch-wise average of precision.

    Computes the precision, a metric for multi-label classification of
    how many selected items are relevant.
    """
    import keras.backend as K
    true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))
    predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))
    precision = true_positives / (predicted_positives + K.epsilon())
    return precision


def commitctx(ctx, error=False, origctx=None):
    """Commit a commitctx instance to the repository."""


def remove_numbers(doc: str) ->str:
    """Removes digit/number characters from a string.

    Parameters
    ----------
    doc: str
        A document given as a single string.

    Returns
    -------
    str
        The document as a single string with all number/digit characters
        removed.

    """
    removed = filter(lambda character: not character.isdigit(), str(doc))
    return ''.join(removed)


def has_resource(resource_name):
    """Does the package contain the named resource?"""


def understands_Unset(cls_or_func):
    """
    Decorator for marking validators as supporting the special Unset value.

    This decorator should be applied to every validator that natively supports
    Unset values. Without it, Unset is never validated.

    This decorator works by setting the ``understands_Unset`` attribute on the
    decorated object and returning it intact.
    """
    cls_or_func.understands_Unset = True
    return cls_or_func


def localize_datetime(dt, tz):
    """
    Localize a timezone naive datetime. Handles pytz timezones correctly.

    """
    try:
        return tz.localize(dt)
    except AttributeError:
        return dt.replace(tzinfo=tz)


def configset(config, section, var, value, overwrite=False):
    """
    Sets a string in the in memory representation of the config object
    Deos NOT overwrite existing values if overwrite is set to False (default)

    Input:
        - config - python ConfigParser object
        - section - section in the file
        - var - variable (key) to set
        - value - the value to set
        - overwrite (optional, default is False)

    Returns:
        - nothing

    """
    if not config.has_section(section):
        config.add_section(section)
        config.set(section, var, value)
    elif not config.has_option(section, var):
        config.set(section, var, value)
    elif overwrite:
        config.set(section, var, value)


def _time_independent_equals(a, b):
    """
    This compares two values in constant time.

    Taken from tornado:

    https://github.com/tornadoweb/tornado/blob/
    d4eb8eb4eb5cc9a6677e9116ef84ded8efba8859/tornado/web.py#L3060

    """
    if len(a) != len(b):
        return False
    result = 0
    if isinstance(a[0], int):
        for x, y in zip(a, b):
            result |= x ^ y
    else:
        for x, y in zip(a, b):
            result |= ord(x) ^ ord(y)
    return result == 0


def binomial(n, k):
    """
    Calculate C(n,k), the number of ways can k be chosen from n. Example:

    >>>binomial(30,12)
    86493225
    """
    nt = 1
    for t in range(min(k, n - k)):
        nt = nt * (n - t) // (t + 1)
    return nt


@classmethod
def configurable_base(cls):
    """Returns the base class of a configurable hierarchy.

        This will normally return the class in which it is defined.
        (which is *not* necessarily the same as the ``cls`` classmethod
        parameter).

        """
    raise NotImplementedError()


def tracking_object_new():
    """Add new object for tracking

    """
    pass


def add(x, y):
    """
    Add two integers.
    :param x: first integer
    :param y: second integer
    :return: result of the addition
    """
    return x + y


def Ztoelname(Z):
    """
  Returns element name of element with nuclear charge Z.

  Parameters
  ----------

  Z :  int
    nuclear charge of element (e.g. 6 for carbon)

  Returns
  -------
  str
    element name (e.g. "Carbon" for carbon)
  """
    elname = ('Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron',
        'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium',
        'Magnesium', 'Aluminum', 'Silicon', 'Phosphorus', 'Sulfur',
        'Chlorine', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titanium',
        'Vanadium', 'Chromium', 'Manganese', 'Iron', 'Cobalt', 'Nickel',
        'Copper', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'Selenium',
        'Bromine', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium',
        'Zirconium', 'Niobium', 'Molybdenum', 'Technetium', 'Ruthenium',
        'Rhodium', 'Palladium', 'Silver', 'Cadmium', 'Indium', 'Tin',
        'Antimony', 'Tellurium', 'Iodine', 'Xenon', 'Cesium', 'Barium',
        'Lanthanum', 'Cerium', 'Praseodymium', 'Neodymium', 'Promethium',
        'Samarium', 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium',
        'Holmium', 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium',
        'Tantalum', 'Tungsten', 'Rhenium', 'Osmium', 'Iridium', 'Platinum',
        'Gold', 'Mercury', 'Thallium', 'Lead', 'Bismuth', 'Polonium',
        'Astatine', 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium',
        'Protactinium', 'Uranium')
    if Z < 1:
        print('Z must be between 1 and 92. You have given Z= ' + repr(Z))
        ret = -1
    elif Z > 92:
        print('Z must be between 1 and 92. You have given Z= ' + repr(Z))
        ret = -1
    else:
        ret = elname[Z - 1]
    return ret


def delete_node_by_xpath(mapping, xpath, ignore_errors=False):
    """Delete the node pointed to by xpath from mapping.

    Args:
        mapping: nested dictionary.
        xpath: string-like selector.
        ignore_errors: if True, pass silently if the node doesn't exist,
            otherwise, raise an exception.

    Example:

    >>> tree = {'level1': {'level2': {'level3': 'bottom'}}}
    >>> delete_node_by_xpath(tree, 'level1.level2')
    >>> tree
    {'level1': {}}

    """
    segments = xpath.split('.')
    attrname = segments.pop()
    for segment in segments:
        if segment not in mapping:
            if ignore_errors:
                return
            raise KeyError(
                "Invalid '{}' selector: '{}' doesn't match anything.".
                format(xpath, segment))
        mapping = mapping[segment]
    return mapping.pop(attrname, None)


@classmethod
def from_vhost(cls, vhost):
    """Retrieve webbacc id associated to a webacc vhost"""
    result = cls.list({'items_per_page': 500})
    webaccs = {}
    for webacc in result:
        for vhost in webacc['vhosts']:
            webaccs[vhost['name']] = webacc['id']
    return webaccs.get(vhost)


def _octant_gt(octant, y, coord):
    """Return whether y is further along the circle than coord."""
    if octant % 2 == 1:
        return y < coord
    else:
        return y > coord


def remove_ip_routes(DirectoryId=None, CidrIps=None):
    """
    Removes IP address blocks from a directory.
    See also: AWS API Documentation

    :example: response = client.remove_ip_routes(
        DirectoryId='string',
        CidrIps=[
            'string',
        ]
    )

    :type DirectoryId: string
    :param DirectoryId: [REQUIRED]
            Identifier (ID) of the directory from which you want to remove the IP addresses.

    :type CidrIps: list
    :param CidrIps: [REQUIRED]
            IP address blocks that you want to remove.
            (string) --

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def imports_on_separate_lines(logical_line):
    """Place imports on separate lines.

    Okay: import os\\nimport sys
    E401: import sys, os

    Okay: from subprocess import Popen, PIPE
    Okay: from myclas import MyClass
    Okay: from foo.bar.yourclass import YourClass
    Okay: import myclass
    Okay: import foo.bar.yourclass
    """
    line = logical_line
    if line.startswith('import '):
        found = line.find(',')
        if -1 < found and ';' not in line[:found]:
            yield found, 'E401 multiple imports on one line'


def as_channel(value):
    """Always return a channel name:

    .. code-block:: python

        >>> print(as_channel('chan'))
        #chan
        >>> print(as_channel('#chan'))
        #chan
        >>> print(as_channel('&chan'))
        &chan
    """
    if not value.startswith(('#', '&')):
        return '#' + value
    return value


def iterate_task_executions(client, node_execution_identifier, limit=None,
    filters=None):
    """
    This returns a generator for task executions, given a node execution identifier
    :param flytekit.clients.friendly.SynchronousFlyteClient client:
    :param flytekit.models.core.identifier.NodeExecutionIdentifier node_execution_identifier:
    :param int limit: The maximum number of elements to retrieve
    :param list[flytekit.models.filters.Filter] filters:
    :rtype: Iterator[flytekit.models.admin.task_execution.TaskExecution]
    """
    token = ''
    num_to_fetch = 100
    if limit is not None and limit < num_to_fetch:
        num_to_fetch = limit
    counter = 0
    while True:
        task_execs, next_token = client.list_task_executions_paginated(
            node_execution_identifier=node_execution_identifier, limit=
            num_to_fetch, token=token, filters=filters)
        for t in task_execs:
            counter += 1
            if limit is not None and counter > limit:
                return
            yield t
        if not next_token:
            break
        token = next_token


def modify_fk_constraint(apps, schema_editor):
    """
    Delete's the current foreign key contraint on the outbound field, and adds
    it again, but this time with an ON DELETE clause
    """
    model = apps.get_model('message_sender', 'OutboundSendFailure')
    table = model._meta.db_table
    with schema_editor.connection.cursor() as cursor:
        constraints = schema_editor.connection.introspection.get_constraints(
            cursor, table)
        [constraint] = filter(lambda c: c[1]['foreign_key'], constraints.
            items())
        [name, _] = constraint
    sql_delete_fk = (
        'SET CONSTRAINTS {name} IMMEDIATE; ALTER TABLE {table} DROP CONSTRAINT {name}'
        .format(table=schema_editor.quote_name(table), name=schema_editor.
        quote_name(name)))
    schema_editor.execute(sql_delete_fk)
    field = model.outbound.field
    to_table = field.remote_field.model._meta.db_table
    to_column = field.remote_field.model._meta.get_field(field.remote_field
        .field_name).column
    sql_create_fk = (
        'ALTER TABLE {table} ADD CONSTRAINT {name} FOREIGN KEY ({column}) REFERENCES {to_table} ({to_column}) ON DELETE CASCADE {deferrable};'
        .format(table=schema_editor.quote_name(table), name=schema_editor.
        quote_name(name), column=schema_editor.quote_name(field.column),
        to_table=schema_editor.quote_name(to_table), to_column=
        schema_editor.quote_name(to_column), deferrable=schema_editor.
        connection.ops.deferrable_sql()))
    schema_editor.execute(sql_create_fk)


def obj_make_list(context, list_obj, item_cls, db_list, **extra_args):
    """Construct an object list from a list of primitives.

    This calls item_cls._from_db_object() on each item of db_list, and
    adds the resulting object to list_obj.

    :param:context: Request context
    :param:list_obj: An ObjectListBase object
    :param:item_cls: The MasakariObject class of the objects within the list
    :param:db_list: The list of primitives to convert to objects
    :param:extra_args: Extra arguments to pass to _from_db_object()
    :returns: list_obj
    """
    list_obj.objects = []
    for db_item in db_list:
        item = item_cls._from_db_object(context, item_cls(), db_item, **
            extra_args)
        list_obj.objects.append(item)
    list_obj._context = context
    list_obj.obj_reset_changes()
    return list_obj


def run():
    """
    Main entry point for the program
    :return:
    """
    ...


def test_adaptator(config, adaptator, ntuple, verbose=False):
    """
    Run tests on the adaptator

    params: config
    params: adaptator
    """
    try:
        if adaptator not in config.keys():
            if verbose:
                print("error: extract_barcode(), config doesn't contain " +
                    str(adaptator) + ' adaptator.')
            raise KeyError
        if 'coords' not in config[adaptator].keys():
            if verbose:
                print('error: extract_barcode(), ' + str(adaptator) +
                    ' has no coords')
            raise KeyError
        if 'reads' not in config[adaptator]['coords'].keys():
            if verbose:
                print('error: extract_barcode(), ' + str(adaptator) +
                    ' has no reads')
            raise KeyError
        if 'start' not in config[adaptator]['coords'].keys():
            if verbose:
                print('error: extract_barcode(), ' + str(adaptator) +
                    ' has no start')
            raise KeyError
        if 'stop' not in config[adaptator]['coords'].keys():
            if verbose:
                print('error: extract_barcode(), ' + str(adaptator) +
                    ' has no stop')
            raise KeyError
        if not ntuple == config[adaptator]['coords']['reads']:
            if verbose:
                print('error: extract_barcode(), ' + str(adaptator) +
                    ' not present for reads ' + str(ntuple))
            raise ValueError
    except KeyError:
        if verbose:
            print('error: test_adaptator() ')
        raise KeyError
    except ValueError:
        if verbose:
            print('error: test_adaptator() ')
        raise ValueError


def set_measure_level(mlvl):
    """
    Set the current 'measure level' used in deciding how much effort to expend
    creating FFTW plans.  Must be an integer from 0 (least effort, shortest time)
    to 3 (most effort and time).
    """
    global _default_measurelvl
    if mlvl not in (0, 1, 2, 3):
        raise ValueError('Measure level can only be one of 0, 1, 2, or 3')
    _default_measurelvl = mlvl


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


def __int_to_hex(num: int):
    """
    Converts integer to hex. Automatically rounds of the float
    :param num: Integer to be converted
    :return: Hex string
    """
    return '%02x' % int(num)


def _get_slot_name_from_key(key):
    """Get slot name from kv store key."""
    return key.split('-')[-2]


def KCl(mw_atmos, mh=1):
    """Defines properties for KCl as condensible"""
    gas_mw = 74.5
    if mh == 1:
        gas_mmr = 2.2627e-07 * (gas_mw / mw_atmos)
    elif mh == 10:
        gas_mmr = 2.1829e-06 * (gas_mw / mw_atmos)
    elif mh == 50:
        gas_mmr = 8.1164e-06 * (gas_mw / mw_atmos)
    else:
        raise Exception(
            'KCl gas properties can only be computed for 1, 10 and 50x Solar Meallicity'
            )
    rho_p = 1.99
    return gas_mw, gas_mmr, rho_p


def _configSpecial_OrthoOpts_zcentre(target, parser, shortArg, longArg,
    helpText):
    """Configures the ``zcentre`` option for the ``OrthoOpts`` class. """
    parser.add_argument(shortArg, longArg, metavar=('X', 'Y'), type=float,
        nargs=2, help=helpText)


def _get_marker_param(request):
    """Extract marker id from request or fail."""
    return request.GET['marker']


def N(n):
    """
	N: Standard core of PyPLaSM
	repetition operator. Returns the sequence with n repetitions of arg
	(n::isintpos)(arg::tt) -> (isseq)
	"""
    return lambda List: [List] * int(n)


def select_pattern(pattern: str='*', case_sensitive: bool=False, extend:
    bool=True):
    """Select objects matching a naming pattern

    :param pattern: Pattern, Name filter using ‘*’, ‘?’ and ‘[abc]’ unix style wildcards
    :type pattern: str
    :param case_sensitive: Case Sensitive, Do a case sensitive compare
    :type case_sensitive: bool
    :param extend: Extend, Extend the existing selection
    :type extend: bool
    """
    pass


def first_continuous_indexes_slice(ol, value):
    """
        from elist.elist import *
        ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
        first_continuous_indexes_slice(ol,"a")
    """
    length = ol.__len__()
    begin = None
    slice = []
    for i in range(0, length):
        if ol[i] == value:
            begin = i
            break
        else:
            pass
    if begin == None:
        return None
    else:
        slice.append(begin)
        for i in range(begin + 1, length):
            if ol[i] == value:
                slice.append(i)
            else:
                break
    return slice


def __acquire_set(nodes):
    """
    Acquires the set of nodes.
    :param nodes: roots
    :return: descendants
    """
    descendants = []
    for node in nodes:
        descendants.extend(node.list_descendants())
    return descendants


def terminate_environment(EnvironmentId=None, EnvironmentName=None,
    TerminateResources=None, ForceTerminate=None):
    """
    Terminates the specified environment.
    See also: AWS API Documentation

    Examples
    The following operation terminates an Elastic Beanstalk environment named my-env:
    Expected Output:

    :example: response = client.terminate_environment(
        EnvironmentId='string',
        EnvironmentName='string',
        TerminateResources=True|False,
        ForceTerminate=True|False
    )

    :type EnvironmentId: string
    :param EnvironmentId: The ID of the environment to terminate.
            Condition: You must specify either this or an EnvironmentName, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type EnvironmentName: string
    :param EnvironmentName: The name of the environment to terminate.
            Condition: You must specify either this or an EnvironmentId, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type TerminateResources: boolean
    :param TerminateResources: Indicates whether the associated AWS resources should shut down when the environment is terminated:
            true : The specified environment as well as the associated AWS resources, such as Auto Scaling group and LoadBalancer, are terminated.
            false : AWS Elastic Beanstalk resource management is removed from the environment, but the AWS resources continue to operate.
            For more information, see the AWS Elastic Beanstalk User Guide.
            Default: true
            Valid Values: true | false

    :type ForceTerminate: boolean
    :param ForceTerminate: Terminates the target environment even if another environment in the same group is dependent on it.

    :rtype: dict
    :return: {
        'EnvironmentName': 'string',
        'EnvironmentId': 'string',
        'ApplicationName': 'string',
        'VersionLabel': 'string',
        'SolutionStackName': 'string',
        'PlatformArn': 'string',
        'TemplateName': 'string',
        'Description': 'string',
        'EndpointURL': 'string',
        'CNAME': 'string',
        'DateCreated': datetime(2015, 1, 1),
        'DateUpdated': datetime(2015, 1, 1),
        'Status': 'Launching'|'Updating'|'Ready'|'Terminating'|'Terminated',
        'AbortableOperationInProgress': True|False,
        'Health': 'Green'|'Yellow'|'Red'|'Grey',
        'HealthStatus': 'NoData'|'Unknown'|'Pending'|'Ok'|'Info'|'Warning'|'Degraded'|'Severe',
        'Resources': {
            'LoadBalancer': {
                'LoadBalancerName': 'string',
                'Domain': 'string',
                'Listeners': [
                    {
                        'Protocol': 'string',
                        'Port': 123
                    },
                ]
            }
        },
        'Tier': {
            'Name': 'string',
            'Type': 'string',
            'Version': 'string'
        },
        'EnvironmentLinks': [
            {
                'LinkName': 'string',
                'EnvironmentName': 'string'
            },
        ]
    }

    :returns:
    Launching : Environment is in the process of initial deployment.
    Updating : Environment is in the process of updating its configuration settings or application version.
    Ready : Environment is available to have an action performed on it, such as update or terminate.
    Terminating : Environment is in the shut-down process.
    Terminated : Environment is not running.

    """
    pass


def is_naive(value):
    """
    Determines if a given datetime.datetime is naive.

    The logic is described in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    """
    return value.tzinfo is None or value.tzinfo.utcoffset(value) is None


def ckConditionOne(eojul, condition):
    """for 문이 없이 단지 현재 어절에 해당 조건이 있는지를 검사한다"""
    found = 'FALSE'
    if condition == '이/가/은/는':
        if eojul == '이' or eojul == '가' or eojul == '은' or eojul == '는':
            found = 'TRUE'
    elif condition == '이/가':
        if eojul == '이' or eojul == '가':
            found = 'TRUE'
    elif condition == '은/는':
        if eojul == '은' or eojul == '는':
            found = 'TRUE'
    elif condition == '을/를':
        if eojul == '을' or eojul == '를':
            found = 'TRUE'
    elif condition == '에/에게':
        if eojul == '에' or eojul == '게':
            found = 'TRUE'
    elif condition == '와/과/및':
        if eojul == '와' or eojul == '과' or eojul == '및':
            found = 'TRUE'
    elif condition == '와/과':
        if eojul == '와' or eojul == '과':
            found = 'TRUE'
    elif condition.startswith('NOUN'):
        if eojul.startswith('NOUN'):
            found = 'TRUE'
    elif condition.startswith('VERB'):
        if eojul.startswith('VERB'):
            found = 'TRUE'
    elif condition == eojul:
        found = 'TRUE'
    return found


def subdivide(G, pendant):
    """
    Given a graph with a list of pendant nodes (and their edges),
    subdivides each of the pendant edges.

    INPUT
    G: A networkx graph
    pendant: A list of the form [[vertex, edge] ...] where
    vertex is pendant and edge is the only edge incident to
    vertex

    OUTPUT
    Gh: The subdivision of G
    """
    Gh = G.copy()
    for pendantEdge in pendant:
        vertex = pendantEdge[0]
        edge = pendantEdge[1]
        Gh.remove_edge(*edge)
        Gh.add_node(str(edge))
        Gh.add_edge(edge[0], str(edge))
        Gh.add_edge(edge[1], str(edge))
    return Gh


def _bisect_right(seq, tgt, key_func, lower_search_bound=0,
    upper_search_bound=None):
    """Return the index of the last item in seq such that all e in seq[:index]
    have key_func(e) <= tgt, and all e in seq[index:] have key_func(e) > tgt.

    Thus, seq.insert(index, value) will insert value after the rightmost item
    such that meets the above condition.

    lower_search_bound and upper_search_bound bound the slice to be searched.

    Assumes that seq is already sorted.
    """
    if lower_search_bound < 0:
        raise ValueError('lower_search_bound must be non-negative')
    if upper_search_bound is None:
        upper_search_bound = len(seq)
    while lower_search_bound < upper_search_bound:
        midpoint_index = (lower_search_bound + upper_search_bound) // 2
        if tgt < key_func(seq[midpoint_index]):
            upper_search_bound = midpoint_index
        else:
            lower_search_bound = midpoint_index + 1
    return lower_search_bound


def get_libraries(document):
    """Returns the libraries for the `document`."""
    return document.BasicLibraries


def safe_issubclass(*args):
    """Like issubclass, but will just return False if not a class."""
    try:
        if issubclass(*args):
            return True
    except TypeError:
        pass
    return False


def escape_path(path):
    """
    Escapes any characters that might be problematic in shell interactions.

    :param path: The original path.
    :return: A potentially modified version of the path with all problematic characters escaped.
    """
    return path.replace('\\', '\\\\')


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


def hz2bark(frq):
    """Convert hz to bark scale.

    Parameters
    ----------
    frq : np.ndarray, float
        frequency

    Returns
    -------
    bark : np.ndarray, float
        bark value
    """
    return 26.81 * frq / (1960 + frq) - 0.51


@classmethod
def get_manifest(cls, carrier, warehouse):
    """
        Returns currently opened manifest for carrier account. if not open new.
        """
    manifests = cls.search([('state', '=', 'open'), ('carrier', '=',
        carrier), ('warehouse', '=', warehouse)])
    if manifests:
        return manifests[0]
    return cls.create([{'carrier': carrier, 'warehouse': warehouse}])[0]


def put_rule(Name=None, ScheduleExpression=None, EventPattern=None, State=
    None, Description=None, RoleArn=None):
    """
    Creates or updates the specified rule. Rules are enabled by default, or based on value of the state. You can disable a rule using  DisableRule .
    When you create or update a rule, incoming events might not immediately start matching to new or updated rules. Please allow a short period of time for changes to take effect.
    A rule must contain at least an EventPattern or ScheduleExpression. Rules with EventPatterns are triggered when a matching event is observed. Rules with ScheduleExpressions self-trigger based on the given schedule. A rule can have both an EventPattern and a ScheduleExpression, in which case the rule triggers on matching events as well as on a schedule.
    Most services in AWS treat : or / as the same character in Amazon Resource Names (ARNs). However, CloudWatch Events uses an exact match in event patterns and rules. Be sure to use the correct ARN characters when creating event patterns so that they match the ARN syntax in the event you want to match.
    See also: AWS API Documentation

    :example: response = client.put_rule(
        Name='string',
        ScheduleExpression='string',
        EventPattern='string',
        State='ENABLED'|'DISABLED',
        Description='string',
        RoleArn='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            The name of the rule that you are creating or updating.

    :type ScheduleExpression: string
    :param ScheduleExpression: The scheduling expression. For example, 'cron(0 20 * * ? *)', 'rate(5 minutes)'.

    :type EventPattern: string
    :param EventPattern: The event pattern. For more information, see Events and Event Patterns in the Amazon CloudWatch Events User Guide .

    :type State: string
    :param State: Indicates whether the rule is enabled or disabled.

    :type Description: string
    :param Description: A description of the rule.

    :type RoleArn: string
    :param RoleArn: The Amazon Resource Name (ARN) of the IAM role associated with the rule.

    :rtype: dict
    :return: {
        'RuleArn': 'string'
    }

    """
    pass


def optimize(dfonc, x_init, pas=0.001, max_iter=1000):
    """ Effectue une descente de gradient de type batch (par lot) pour
    optimiser la valeur d'une fonction.
    :param: dfonc, La fonction retournant le gradient de la fonction à
    optimiser.
    :param: x_init, La valeur initiale de la fonction à optimiser.
    :param: pas, Le pas d'apprentissage.
    :param: max_iter, Le seuil d'itération maximal.
    :return: (x_histo, f_histo, grad_histo), L'historique des valeurs
    calculées.
    """
    x = x_init
    for _ in range(max_iter):
        x = x - pas * dfonc(*x.T)
    return x


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

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


def _default_to(check, default, comparator=None):
    """ If check is None, apply default; else, return check.
    """
    if comparator is None:
        if check is None:
            return default
        else:
            return check
    elif check == comparator:
        return default
    else:
        return check


def density_over_range(lst, cpg_ranges):
    """
	Calculate CpG density over range (upstream, gene, downstream)
	lst = list of (chr,start,end, strand)
	cpg_ranges is returned by read_CpG_bed
	"""
    up_CpG_density = {}
    gene_CpG_density = {}
    down_CpG_density = {}
    for i in range(0, 101):
        up_CpG_density[i] = 0
        gene_CpG_density[i] = 0
        down_CpG_density[i] = 0
    for r1, r2, r3, strand in lst:
        if strand == '+':
            up_region = r1
            gene_region = r2
            down_region = r3
        elif strand == '-':
            up_region = r3
            gene_region = r2
            down_region = r1
        chrom = up_region[0]
        start = up_region[1]
        end = up_region[2]
        span = end - start
        if chrom not in cpg_ranges:
            continue
        tmp = cpg_ranges[chrom].find(start, end)
        for i in tmp:
            if strand == '+':
                CpG_to_origin = round((i.end - start) * 100 / span)
            elif strand == '-':
                CpG_to_origin = abs(round((i.end - end) * 100 / span))
            up_CpG_density[CpG_to_origin] += 1
        chrom = gene_region[0]
        start = gene_region[1]
        end = gene_region[2]
        span = end - start
        if chrom not in cpg_ranges:
            continue
        tmp = cpg_ranges[chrom].find(start, end)
        for i in tmp:
            if strand == '+':
                CpG_to_origin = round((i.end - start) * 100 / span)
            elif strand == '-':
                CpG_to_origin = abs(round((i.end - end) * 100 / span))
            gene_CpG_density[CpG_to_origin] += 1
        chrom = down_region[0]
        start = down_region[1]
        end = down_region[2]
        span = end - start
        if chrom not in cpg_ranges:
            continue
        tmp = cpg_ranges[chrom].find(start, end)
        for i in tmp:
            if strand == '+':
                CpG_to_origin = round((i.end - start) * 100 / span)
            elif strand == '-':
                CpG_to_origin = abs(round((i.end - end) * 100 / span))
            down_CpG_density[CpG_to_origin] += 1
    return up_CpG_density, gene_CpG_density, down_CpG_density


def replace_in_binary_file(file_path, replacements):
    """
    Replaces all instances of a pattern in a binary file with the specified replacement.
    'replacements' is a list of tuples in the form (pattern, repl) where 'pattern'
    is a pattern and 'repl' is its replacement. Regex is not supported.
    """
    file = open(file_path, 'rb')
    file_content = file.read()
    file.close()
    for replacement in replacements:
        pattern, repl = replacement
        file_content = file_content.replace(pattern, repl)
    file = open(file_path, 'wb')
    file.write(file_content)
    file.close()


@staticmethod
def is_image(value):
    """
        Tries to check if the filename provided references to an image

        Checking is based on filename extension. Currently recognized:
           gif, png, jp(e)g, bmp

        Args:
            value: filename
        """
    extension = value.split('.')[-1].lower()
    if extension in ['gif', 'png', 'jpg', 'jpeg', 'bmp']:
        return True
    return False


@staticmethod
def index_corners(x, y, cell_size):
    """x, y is the index of a cell (bottom left)"""
    x0 = x
    y0 = y
    x1 = (x + 90 + cell_size) % 180 - 90
    y1 = y0
    x2 = x1
    y2 = (y + 180 + cell_size) % 360 - 180
    x3 = x0
    y3 = y2
    return x0, y0, x1, y1, x2, y2, x3, y3


def release_data(key, state, delete=True):
    """ Remove data from temporary storage

    See Also
        finish_task
    """
    if key in state['waiting_data']:
        assert not state['waiting_data'][key]
        del state['waiting_data'][key]
    state['released'].add(key)
    if delete:
        del state['cache'][key]


def tamper(payload, **kwargs):
    """
    Embraces complete query with (MySQL) zero-versioned comment

    Requirement:
        * MySQL

    Tested against:
        * MySQL 5.0

    Notes:
        * Useful to bypass ModSecurity WAF

    >>> tamper('1 AND 2>1--')
    '1 /*!00000AND 2>1*/--'
    """
    retVal = payload
    if payload:
        postfix = ''
        for comment in ('#', '--', '/*'):
            if comment in payload:
                postfix = payload[payload.find(comment):]
                payload = payload[:payload.find(comment)]
                break
        if ' ' in payload:
            retVal = '%s /*!00000%s*/%s' % (payload[:payload.find(' ')],
                payload[payload.find(' ') + 1:], postfix)
    return retVal


@classmethod
def success(cls, value=None, message=None, **kwargs):
    """
        Provides a convenience constructor for successful Value instances.

        :param value: The value of the Value instance to be constructed.
        :param message: The message, if any.
        :param kwargs: Extra payload for the value.
        :return: A successful Value instance.
        """
    return cls(value=value, message=message, status=cls.Status.Success, **
        kwargs)


def get_instrument_list(filtdcat):
    """ Retrieve clean instrument list without any codes """
    return filtdcat[['array_name', 'site_name', 'infrastructure_name',
        'instrument_name', 'stream_method', 'stream_rd']].sort_values(by=[
        'site_name', 'infrastructure_name', 'instrument_name']
        ).drop_duplicates().reset_index(drop='index')


def invalid_node_ids_error(node_ids):
    """
    Return validation error string given when node_ids are not part of CLB

    :param ``list`` node_ids: List of int node_id
    :rtype: ``str``
    """
    nodes = ','.join(map(str, sorted(node_ids)))
    return 'Node ids {0} are not a part of your loadbalancer'.format(nodes)


def match(pattern, sentence, *args, **kwargs):
    """ Returns the first match found in the given sentence, or None.
    """
    return compile(pattern, *args, **kwargs).match(sentence)


def __enter__():
    """
        Release the underlying file descriptor so that code within the
        context manager can open a new file.
        """


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

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


def get_host_info(node_info, host):
    """
    Simple callback that takes the node info from `/_cluster/nodes` and a
    parsed connection information and return the connection information. If
    `None` is returned this node will be skipped.

    Useful for filtering nodes (by proximity for example) or if additional
    information needs to be provided for the :class:`~elasticsearch.Connection`
    class. By default master only nodes are filtered out since they shouldn't
    typically be used for API operations.

    :arg node_info: node information from `/_cluster/nodes`
    :arg host: connection information (host, port) extracted from the node info
    """
    if node_info.get('roles', []) == ['master']:
        return None
    return host


def check_column_existence(col_name, df, presence=True):
    """
    Checks whether or not `col_name` is in `df` and raises a helpful error msg
    if the desired condition is not met.

    Parameters
    ----------
    col_name : str.
        Should represent a column whose presence in `df` is to be checked.
    df : pandas DataFrame.
        The dataframe that will be checked for the presence of `col_name`.
    presence : bool, optional.
        If True, then this function checks for the PRESENCE of `col_name` from
        `df`. If False, then this function checks for the ABSENCE of
        `col_name` in `df`. Default == True.

    Returns
    -------
    None.
    """
    if presence:
        if col_name not in df.columns:
            msg = 'Ensure that `{}` is in `df.columns`.'
            raise ValueError(msg.format(col_name))
    elif col_name in df.columns:
        msg = 'Ensure that `{}` is not in `df.columns`.'
        raise ValueError(msg.format(col_name))
    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 safe_int(val, default=None):
    """
    Returns int() of val if val is not convertable to int use default
    instead

    :param val:
    :param default:
    """
    try:
        val = int(val)
    except (ValueError, TypeError):
        val = default
    return val


@classmethod
def create_with_netlinks(cls, name, netlinks, **kwargs):
    """
        Create a multilink with a list of StaticNetlinks. To properly create
        the multilink using this method, pass a list of netlinks with the
        following dict structure::

            netlinks = [{'netlink': StaticNetlink,
                         'ip_range': 1.1.1.1-1.1.1.2,
                         'netlink_role': 'active'}]

        The `netlink_role` can be either `active` or `standby`. The remaining
        settings are resolved from the StaticNetlink. The IP range value must
        be an IP range within the StaticNetlink's specified network.
        Use kwargs to pass any additional arguments that are supported by the
        `create` constructor.
        A full example of creating a multilink using predefined netlinks::

            multilink = Multilink.create_with_netlinks(
                name='mynewnetlink',
                netlinks=[{'netlink': StaticNetlink('netlink1'),
                           'ip_range': '1.1.1.2-1.1.1.3',
                           'netlink_role': 'active'},
                          {'netlink': StaticNetlink('netlink2'),
                           'ip_range': '2.1.1.2-2.1.1.3',
                           'netlink_role': 'standby'}])

        :param StaticNetlink,DynamicNetlink netlink: StaticNetlink element
        :param str ip_range: ip range for source NAT on this netlink
        :param str netlink_role: the role for this netlink, `active` or
            `standby`
        :raises CreateElementFailed: failure to create multilink
        :rtype: Multilink
        """
    multilink_members = []
    for member in netlinks:
        m = {'ip_range': member.get('ip_range', '0.0.0.0'), 'netlink_role':
            member.get('netlink_role', 'active')}
        netlink = member.get('netlink')
        m.update(netlink_ref=netlink.href)
        if netlink.typeof == 'netlink':
            m.update(network_ref=netlink.data.get('ref')[0])
        multilink_members.append(m)
    return cls.create(name, multilink_members, **kwargs)


def paginate(items, n):
    """Generate n-sized chunks from items"""
    for i in range(0, len(items), n):
        yield items[i:i + n]


def run():
    """    The ``gunicorn_thrift`` command line runner for launching Gunicorn with
    generic thrift applications.
    """
    from gunicorn_thrift.app.thriftapp import ThriftApplication
    ThriftApplication('%(prog)s [OPTIONS] [APP_MODULE]').run()


@classmethod
def rsaa(cls, ra, league_ra, ip):
    """
        Run Saved Above Average
        :param ra: run average
        :param league_ra: league run average
        :param ip: inning pitched
        :return: (float) rsaa
        """
    return round(float(league_ra - ra) * ip / 9.0, 1)


def updateResponse(context, request, view):
    """
	This method is always called, and should set a HTTP header informing
        the current data needed to invalid a request the next time they
        request the adapted view.
        """


def html_quote(line):
    """Change HTML special characters to their codes.

    Follows ISO 8859-1 Characters changed: `&`, `<` and `>`.
    """
    result = line
    if '`' not in result:
        result = line.replace('&', '&')
        result = result.replace('<', '<')
        result = result.replace('>', '>')
    return result


@classmethod
def from_factory(cls, factory):
    """Make Registry from Pre-existing Factory."""
    obj = object.__new__(cls)
    obj._factory = factory
    return obj


def upgrade_environment():
    """Actually perform an environment upgrade.

        Implementations of this method don't need to commit any
        database transactions. This is done implicitly for each
        participant if the upgrade succeeds without an error being
        raised.

        However, if the `upgrade_environment` consists of small,
        restartable, steps of upgrade, it can decide to commit on its
        own after each successful step.
        """


def delete_subscription(subscription_id):
    """
    Deletes a subscription

    :param subscription_id: Subscription identifier
    :type subscription_id:  String
    """
    raise NotImplementedError


def download(url, path, verbosity=0):
    """Download large file efficiently from url into path

    Parameters
    ==========
    url: string
        The URL to download from.  Redirects are followed.
    path: string
        Relative or absolute path to the file in which the download will be stored.  If this is
        an existing directory or ends in a path separator, the "path" component of the URL will
        be used as the file name, and the full directory path will be created.
    verbosity: integer
        If greater than zero, dump the response to this request.

    """
    from shutil import copyfileobj
    from os import makedirs
    from os.path import split, exists, join, isdir
    from functools import partial
    import requests
    try:
        from urllib.parse import urlparse
    except ImportError:
        from urlparse import urlparse
    url_path = urlparse(url).path
    if isdir(path):
        path = join(path, url_path[1:])
        directory, filename = split(path)
        if not exists(directory):
            makedirs(directory)
        local_filename = join(directory, filename)
    else:
        directory, filename = split(path)
        if not exists(directory):
            makedirs(directory)
        if not filename:
            filename = url_path
        local_filename = join(directory, filename)
    r = requests.get(url, stream=True, allow_redirects=True)
    if r.status_code != 200:
        print('An error occurred when trying to access <{0}>.'.format(url))
        try:
            print(r.json())
        except:
            pass
        r.raise_for_status()
        raise RuntimeError()
    r.raw.read = partial(r.raw.read, decode_content=True)
    with open(local_filename, 'wb') as f:
        copyfileobj(r.raw, f)
    if verbosity > 0:
        from requests_toolbelt.utils import dump
        data = dump.dump_all(r)
        print(data.decode('utf-8'))
    return local_filename


def __get_namespace(args, kw='package'):
    """ Return the namespace of the package as specified as an argument
    unless it was specified in the package name.
    """
    namespace = args.namespace
    try:
        if args.__getattribute__(kw) and '/' in args.__getattribute__(kw):
            namespace = args.__getattribute__(kw).split('/', 1)[0]
    except AttributeError:
        pass
    return namespace


def overwrite(new_contents):
    """Replace the contents of the mutable file, provided that no other
        node has published (or is attempting to publish, concurrently) a
        newer version of the file than this one.

        I will avoid modifying any share that is different than the version
        given by get_sequence_number(). However, if another node is writing
        to the file at the same time as me, I may manage to update some shares
        while they update others. If I see any evidence of this, I will signal
        UncoordinatedWriteError, and the file will be left in an inconsistent
        state (possibly the version you provided, possibly the old version,
        possibly somebody else's version, and possibly a mix of shares from
        all of these).

        The recommended response to UncoordinatedWriteError is to either
        return it to the caller (since they failed to coordinate their
        writes), or to attempt some sort of recovery. It may be sufficient to
        wait a random interval (with exponential backoff) and repeat your
        operation. If I do not signal UncoordinatedWriteError, then I was
        able to write the new version without incident.

        I return a Deferred that fires (with a PublishStatus object) when the
        update has completed.
        """


def get_id(c):
    """Return the id of the python object."""
    return str(c.name)[str(c.name).find(' at ') + 4:-1]


def delete_gcm_channel(ApplicationId=None):
    """
    Deletes the GCM channel for an app.

    :example: response = client.delete_gcm_channel(
        ApplicationId='string'
    )

    :type ApplicationId: string
    :param ApplicationId: [REQUIRED]

    :rtype: dict
    :return: {
        'GCMChannelResponse': {
            'ApplicationId': 'string',
            'CreationDate': 'string',
            'Credential': 'string',
            'Id': 'string',
            'IsArchived': True|False,
            'LastModifiedBy': 'string',
            'LastModifiedDate': 'string',
            'Platform': 'string',
            'Version': 123
        }
    }

    """
    pass


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


def Swamee_Ojha(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D = 0.5\\left\\{16\\left[(\\frac{24}{Re})^{1.6} + (\\frac{130}{Re})^{0.72}
        \\right]^{2.5}+ \\left[\\left(\\frac{40000}{Re}\\right)^2 + 1\\right]^{-0.25}
        \\right\\}^{0.25}

    Parameters
    ----------
    Re : float
        Particle Reynolds number of the sphere using the surrounding fluid
        density and viscosity, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is Re <= 1.5E5

    Examples
    --------
    >>> Swamee_Ojha(200.)
    0.8490012397545713

    References
    ----------
    .. [1] Swamee, P. and Ojha, C. (1991). "Drag Coefficient and Fall Velocity
       of nonspherical particles." J. Hydraul. Eng., 117(5), 660-667.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    Cd = 0.5 * (16 * ((24.0 / Re) ** 1.6 + (130.0 / Re) ** 0.72) ** 2.5 + (
        (40000.0 / Re) ** 2 + 1) ** -0.25) ** 0.25
    return Cd


def ref_seq_nt_output(in_seq_name, in_ref_name, nt, ext):
    """
    Generate output file name
    :param in_seq_name: treatment name (str)
    :param in_ref_name: reference name (str)
    :param nt: aligned read length (int)
    :param ext: extension (ie. csv or pdf)
    :return: output filename (str)
    """
    return '{0}_{1}_{2}.{3}'.format(in_ref_name, in_seq_name, str(nt), ext)


@classmethod
def from_path(cls, path):
    """Creates a new item from the media file at the specified path.
        """
    i = cls(album_id=None)
    i.read(path)
    i.mtime = i.current_mtime()
    return i


def canonical_name(k, config):
    """Return the canonical name for a key.

    Handles user choice of '-' or '_' conventions by standardizing on whichever
    version was set first. If a key already exists in either hyphen or
    underscore form, the existing version is the canonical name. If neither
    version exists the original key is used as is.
    """
    try:
        if k in config:
            return k
    except TypeError:
        return k
    altk = k.replace('_', '-') if '_' in k else k.replace('-', '_')
    if altk in config:
        return altk
    return k


def check_that_operator_can_be_applied_to_produces_items(op, g1, g2):
    """
    Helper function to check that the operator `op` can be applied to items produced by g1 and g2.
    """
    g1_tmp_copy = g1.spawn()
    g2_tmp_copy = g2.spawn()
    sample_item_1 = next(g1_tmp_copy)
    sample_item_2 = next(g2_tmp_copy)
    try:
        op(sample_item_1, sample_item_2)
    except TypeError:
        raise TypeError(
            f"Operator '{op.__name__}' cannot be applied to items produced by {g1} and {g2} (which have type {type(sample_item_1)} and {type(sample_item_2)}, respectively)"
            )


def set_hr(A, a):
    """ Return the half-right of the given array.
    """
    nx, _ = A.shape
    li = int(nx / 2)
    A[:, li:] = a


def replace_keys(the_string, the_dict):
    """
    Replace all keys with their values in 'the_string'
    :param the_string:
    :param the_dict:
    :return: processed string
    """
    for key, value in the_dict.items():
        the_string = the_string.replace(key, value)
    return the_string


def broadcast_plus(lhs=None, rhs=None, name=None, attr=None, out=None, **kwargs
    ):
    """Returns element-wise sum of the input arrays with broadcasting.

    `broadcast_plus` is an alias to the function `broadcast_add`.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_add(x, y) = [[ 1.,  1.,  1.],
                              [ 2.,  2.,  2.]]

       broadcast_plus(x, y) = [[ 1.,  1.,  1.],
                               [ 2.,  2.,  2.]]

    Supported sparse operations:

       broadcast_add(csr, dense(1D)) = dense
       broadcast_add(dense(1D), csr) = dense

    Defined in src/operator/tensor/elemwise_binary_broadcast_op_basic.cc:L58

    Parameters
    ----------
    lhs : Symbol
        First input to the function
    rhs : Symbol
        Second input to the function

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

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


def isLanguageIndependent(instance):
    """Get the language independed flag for i18n content."""


def set(data, c):
    """
    Set to a constant.

    Parameters
    ----------
    data : ndarray
        Array of NMR data.
    c : float or complex
        Constant to set data to.

    Returns
    -------
    ndata : ndarray
        Array of constants.

    Notes
    -----
    data is set in place, if original data is required make a copy before
    calling this function.

    """
    data[(...), :] = c
    return data


def randomize_unitofwork():
    """Use random-ordering sets within the unit of work in order
    to detect unit of work sorting issues.

    This is a utility function that can be used to help reproduce
    inconsistent unit of work sorting issues.   For example,
    if two kinds of objects A and B are being inserted, and
    B has a foreign key reference to A - the A must be inserted first.
    However, if there is no relationship between A and B, the unit of work
    won't know to perform this sorting, and an operation may or may not
    fail, depending on how the ordering works out.   Since Python sets
    and dictionaries have non-deterministic ordering, such an issue may
    occur on some runs and not on others, and in practice it tends to
    have a great dependence on the state of the interpreter.  This leads
    to so-called "heisenbugs" where changing entirely irrelevant aspects
    of the test program still cause the failure behavior to change.

    By calling ``randomize_unitofwork()`` when a script first runs, the
    ordering of a key series of sets within the unit of work implementation
    are randomized, so that the script can be minimized down to the
    fundamental mapping and operation that's failing, while still reproducing
    the issue on at least some runs.

    This utility is also available when running the test suite via the
    ``--reversetop`` flag.

    .. versionadded:: 0.8.1 created a standalone version of the
       ``--reversetop`` feature.

    """
    from sqlalchemy.orm import unitofwork, session, mapper, dependency
    from sqlalchemy.util import topological
    from sqlalchemy.testing.util import RandomSet
    (topological.set) = (unitofwork.set) = (session.set) = (mapper.set) = (
        dependency.set) = RandomSet


def _fd(f):
    """Get a filedescriptor from something which could be a file or an fd."""
    return f.fileno() if hasattr(f, 'fileno') else f


def get_folder(FolderId=None):
    """
    Retrieves the metadata of the specified folder.
    See also: AWS API Documentation

    :example: response = client.get_folder(
        FolderId='string'
    )

    :type FolderId: string
    :param FolderId: [REQUIRED]
            The ID of the folder.

    :rtype: dict
    :return: {
        'Metadata': {
            'Id': 'string',
            'Name': 'string',
            'CreatorId': 'string',
            'ParentFolderId': 'string',
            'CreatedTimestamp': datetime(2015, 1, 1),
            'ModifiedTimestamp': datetime(2015, 1, 1),
            'ResourceState': 'ACTIVE'|'RESTORING'|'RECYCLING'|'RECYCLED',
            'Signature': 'string'
        }
    }

    """
    pass


@classmethod
def _from_munch(cls, obj, synchronized=True, connection=None):
    """Create an instance from a ``munch.Munch`` object.

        This is intended as a temporary measure to convert between shade-style
        Munch objects and original openstacksdk resources.

        :param obj: a ``munch.Munch`` object to convert from.
        :param bool synchronized: whether this object already exists on server
            Must be set to ``False`` for newly created objects.
        """
    return cls(_synchronized=synchronized, connection=connection, **obj)


@classmethod
def getParentPid(cls, pid):
    """
            getParentPid - Get parent pid of given process pid.

            @param pid <int> - Process pid

            @return <int/None> - Integer of parent pid of @pid, or None if could not determine (like program not running)
        """
    pid = int(pid)
    try:
        statInfo = cls.getStatInfo(pid)
    except:
        return None
    return statInfo['ppid']


def split_negations(iterable, func=str):
    """"Split an iterable into negative and positive elements.

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

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


def transPara(trans_iter, trans_for_bam):
    """Generate parameters (trans, g1t, g2t) for function _get_tis()
  """
    for t in trans_iter:
        if t.id in trans_for_bam:
            yield t, trans_for_bam[t.id]


def _write_script(cmds, script):
    """Write commands into a bash script"""
    f = open(script, 'w+')
    for cmd in cmds:
        print(cmd, file=f)
    f.close()


def ValidateSizeQuota(value):
    """
    Validate a quota value.  This may be blank or a non-negative integer.

    :param value: The proposed value.
    :type value: int
    :returns: The validated value or None,
              and a recommended error message or None.
    :rtype: (int or None, str or None)
    """
    if value is None or value == '':
        return None, None
    error = False
    try:
        value = int(value)
        if value < 0:
            error = True
    except ValueError:
        error = True
    if error:
        return (value,
            'Invalid quota.  Must be blank or a non-negative integer representing the limit in bytes.'
            )
    return value, None


def make_normalizer_node(context, input, output, norm):
    """
    Helper function to construct a normalizer node
    """
    from ..common import NodeBuilder
    nb = NodeBuilder(context, 'Normalizer', op_domain='ai.onnx.ml')
    nb.add_attribute('norm', norm)
    nb.add_input(input)
    nb.add_output(output)
    return nb.make_node()


def mark_seam(clear: bool=False):
    """Mark selected UV edges as seams

    :param clear: Clear Seams, Clear instead of marking seams
    :type clear: bool
    """
    pass


def escape(string):
    """ Returns the string with control characters for Pattern syntax escaped.
        For example: "hello!" => "hello\\!".
    """
    for ch in ('{', '}', '[', ']', '(', ')', '_', '|', '!', '*', '+', '^'):
        string = string.replace(ch, '\\' + ch)
    return string


def ncycle(input_iter, n: int):
    """iterz.ncycle(input_iter)

    This will cycle an iterator a certain number of times. Usage:

    >>> alist = [1, 2, 4, 8]
    >>> for item in iterz.ncycle(alist, 2)
    ...     print(item)
    1
    2
    4
    8
    1
    2
    4
    8

    In fact, it works with any iterable containing any datatypes:

    >>> atuple = (1, 'foo', 3.0)
    >>> for item in iterz.ncycle(atuple, 3):
    ...     print(item)
    1
    foo
    3.0
    1
    foo
    3.0
    1
    foo
    3.0
    """
    try:
        iterator = iter(input_iter)
    except:
        raise TypeError("'input_iter' must be 'iter'")
    if not isinstance(n, int):
        raise TypeError("'n' must be 'int'")
    if len(input_iter) < 1:
        return
    for i in range(n * len(input_iter)):
        yield input_iter[i % len(input_iter)]


def write_qgis_path(cmd, basename, filename):
    """Write the qgis path to an egg-info file.

    Write the qgis installation path to an egg-info file when the distribution attribute
    ``qgis_path`` is ``True``. The attribute value is typically set by argument ``qgis_path``
    in ``setup.py``. Intended for use by setuptools only.

    Args:
       cmd (setuptools.command.egg_info.egg_info): Object creating a distribution's
           egg-info directory and contents.
       basename (str): Filename to write.
       filename (str): Complete path, with filename, to write.
    """
    import os
    if cmd.distribution.qgis_path:
        argname = os.path.splitext(basename)[0]
        cmd.write_or_delete_file(argname, filename, cmd.distribution.qgis_path)


def find_server(servers, fd):
    """ Find matching ``server.server_socket`` for given file descriptor. """
    for server in servers:
        if fd == server.server_socket.fileno():
            return server


def get_permissions_for_role(role_id):
    """Get the premissions granted to a role.

        Return a sequence of (permission id, setting) tuples for the given
        role.

        If no permissions have been granted to this
        role, then the empty list is returned.
        """


def accept(new_energy):
    """Accept the move.

    Parameters
    ----------
    new_energy: float
        A new total energy for the system.

    Returns
    -------
    float:
        A new total energy for the system.
    """
    return new_energy


def makeDateStamp(instant):
    """
    Serialize a L{datetime.datetime} according to the AWS "date stamp"
    format.

    @param instant: A naive UTC L{datetime.datetime} (as returned from
        L{datetime.datetime.utcnow})
    @type instant: L{datetime.datetime}

    @return: The formatted date and time.
    @rtype: L{str} (native string).
    """
    return instant.strftime('%Y%m%d')


def freestyle_modifier_copy():
    """Duplicate the modifier within the list of modifiers

    """
    pass


def auth0_user_is_superuser(auth0_user):
    """
    Check if an Auth0User has been marked as having superuser status.

    :param django_db_auth0_user.models.Auth0User auth0_user: The Auth0User to check for supervisor status.
    :return:
    """
    if auth0_user.auth0_app_metadata:
        return auth0_user.auth0_app_metadata.get('is_superuser', False)
    else:
        return False


@classmethod
def _build_routes(cls, method_args, url_extra_part=None):
    """Create bottle route for a handler http method."""
    prefix = '/{}'.format(url_extra_part) if url_extra_part else ''
    endpoint = cls.base_endpoint + prefix
    if not method_args:
        return [endpoint]
    endpoints = []
    for args_list in cls._router_helper(method_args):
        prefix = '/:' if args_list else ''
        endpoints.append((endpoint + prefix + '/:'.join(args_list)).replace
            ('//', '/'))
    return endpoints


def register_handler(handler):
    """
    Install application-specific BUFR image handler.

    :param handler: Handler object.
    """
    global _handler
    _handler = handler


def rommon_prompt_handler(spawn, session, context):
    """ handles connection refused scenarios
    """
    image = context.get('image')
    cmd = 'boot ' + image[0] if image else 'boot'
    if not session.get('please_reset_seen'):
        if not session.get('rommon_count'):
            spawn.sendline(cmd)
            session['rommon_count'] = 1
        else:
            raise Exception(
                'Rommon prompt encountered unexpectedly, Maybe golden image does not exist for  % '
                , str(spawn))
    elif session.get('rommon_count'):
        if session['rommon_count'] == 1:
            spawn.send('reset\r\r')
            session['rommon_count'] += 1
        elif session['rommon_count'] == 2:
            spawn.send('confreg 0x1\r')
            session['rommon_count'] += 1
        elif session['rommon_count'] == 3:
            spawn.sendline(cmd)
            session['rommon_count'] += 1
        else:
            raise Exception(
                'Rommon prompt encountered unexpectedly, Maybe golden image does not exist for  % '
                , str(spawn))
    else:
        spawn.send('confreg 0x0\r')
        session['rommon_count'] = 1


def getIntensityPercentile(sampleList, cutoffPercent):
    """
    Returns the nth percent of energy represented in a dataset
    """
    tmpSampleList = sorted(sampleList)
    return tmpSampleList[int(len(tmpSampleList) * cutoffPercent)]


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

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

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


def update_kwargs(kwargs, **keyvalues):
    """Update dict with keys and values if keys do not already exist.

    >>> kwargs = {'one': 1, }
    >>> update_kwargs(kwargs, one=None, two=2)
    >>> kwargs == {'one': 1, 'two': 2}
    True

    """
    for key, value in keyvalues.items():
        if key not in kwargs:
            kwargs[key] = value


def load_matrix(matrix: 'mathutils.Matrix'):
    """Load a matrix into the stack.

    :param matrix: A 4x4 matrix.
    :type matrix: 'mathutils.Matrix'
    """
    pass


def escape_table_cell_value(text: str) ->str:
    """
    Escape pipe characters `|` in a table cell's value. Since the pipe characters
    are used to separate cells in a row, we need to replace them by `\\|`.
    """
    return text.replace('|', '\\|')


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


def check_constraints(param_constraints):
    """Checks whether user provided list specifying which parameters
    are to be free versus fixed is in proper format, and assigns
    default values where necessary.

    Keyword arguments:
    param_constraints -- specifies which parameters to estimate (list)
    """
    if param_constraints is None:
        param_constraints = [True, True, False, False]
    elif param_constraints is not None:
        if isinstance(param_constraints, list) is False:
            raise ValueError(
                """User Error: Please provide a argument of type list indicating
            which parameters of the model are free (i.e., TRUE) versus fixed (i.e., FALSE)."""
                )
        for i in param_constraints:
            if isinstance(i, bool) is False:
                raise ValueError(
                    """User Error: Please provide boolean arguments for parameter '
                                constraints (i.e., free vs fixed) of the model."""
                    )
            if len(param_constraints) < 2:
                raise ValueError(
                    """User Error: Please provide at least two constraints (scale; slope)
                                for parameters of the model."""
                    )
            elif len(param_constraints) == 2:
                print(
                    'Setting parameter constraints for gamma and lambda to default values (i.e., fixed)!'
                    )
                param_constraints.append(False)
                param_constraints.append(True)
            elif len(param_constraints) == 3:
                print(
                    'Setting parameter constraints for lambda to default value (i.e., fixed)!'
                    )
                param_constraints.append(True)
            elif len(param_constraints) > 4:
                raise ValueError(
                    'User Error: More than 4 constraints for parameters of the model provided!'
                    )
    return param_constraints


def default_clutch_k_factor_curve():
    """
    Returns a default k factor curve for a generic clutch.

    :return:
        k factor curve.
    :rtype: callable
    """
    from ..defaults import dfl
    par = dfl.functions.default_clutch_k_factor_curve
    a = par.STAND_STILL_TORQUE_RATIO, par.LOCKUP_SPEED_RATIO
    from . import define_k_factor_curve
    return define_k_factor_curve(*a)


@classmethod
def from_json(Note, n):
    """
        Creates a Note object from a dictionary that contains keys values equivalent to the name of the instance variables of the Note class

        :param n: Dictionary containing key-value pairs, where the keys values are equivalent to the name of the instance variables in the Note class
        :type n: dict

        :return: Note whose instance variables contain the values from the dictionary
        :rtype: Note
        """
    note = Note(id=n.get('id'), original=n.get('original'), number=n.get(
        'number'), cdate=n.get('cdate'), tcdate=n.get('tcdate'), tmdate=n.
        get('tmdate'), ddate=n.get('ddate'), content=n.get('content'),
        forum=n.get('forum'), referent=n.get('referent'), invitation=n.get(
        'invitation'), replyto=n.get('replyto'), readers=n.get('readers'),
        nonreaders=n.get('nonreaders'), signatures=n.get('signatures'),
        writers=n.get('writers'), details=n.get('details'), tauthor=n.get(
        'tauthor'))
    return note


def path_from_imagestore_string(imagestore_connstr):
    """
    Parse the file share path from the image store connection string
    """
    if imagestore_connstr and 'file:' in imagestore_connstr:
        conn_str_list = imagestore_connstr.split('file:')
        return conn_str_list[1]
    return False


@classmethod
def from_file(cls, fname):
    """Create a SchemaRegistry from a file.

        Args:
            fname (str): Full path to the file the schema should be loaded from.

        """
    out = cls()
    out.load(fname)
    return out


def to_value(unit_system: str, unit_category: str, str_input: str,
    str_ref_unit: str=None) ->float:
    """Convert a given input string into a float value.

    :param unit_system: The unit system, from bpy.utils.units.systems.
    :type unit_system: str
    :param unit_category: The category of data we are converting (length, area, rotation, etc.), from bpy.utils.units.categories.
    :type unit_category: str
    :param str_input: The string to convert to a float value.
    :type str_input: str
    :param str_ref_unit: A reference string from which to extract a default unit, if none is found in str_input.
    :type str_ref_unit: str
    :return:  The converted/interpreted value.
    """
    pass


def localCovMtxs(meanTensor, pCovMtx, tensorVectForm=True):
    """Determines the covariance matrix :math:`\\boldsymbol{\\mathrm{W}_i}` of
    the random variables :math:`\\left(\\mathrm{d}p_{ji},
    \\mathrm{d}p_{ki}\\right)` from the local Cartesian System
    :math:`\\mathrm{d}\\boldsymbol{p}_i` that define the :math:`\\mathscr{P}-`
    plane where each confidence area of the mean tensor's princial direcions
    are drawn by using the equation (27) of
    `Jelínek (1978) <https://doi.org/10.1007/BF01613632>`_.

    Parameters:
        meanTensor (`numpy.ndarray`): mean tensor :math:`\\boldsymbol{k}` of
            the sample either in vector or matrix form.
        pCovMtx (`numpy.ndarray`): :math:`(6 \\times 6)` covariance matrix
            :math:`\\boldsymbol{\\mathrm{V^\\mathrm{P}}}` of
            :math:`\\boldsymbol{k^\\mathrm{P}}`'s elements. It is obtained
            with the ``covMtx2PPlane`` function.
        tensorVectForm (`bool`): Logical variable to indicate if the input
            :math:`\\boldsymbol{k}` is in vector form. ``True`` is the default
            value.

    Returns:
        Three elements are returned; they are described below.

            - **W** (`list`): list of three :math:`(2 \\times 2)` arrayes                with the covariance matrix :math:`\\boldsymbol{\\mathrm{W}_i}`                described above.
            - **eigVal_W** (`list`): list with the three couples of                 :math:`\\boldsymbol{\\mathrm{W}_i}`'s eigenvalues obtained                 with the ``getEigSorted`` function.
            - **eigVec_W** (`list`): list with the three :math:`(2 \\times 2)`                arrayes of :math:`\\boldsymbol{\\mathrm{W}_i}`'s eigevectors                obtained with the ``getEigSorted`` function.

    Examples:
        >>> from numpy import cov
        >>> from jelinekstat.tools import dataFromFile
        >>> from jelinekstat.jelinekstat import meantensor, covMtx2PPlane
        >>> sample, numTensors = dataFromFile('inputDataExample.txt')
        >>> normTensors = normalizeTensors(sample)
        >>> meanTensorVect, meanTensorMtx, numTensors = meantensor(
        >>>     normTensors, normalized=True)
        >>> covMtx = cov(normTensors.T, bias=False)
        >>> pCovMtx = covMtx2PPlane(
        >>>     covMtx, meanTensorVect, numTensors)
        >>> W, eigVal_W, eigVec_W = localCovMtxs(
        >>>     meanTensorVect, pCovMtx)
        >>> W
        [array([[ 0.41635005, -0.00798796],
                [-0.00798796,  0.00679994]]),
         array([[ 0.00739345, -0.02211065],
                [-0.02211065,  0.41635005]]),
        array([[ 0.00679994, -0.00565157],
               [-0.00565157,  0.00739345]])]
        >>> eigVal_W
        [array([ 0.41650579,  0.0066442 ]),
         array([ 0.41754201,  0.00620149]),
         array([ 0.01275605,  0.00143733])]
        >>> eigVec_W
        [array([[ 0.99980999,  0.01949312],
                [-0.01949312,  0.99980999]]),
         array([[ 0.05383071, -0.99855008],
                [-0.99855008, -0.05383071]]),
         array([[ 0.68831829, -0.7254088 ],
                [-0.7254088 , -0.68831829]])]
    """
    import numpy as np
    from jelinekstat.tools import tensorvect2matrixform, getEigSorted
    if tensorVectForm:
        meanTensor = tensorvect2matrixform(meanTensor)
    eigVal_mT, eigVec_mT = getEigSorted(meanTensor)
    t = eigVal_mT
    W = list()
    eigVal_W = list()
    eigVec_W = list()
    for l, r, s in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]:
        Wl = np.array([[pCovMtx[3 + l, 3 + l] / (t[l] - t[r]) ** 2, pCovMtx
            [3 + l, 3 + s] / ((t[l] - t[r]) * (t[l] - t[s]))], [pCovMtx[3 +
            l, 3 + s] / ((t[l] - t[r]) * (t[l] - t[s])), pCovMtx[3 + s, 3 +
            s] / (t[l] - t[s]) ** 2]])
        W.append(Wl)
        eigVal, eigVec = getEigSorted(Wl)
        eigVal_W.append(eigVal)
        eigVec_W.append(eigVec)
    return W, eigVal_W, eigVec_W


def decimate(ratio: float=1.0):
    """Simplify selected curves

    :param ratio: Ratio
    :type ratio: float
    """
    pass


def constantly(x):
    """Creates a function accepting any args, but always returning x."""
    return lambda *a, **kw: x


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 SearchableText():
    """ Return a string containing textual information about the content.

        o This string may be the content of a file, or may be synthesized
          by concatenating the string attributes of the instance.

        o Permissions:  View
        """


def get(isdsAppliance, check_mode=False, force=False):
    """
    Retrieve available updates
    """
    return isdsAppliance.invoke_get('Retrieving available updates',
        '/updates/available.json')


def is_cuda_array(obj):
    """Test if the object has defined the `__cuda_array_interface__` attribute.

    Does not verify the validity of the interface.
    """
    return hasattr(obj, '__cuda_array_interface__')


def _adjust_table_code(table_code: int) ->int:
    """
    table code handler for alternate table code form:
       501 -> 1
       510 -> 10
       511 -> 11
       601 -> 1
       etc.
    """
    if table_code in [501, 510, 511]:
        table_code -= 500
    elif table_code in [601, 610, 611]:
        table_code -= 600
    elif table_code in [701, 710, 711]:
        table_code -= 700
    elif table_code in [801, 810, 811]:
        table_code -= 800
    elif table_code in [901, 910, 911]:
        table_code -= 900
    return table_code


def prepare_dataset(dataset_id: str):
    """Find a dataset given its id"""
    from .definitions import DatasetDefinition
    ds = DatasetDefinition.find(dataset_id)
    return ds.prepare(download=True)


@classmethod
def asArray(cls, value, typeCode=None):
    """Convert given value to an array value of given typeCode"""
    return value


@classmethod
def global_mute(cls) ->bool:
    """Default: False (never globally muted)"""
    return False


@staticmethod
def _default_evidence_code() ->str:
    """Yields the default GO evidence code"""
    return 'NR'


def dot(x, y):
    """
	Dot product between two vector-like arrays
	"""
    if len(x) != len(y):
        print('Array sizes are not equal.')
        return
    sum = 0
    for i in range(0, len(x)):
        sum += x[i] * y[i]
    return sum


@classmethod
def meta(cls):
    """Return a dictionary containing meta-information about the given
        resource."""
    if getattr(cls, '__from_class__', None) is not None:
        cls = cls.__from_class__
    attribute_info = {}
    for name, value in cls.__table__.columns.items():
        attribute_info[name] = str(value.type).lower()
    return {cls.__name__: attribute_info}


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

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


def set_hwm(sock, hwm=0):
    """set zmq High Water Mark on a socket

    in a way that always works for various pyzmq / libzmq versions.
    """
    import zmq
    for key in ('HWM', 'SNDHWM', 'RCVHWM'):
        opt = getattr(zmq, key, None)
        if opt is None:
            continue
        try:
            sock.setsockopt(opt, hwm)
        except zmq.ZMQError:
            pass


def convert2boolean(arg):
    """
    convert2boolean is used for environmental variables
    that must be returned as boolean
    """
    if not isinstance(arg, bool):
        return arg.lower() in ('yes', 'true', 't', '1', 'y')
    return arg


def deserializeValueWithNone(value):
    """Return None if value is NONE_MARKER, otherwise deserialie normally.
        """


def int_if_digit(s: str):
    """Iterpret as integer if `s` represents a digit string."""
    try:
        if s.isdigit():
            return int(s)
    except AttributeError:
        pass
    return s


def distinct(keys):
    """
    Return the distinct keys in order.
    """
    known = set()
    outlist = []
    for key in keys:
        if key not in known:
            outlist.append(key)
        known.add(key)
    return outlist


@classmethod
def set_default_resource_registry(cls, registry):
    """ Set the callable that will act as a default
        :term:`resource registry` for instances of the associated
        class when no ``resource_registry`` argument is provided to
        the class' constructor.  Useful when you'd like to use
        non-default requirement to resource path mappings for the
        entirety of a process.

        Calling this method resets the default :term:`resource registry`.
        """
    cls.default_resource_registry = registry


def afterDaemonize():
    """
        Hook to be called immediately after daemonization. This may only be
        called after L{beforeDaemonize} had been called previously.

        @return: L{None}.
        """


def load_stop_words(stop_word_file):
    """
    Utility function to load stop words from a file and return as a list of words
    @param stop_word_file Path and file name of a file containing stop words.
    @return list A list of stop words.
    """
    stop_words = []
    for line in open(stop_word_file):
        if line.strip()[0:1] != '#':
            for word in line.split():
                stop_words.append(word)
    return stop_words


def getMeanWave(Parms):
    """returns mean wavelength from Instrument parameters dictionary

    :param dict Parms: Instrument parameters;
        must contain:
        Lam: single wavelength
        or
        Lam1,Lam2: Ka1,Ka2 radiation wavelength
        I(L2)/I(L1): Ka2/Ka1 ratio

    :returns: float wave: mean wavelength

    """
    try:
        return Parms['Lam'][1]
    except KeyError:
        meanLam = (Parms['Lam1'][1] + Parms['I(L2)/I(L1)'][1] * Parms[
            'Lam2'][1]) / (1.0 + Parms['I(L2)/I(L1)'][1])
        return meanLam


def generate_lower_name(model_cls):
    """
    Generates the name of the class from the class object, e.g. ``SomeClass`` -> ``some_class``

    :param model_cls: class to evaluate
    :return: lowercase name
    :rtype: basestring
    """
    return getattr(model_cls, '__mapiname__', model_cls.__tablename__)


def _parsepref_old(preffile):
    """ Parse parameter file of old type (using exec of Python commands)
    """
    pars = {}
    with open(preffile, 'r') as fp:
        for line in fp.readlines():
            line_clean = line.rstrip('\n').split('#')[0]
            if line_clean and '=' in line:
                attribute, value = line_clean.split('=')
                try:
                    value_eval = eval(value.strip())
                except NameError:
                    value_eval = value.strip()
                finally:
                    pars[attribute.strip()] = value_eval
    return pars


def expiration_age():
    """Python timedelta of when cached item should be considered invalid"""


def _filters(query):
    """Filter rows with a CBS-style query.

    Parameters
    ----------
    query : str
        The rows to return.

    Returns
    -------
    str
        Filter parameter for URL
    """
    return query