def create_snapshot(DryRun=None, VolumeId=None, Description=None):
    """
    Creates a snapshot of an EBS volume and stores it in Amazon S3. You can use snapshots for backups, to make copies of EBS volumes, and to save data before shutting down an instance.
    When a snapshot is created, any AWS Marketplace product codes that are associated with the source volume are propagated to the snapshot.
    You can take a snapshot of an attached volume that is in use. However, snapshots only capture data that has been written to your EBS volume at the time the snapshot command is issued; this may exclude any data that has been cached by any applications or the operating system. If you can pause any file systems on the volume long enough to take a snapshot, your snapshot should be complete. However, if you cannot pause all file writes to the volume, you should unmount the volume from within the instance, issue the snapshot command, and then remount the volume to ensure a consistent and complete snapshot. You may remount and use your volume while the snapshot status is pending .
    To create a snapshot for EBS volumes that serve as root devices, you should stop the instance before taking the snapshot.
    Snapshots that are taken from encrypted volumes are automatically encrypted. Volumes that are created from encrypted snapshots are also automatically encrypted. Your encrypted volumes and any associated snapshots always remain protected.
    For more information, see Amazon Elastic Block Store and Amazon EBS Encryption in the Amazon Elastic Compute Cloud User Guide .
    See also: AWS API Documentation

    Examples
    This example creates a snapshot of the volume with a volume ID of vol-1234567890abcdef0 and a short description to identify the snapshot.
    Expected Output:

    :example: response = client.create_snapshot(
        DryRun=True|False,
        VolumeId='string',
        Description='string'
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type VolumeId: string
    :param VolumeId: [REQUIRED]
            The ID of the EBS volume.

    :type Description: string
    :param Description: A description for the snapshot.

    :rtype: dict
    :return: {
        'SnapshotId': 'string',
        'VolumeId': 'string',
        'State': 'pending'|'completed'|'error',
        'StateMessage': 'string',
        'StartTime': datetime(2015, 1, 1),
        'Progress': 'string',
        'OwnerId': 'string',
        'Description': 'string',
        'VolumeSize': 123,
        'OwnerAlias': 'string',
        'Tags': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        'Encrypted': True|False,
        'KmsKeyId': 'string',
        'DataEncryptionKeyId': 'string'
    }

    """
    pass


def verify_sign(pub_key, signature, data):
    """
    Verifies with a public key from whom the data came that it was indeed
    signed by their private key.
    :param pub_key: Public key
    :param signature: String signature to be verified
    :param data: The data the signature was created with
    :return: Boolean. True for verified. False for not verified.
    """
    from Crypto.PublicKey import RSA
    from Crypto.Signature import PKCS1_v1_5
    from Crypto.Hash import SHA256
    from base64 import b64decode
    data = data.replace('\r', '')
    rsakey = RSA.importKey(pub_key)
    signer = PKCS1_v1_5.new(rsakey)
    digest = SHA256.new()
    digest.update(data)
    try:
        if signer.verify(digest, b64decode(signature)):
            return True
    except ValueError:
        pass
    return False


@staticmethod
def pluralize(realised):
    """Return the plural form of the argument realisation string."""
    if realised.endswith((u's', u'x', u'z')):
        return realised
    elif realised.endswith((u'au', u'eu')):
        return '%sx' % realised
    elif realised.endswith(u'al'):
        return '%saux' % realised[:-2]
    else:
        return '%ss' % realised


def code_to_line(code, cursor_pos):
    """Turn a multiline code block and cursor position into a single line
    and new cursor position.

    For adapting ``complete_`` and ``object_info_request``.
    """
    if not code:
        return '', 0
    for line in code.splitlines(True):
        n = len(line)
        if cursor_pos > n:
            cursor_pos -= n
        else:
            break
    return line, cursor_pos


def __call__(name):
    """Returns article registered by name"""


def rev_reg_id(cd_id: str, tag: str) ->str:
    """
    Given a credential definition identifier and a tag, return the corresponding
    revocation registry identifier, repeating the issuer DID from the
    input identifier.

    :param cd_id: credential definition identifier
    :param tag: tag to use
    :return: revocation registry identifier
    """
    return '{}:4:{}:CL_ACCUM:{}'.format(cd_id.split(':', 1)[0], cd_id, tag)


@staticmethod
def pad(input_sequence, length, pad_char):
    """
        Pad the given iterable, so that it is the correct length.

        :param input_sequence: Any iterable object
        :param length: The desired length of the output.
        :type length: int
        :param pad_char: The character or int to be added to short sequences
        :type pad_char: str or int
        :return: A sequence, of len `length`
        :rtype: []
        """
    if isinstance(input_sequence, str):
        input_sequence = list(input_sequence)
    if len(input_sequence) == length:
        return input_sequence
    elif len(input_sequence) > length:
        return input_sequence[:length]
    else:
        padding_len = length - len(input_sequence)
        padding = [pad_char] * padding_len
        return list(input_sequence) + list(padding)


def _to_json(response):
    """
    从 HTTP 请求的响应中获取数据并解析成 JSON 格式
    异步方法: JS requests 库中基于 fetch api, 其 Response.json() 方法返回 Promise

    :param response:
    :return:
    """
    return response.json()


def identity(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns a copy of the input.

    From:src/operator/tensor/elemwise_unary_op_basic.cc:246

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

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

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


def make_ideal(psr):
    """Adjust the TOAs so that the residuals to zero, then refit."""
    psr.stoas[:] -= psr.residuals() / 86400.0
    psr.fit()


def _testFlattenGlyph():
    """
    >>> from fontPens.printPen import PrintPen
    >>> glyph = _makeTestGlyph()
    >>> flattenGlyph(glyph) #doctest: +ELLIPSIS
    <RGlyph...
    >>> glyph.draw(PrintPen())
    pen.moveTo((10.0, 10.0))
    pen.lineTo((10.0, 20.0))
    pen.lineTo((10.0, 30.0))
    pen.lineTo((20.0, 30.0))
    pen.lineTo((30.0, 30.0))
    pen.lineTo((30.0, 20.0))
    pen.lineTo((30.0, 10.0))
    pen.lineTo((20.0, 10.0))
    pen.closePath()
    """


@classmethod
def stop_task(cls, task_tag, stop_dependent=True, stop_requirements=False):
    """ Stop started task from registry

		:param task_tag: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
		:param stop_dependent: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
		:param stop_requirements: same as in :meth:`.WTaskDependencyRegistryStorage.stop_task` method
		:return: None
		"""
    registry = cls.registry_storage()
    registry.stop_task(task_tag, stop_dependent=stop_dependent,
        stop_requirements=stop_requirements)


def sum_them_all(student_marks):
    """Sum all marks of a student."""
    total_mark = 0
    for i in range(0, len(student_marks)):
        total_mark += int(student_marks[i]['student_mark'])
    return total_mark


def get_parent(path):
    """
    >>> get_parent('/usr/share/doc')
    '/usr/share'
    """
    path = path.strip()
    if path.endswith('/'):
        path = path[:-1]
    return '/'.join(path.split('/')[:-1]) or '/'


def bake_action_objects_iter(object_action_pairs: 'bpy.types.Object', **kwargs
    ):
    """An coroutine that bakes actions for multiple objects.

    :param object_action_pairs: Sequence of object action tuples, action is the destination for the baked data. When None a new action will be created.
    :type object_action_pairs: 'bpy.types.Object'
    """
    pass


def unique(a):
    """Find unique elements, retaining order."""
    b = []
    for x in a:
        if x not in b:
            b.append(x)
    return b


def psi_H_Na_ClO4_PK74(T, P):
    """c-c'-a: hydrogen sodium perchlorate [PK74]."""
    psi = -0.016
    valid = T == 298.15
    return psi, valid


@classmethod
def _extract_note_part(cls, item_part, token_list):
    """
        Extracts the given part from the note
        token list

        :param item_part: element from the NOTE_SCHEME
        :type item_part: tuple
        :param token_list: list of note tokens
        """
    _start = item_part[cls.POSITION]
    _end = item_part[cls.POSITION] + item_part[cls.LEN]
    return token_list[_start:_end]


def _mean(data):
    """
    Returns the sample arithmetic mean of data. 0 is returned if an empty list
    was provided.

    Parameters
    ----------
    data : list of floats

    Returns
    _______
    out: float
        The sample arithmetic mean of data.
    """
    return float(sum(data)) / max(len(data), 1)


@staticmethod
def find_parameter(array, rmin, radius):
    """Compute for optimal R for certain atom, given array and rmin.

        To find the proper R value to make sure half points are within atomic
        radius r.

        Parameters
        ----------
        array : np.ndarray(N,)
            one dimention array locates within [-1, 1]
        rmin : float
            Minimum value for transformed array.
        radius : float
            Atomic radius of interest

        Returns
        -------
        float
            The optimal value of scale factor R

        Raises
        ------
        ValueError
            rmin needs to be smaller than atomic radius to compute R
        """
    if rmin > radius:
        raise ValueError(
            f'rmin need to be smaller than radius, rmin: {rmin}, radius: {radius}.'
            )
    size = array.size
    if size % 2:
        mid_value = array[size // 2]
    else:
        mid_value = (array[size // 2 - 1] + array[size // 2]) / 2
    return (radius - rmin) * (1 - mid_value) / (1 + mid_value)


def get_projects(slug):
    """Get project information from TimeSync"""
    p_list = [{'uri': 'https://code.osuosl.org/projects/ganeti-webmgr',
        'name': 'Ganeti Web Manager', 'slugs': [slug if slug else 'gwm'],
        'uuid': 'a034806c-00db-4fe1-8de8-514575f31bfb', 'revision': 4,
        'created_at': '2014-07-17', 'deleted_at': None, 'updated_at':
        '2014-07-20', 'users': {'patcht': {'member': True, 'spectator':
        False, 'manager': False}, 'tschuy': {'member': True, 'spectator':
        True, 'manager': True}}}]
    if not slug:
        p_list.append({'uri': 'https://code.osuosl.org/projects/timesync',
            'name': 'TimeSync', 'slugs': ['timesync', 'ts'], 'uuid':
            'a034806c-rrrr-bbbb-8de8-514575f31bfb', 'revision': 2,
            'created_at': '2014-07-17', 'deleted_at': None, 'updated_at':
            '2014-07-20', 'users': {'patcht': {'member': True, 'spectator':
            False, 'manager': False}, 'mrsj': {'member': True, 'spectator':
            True, 'manager': False}, 'tschuy': {'member': True, 'spectator':
            True, 'manager': True}}})
        p_list.append({'uri': 'https://code.osuosl.org/projects/pymesync',
            'name': 'pymesync', 'slugs': ['pymesync', 'ps'], 'uuid':
            'a034806c-ssss-cccc-8de8-514575f31bfb', 'revision': 1,
            'created_at': '2014-07-17', 'deleted_at': None, 'updated_at':
            '2014-07-20', 'users': {'patcht': {'member': True, 'spectator':
            False, 'manager': False}, 'tschuy': {'member': True,
            'spectator': True, 'manager': False}, 'mrsj': {'member': True,
            'spectator': True, 'manager': True}, 'MaraJade': {'member':
            True, 'spectator': False, 'manager': False}, 'thai': {'member':
            True, 'spectator': False, 'manager': False}}})
    return p_list


def parse_substitution_misc(consequence):
    """
    Return fields for syn, non-syn or correlated
    """
    elem = consequence.strip().split(' ')
    correlated = False
    locus_tag = elem[2]
    if elem[4][-1] == ',':
        elem[4] = elem[4][:-1]
    base = int(elem[4])
    codon = None
    region = None
    sub_type = None
    old_aa, new_aa = None, None
    protein = None
    return (sub_type, locus_tag, base, codon, region, old_aa, new_aa,
        protein, correlated)


@classmethod
def from_json(cls, data, json_schema_class=None):
    """ JSON deserialization method that retrieves a genome instance from its json representation

        If specific json schema is provided, it is utilized, and if not, a class specific is used
        """
    schema = (cls.json_schema if json_schema_class is None else
        json_schema_class())
    return schema.load(data)


def split_read(file):
    """ read file with split mark ':' """
    data = open(file)
    for each_line in data:
        try:
            [role, line_speak] = each_line.split(':', 1)
            print(role, end='')
            print(' said - ', end='')
            print(line_speak, end='')
        except ValueError:
            print(each_line)
    data.close()


def py_node(code, context):
    """A node that allows arbitrary python to be executed."""
    exec(code, context.meta, context.params)


def ms(x):
    """Convert seconds to milliseconds"""
    return 1000 * x


def parse_env(env: str):
    """
    For internal use only.
    """
    return env.split(';')


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


def __len__():
    """Return the size of the stored text.
        """


@classmethod
def replace_by_example(cls, collection, example_data, new_value,
    wait_for_sync=None, limit=None):
    """
            This will find all documents in the collection that match the specified example object,
            and replace the entire document body with the new value specified. Note that document
            meta-attributes such as _id, _key, _from, _to etc. cannot be replaced.

            Note: the limit attribute is not supported on sharded collections. Using it will result in an error.
            The options attributes waitForSync and limit can given yet without an ecapsulation into a json object.
            But this may be deprecated in future versions of arango

            Returns result dict of the request.

            :param collection Collection instance
            :param example_data An example document that all collection documents are compared against.
            :param new_value The replacement document that will get inserted in place of the "old" documents.

            :param wait_for_sync  if set to true, then all removal operations will instantly be synchronised to disk.
            If this is not specified, then the collection's default sync behavior will be applied.

            :param limit an optional value that determines how many documents to replace at most. If limit is
            specified but is less than the number of documents in the collection, it is undefined which of the
            documents will be replaced.

            :returns dict
        """
    kwargs = {'newValue': new_value, 'options': {'waitForSync':
        wait_for_sync, 'limit': limit}}
    return cls._construct_query(name='replace-by-example', collection=
        collection, example=example_data, result=False, **kwargs)


def unique_filter(seqs, feature_ids):
    """returns a map that contains only the keys that are in
    feature_ids and only contains unique sequences"""
    unique_seqs = {}
    for feature_id in feature_ids:
        if feature_id in seqs and seqs[feature_id] not in unique_seqs.values():
            unique_seqs[feature_id] = seqs[feature_id]
    return unique_seqs


def _filtered(items, keyword):
    """Filter a data frame of population / population models."""
    if not keyword:
        return items
    idx = []
    for r in range(items.shape[0]):
        if items.name[r].lower().find(keyword.lower()) != -1:
            idx.append(r)
    return items.loc[idx]


def report_missing_files():
    """Report all missing external files

    """
    pass


def writeBytes66(v):
    """Converts a value to a Rep Code 66 and returns the bytes."""
    return bytes([v])


def duplicate_object_hook(ordered_pairs):
    """Make lists out of duplicate keys."""
    json_dict = {}
    for key, val in ordered_pairs:
        existing_val = json_dict.get(key)
        if not existing_val:
            json_dict[key] = val
        elif isinstance(existing_val, list):
            existing_val.append(val)
        else:
            json_dict[key] = [existing_val, val]
    return json_dict


def _arg_kind(arg):
    """Helper function to determine kind for a given argument.

    This method will help `inspect_function` to determine the correct
    kind for arguments when using python3.

    Parameters
    ----------
    arg : object like inspect.Parameter
        The argument we will determine the type of.

    Returns
    -------
    out : string
        A string we use for determine the kind.
    """
    kind = None
    if arg.kind == arg.POSITIONAL_OR_KEYWORD:
        if arg.default is arg.empty:
            kind = 'args'
        else:
            kind = 'kwargs'
    elif arg.kind == arg.VAR_POSITIONAL:
        kind = 'varargs'
    elif arg.kind == arg.VAR_KEYWORD:
        kind = 'keywords'
    elif arg.kind == arg.KEYWORD_ONLY:
        kind = 'kwargs'
    return kind


def pad_rectangle(rect, dx, dy):
    """
    Increase width of the rectangle by dx, and height by dy.
    """
    x, y, w, h = rect
    w_new = int(w + 2 * dx)
    h_new = int(h + 2 * dy)
    x_new = max(0, int(x - dx))
    y_new = max(0, int(y - dy))
    return x_new, y_new, w_new, h_new


def group(l):
    """group(iterable) -> set of tuple of key-value"""
    d = {}
    for k in l:
        d[k] = d.get(k, 0) + 1
    return d.items()


def bone_primitive_add(name: str='Bone'):
    """Add a new bone located at the 3D-Cursor

    :param name: Name, Name of the newly created bone
    :type name: str
    """
    pass


@staticmethod
def get_tags(instance):
    """
        Returns a dictionary of tags
        """
    return instance['tags']


@classmethod
def type_descriptor(cls, typeobj):
    """Transform a generic type to a dialect-specific type.

        Dialect classes will usually use the
        :func:`.types.adapt_type` function in the types module to
        accomplish this.

        The returned result is cached *per dialect class* so can
        contain no dialect-instance state.

        """
    raise NotImplementedError()


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


@classmethod
def get_mountpoints(cls):
    """Returns a list of MountPoint instances

        >>> host.mount_point.get_mountpoints()
        [<MountPoint(path=/proc, device=proc, filesystem=proc, options=rw,nosuid,nodev,noexec,relatime)>
         <MountPoint(path=/, device=/dev/sda1, filesystem=ext4, options=rw,relatime,errors=remount-ro,data=ordered)>]
        """
    mountpoints = []
    for mountpoint in cls._iter_mountpoints():
        mountpoints.append(cls(mountpoint['path'], mountpoint))
    return mountpoints


@classmethod
def different_attributes(cls, old, new):
    """
        Backwards-compat comparison that ignores orm. on the RHS and not the left
        and which knows django.db.models.fields.CharField = models.CharField.
        Has a whole load of tests in tests/autodetection.py.
        """
    if not cls.is_triple(old) or not cls.is_triple(new):
        return old != new
    old_field, old_pos, old_kwd = old
    new_field, new_pos, new_kwd = new
    old_pos, new_pos = old_pos[:], new_pos[:]
    old_kwd = dict(old_kwd.items())
    new_kwd = dict(new_kwd.items())
    if 'unique' in old_kwd:
        del old_kwd['unique']
    if 'unique' in new_kwd:
        del new_kwd['unique']
    if old_field != new_field:
        if old_field.startswith('models.') and (new_field.startswith(
            'django.db.models') or new_field.startswith('django.contrib.gis')):
            if old_field.split('.')[-1] != new_field.split('.')[-1]:
                return True
            else:
                old_field = new_field = ''
    if (old_pos and 'to' in new_kwd) and ('orm' in new_kwd['to'] and 'orm'
         not in old_pos[0]):
        try:
            if old_pos[0] != new_kwd['to'].split("'")[1].split('.')[1]:
                return True
        except IndexError:
            pass
        old_pos = old_pos[1:]
        del new_kwd['to']
    return old_field != new_field or old_pos != new_pos or old_kwd != new_kwd


@staticmethod
def _unsubscribe(sub_id):
    """Stop listening to a queue or a broadcast
        :param sub_id: ID for this subscription in the transport layer
        """
    raise NotImplementedError('Transport interface not implemented')


def E2L(energy):
    """
    energy (ev) to wavelength in meter !!!
    """
    return 12398.0 / energy * 1e-10


@classmethod
def _register(cls, registerCls):
    """
        Decorator to register Entry type classes.

        :param registerCls: class to register
        :type registerCls: class
        :return: class to register
        :rtype: class
        """
    type_name = registerCls.BibTeXType
    cls._registeredTypes[type_name] = registerCls
    return registerCls


@classmethod
def __fixName(cls, name):
    """Translate a class argument name to a CSS property name by
        replacing underscores with dashes.

        * name -- The name to fix

        """
    return name.replace('_', '-')


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

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


def post_build(site):
    """
    Called after building the site.

    :param site: The site that was just built.
    :returns: None
    """
    pass


def p_inner_statement(p):
    """inner_statement : statement
                       | function_declaration_statement
                       | class_declaration_statement
                       | HALT_COMPILER LPAREN RPAREN SEMI"""
    assert len(p
        ) == 2, '__HALT_COMPILER() can only be used from the outermost scope'
    p[0] = p[1]


def split_org_repo(in_str):
    """Splits the input string to extract the repo and the org

    If the repo is not provided none will be returned

    Returns a pair or org, repo
    """
    tokens = in_str.split('/', 1)
    org = tokens[0]
    repo = None
    if len(tokens) > 1 and tokens[1]:
        repo = tokens[1]
    return org, repo


def save_homefile():
    """Make the current file the default .blend file, includes preferences

    """
    pass


def _ligotimegps(s, ns=0):
    """Catch TypeError and cast `s` and `ns` to `int`
    """
    from lal import LIGOTimeGPS
    try:
        return LIGOTimeGPS(s, ns)
    except TypeError:
        return LIGOTimeGPS(int(s), int(ns))


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

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


def revoke_roles_on_project_deletion(sender, instance=None, **kwargs):
    """
    When project is deleted, all project permissions are cascade deleted
    by Django without emitting structure_role_revoked signal.
    So in order to invalidate nc_user_count quota we need to emit it manually.
    """
    instance.remove_all_users()


def chop_list(blocks, src, start, end):
    """
    For each alignment block in the sequence `blocks`, chop out the portion
    of the block that overlaps the interval [`start`,`end`) in the
    component/species named `src`.
    """
    new_blocks = []
    for block in blocks:
        ref = block.get_component_by_src(src)
        if ref.strand == '-':
            slice_start = max(ref.src_size - end, ref.start)
            slice_end = max(ref.src_size - start, ref.end)
        else:
            slice_start = max(start, ref.start)
            slice_end = min(end, ref.end)
        sliced = block.slice_by_component(ref, slice_start, slice_end)
        good = True
        for c in sliced.components:
            if c.size < 1:
                good = False
        if good:
            new_blocks.append(sliced)
    return new_blocks


def parse_report_section(config_obj, section):
    """
  parse the [REPORT] section of a config file to extract various reporting options to be passed to the Report object
  :param: config_obj : configparser object for the config file passed in to naarad
  :param: section: name of the section. 'REPORT' should be passed in here
  :return: report_kwargs: dictionary of Reporting options and values specified in config.
  """
    report_kwargs = {}
    if config_obj.has_option(section, 'stylesheet_includes'):
        report_kwargs['stylesheet_includes'] = config_obj.get(section,
            'stylesheet_includes')
    if config_obj.has_option(section, 'javascript_includes'):
        report_kwargs['javascript_includes'] = config_obj.get(section,
            'javascript_includes')
    if config_obj.has_option(section, 'header_template'):
        report_kwargs['header_template'] = config_obj.get(section,
            'header_template')
    if config_obj.has_option(section, 'footer_template'):
        report_kwargs['footer_template'] = config_obj.get(section,
            'footer_template')
    if config_obj.has_option(section, 'summary_content_template'):
        report_kwargs['summary_content_template'] = config_obj.get(section,
            'summary_content_template')
    if config_obj.has_option(section, 'summary_page_template'):
        report_kwargs['summary_page_template'] = config_obj.get(section,
            'summary_page_template')
    if config_obj.has_option(section, 'metric_page_template'):
        report_kwargs['metric_page_template'] = config_obj.get(section,
            'metric_page_template')
    if config_obj.has_option(section, 'client_charting_template'):
        report_kwargs['client_charting_template'] = config_obj.get(section,
            'client_charting_template')
    if config_obj.has_option(section, 'diff_client_charting_template'):
        report_kwargs['diff_client_charting_template'] = config_obj.get(section
            , 'diff_client_charting_template')
    if config_obj.has_option(section, 'diff_page_template'):
        report_kwargs['diff_page_template'] = config_obj.get(section,
            'diff_page_template')
    return report_kwargs


def update_remote_vpsa_rate_limit(session, remote_vpsa_id, limit,
    return_type=None, **kwargs):
    """
    Detach a Snapshot Policy from a Volume

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type remote_vpsa_id: str
    :param remote_vpsa_id: Remote VPSA ID

    :type limit: int
    :param limit: New rate limit to set in kb/s

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/remote_vpsas/{0}/rate_limit.json'.format(remote_vpsa_id)
    body_values = {'limit': limit}
    return session.post_api(path=path, body=body_values, return_type=
        return_type, **kwargs)


def pupil_sample_to_psf_sample(pupil_sample, samples, wavelength, efl):
    """Convert pupil sample spacing to PSF sample spacing.

    Parameters
    ----------
    pupil_sample : `float`
        sample spacing in the pupil plane
    samples : `int`
        number of samples present in both planes (must be equal)
    wavelength : `float`
        wavelength of light, in microns
    efl : `float`
        effective focal length of the optical system in mm

    Returns
    -------
    `float`
        the sample spacing in the PSF plane

    """
    return wavelength * efl * 1000.0 / (pupil_sample * samples)


def get_all_ips(instance):
    """ Returns the public and private ip addresses of an AWS EC2 instances
    """
    output = []
    output.append(instance.private_ip_address)
    output.append(instance.public_ip_address)
    return output


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


def reduce(ls: list) ->list:
    """
    cancel out units that appear in both the numerator and denominator, those
    that have no name (_) and those with power of 0
    """
    upper = {**ls[0]}
    lower = {**ls[1]}
    for u in ls[0]:
        if u in ls[1]:
            if upper[u] > lower[u]:
                upper[u] -= lower[u]
                del lower[u]
            elif upper[u] < lower[u]:
                lower[u] -= upper[u]
                del upper[u]
            else:
                del upper[u]
                del lower[u]
    for u in {**upper}:
        if upper[u] == 0 or u == '_':
            del upper[u]
    for u in {**lower}:
        if lower[u] == 0 or u == '_':
            del lower[u]
    return [upper, lower]


def charge_deleted(charge):
    """
    We don't want to display a green check box to mean deleted.
    We use text instead to make sure there is no misinterpretation.
    """
    return 'Yes' if charge.deleted else 'No'


def relative_script(lines):
    """Return a script that'll work in a relocatable environment."""
    activate = (
        "import os; activate_this=os.path.join(os.path.dirname(os.path.realpath(__file__)), 'activate_this.py'); exec(compile(open(activate_this).read(), activate_this, 'exec'), { '__file__': activate_this}); del os, activate_this"
        )
    activate_at = None
    for idx, line in reversed(list(enumerate(lines))):
        if line.split()[:3] == ['from', '__future__', 'import']:
            activate_at = idx + 1
            break
    if activate_at is None:
        activate_at = 1
    return lines[:activate_at] + ['', activate, ''] + lines[activate_at:]


def _partial_parse(state, parser, at):
    """ Parse using only a portion of the input (namely, up to 'at'). """
    use, do_not = state.split(at)
    after = parser(use)
    after = after._replace(effect=after.effect, left_end=do_not.left_end)
    return after


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 _visit_handlers(handlers, visitor, prefix, suffixes):
    """ Use visitor partern to collect information from handlers """
    results = []
    for handler in handlers:
        for suffix in suffixes:
            func = getattr(handler, '{}_{}'.format(prefix, suffix).lower(),
                None)
            if func:
                results.append(visitor(suffix, func))
    return results


@classmethod
def from_rule_tree(cls, tree):
    """From a nested list of (rule, subrules) pairs, build a MagicMatchAny
        instance, recursing down the tree.

        Where there's only one top-level rule, this is returned directly,
        to simplify the nested structure. Returns None if no rules were read.
        """
    rules = []
    for rule, subrules in tree:
        if subrules:
            rule.also = cls.from_rule_tree(subrules)
        rules.append(rule)
    if len(rules) == 0:
        return None
    if len(rules) == 1:
        return rules[0]
    return cls(rules)


def reverse_complement(seq):
    """Creates reverse complement of a DNA string."""
    seq = seq.upper()
    return seq.translate(str.maketrans('ATGCN', 'TACGN'))[::-1]


def statement_passive_verb(stmt_type):
    """Return the passive / state verb form of a statement type.

    Parameters
    ----------
    stmt_type : str
        The lower case string form of a statement type, for instance,
        'phosphorylation'.

    Returns
    -------
    str
        The passive/state verb form of a statement type, for instance,
        'phosphorylated'.
    """
    override = {'complex': 'bound', 'regulateamount': 'amount regulated',
        'decreaseamount': 'decreased', 'increaseamount': 'increased', 'gap':
        'GAP-regulated', 'gef': 'GEF-regulated', 'gtpactivation':
        'GTP-activated', 'influence': 'influenced', 'event': 'happened',
        'conversion': 'converted', 'modification': 'modified',
        'addmodification': 'modified', 'removemodification': 'unmodified',
        'regulateactivity': 'activity regulated'}
    return override.get(stmt_type) if stmt_type in override else stmt_type[:-3
        ] + 'ed'


def provider_parser(subparser):
    """Specify arguments for Gandi Lexicon Provider."""
    subparser.add_argument('--auth-token', help='specify Gandi API key')
    subparser.add_argument('--api-protocol', help=
        '(optional) specify Gandi API protocol to use: rpc (default) or rest')


def p_and_test(p):
    """and_test : not_test
                 | and_test AND not_test
                 | and_test BADAND not_test"""
    if len(p) == 2:
        p[0] = p[1]
    else:
        p[0] = ['MATHOP', 'and', p[1], p[3]]


def get_unique_identifier(item):
    """Return unique item identifier

    The complete format is {database}/{uri}_{channel}:
    * prefixed by "{database}/" only when `item` has a 'database' key.
    * suffixed by "_{channel}" only when `item` has a 'channel' key.

    Parameters
    ----------
    item : dict
        Item as yielded by pyannote.database protocols

    Returns
    -------
    identifier : str
        Unique item identifier
    """
    IDENTIFIER = ''
    database = item.get('database', None)
    if database is not None:
        IDENTIFIER += '{database}/'
    IDENTIFIER += '{uri}'
    channel = item.get('channel', None)
    if channel is not None:
        IDENTIFIER += '_{channel:d}'
    return IDENTIFIER.format(**item)


def _gm(x):
    """Returns the geometric means of the rows in `x`.

    Parameters
    ----------
    x : NumPy array, shape (k,n)
        The k compositions whose geometric means are to be computed.

    Returns
    -------
    x_gm : NumPy array, shape (k,)
        The geometric means for the k compositions in `x`.

    """
    last_axis = -1
    x_gm = x.prod(axis=last_axis) ** (1 / x.shape[last_axis])
    return x_gm


def bid_order_array(market, p, q, reference_price):
    """ make array of orders from array of percents, quantities and reference price """
    i = 0
    orders = list()
    print('bid order array. ref: ' + str(reference_price))
    print(str(p))
    for px in p:
        submit_price = reference_price * (1 - px)
        orders.append([market, 'BUY', submit_price, q[i]])
        i += 1
    return orders


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

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


def get_decimal(value):
    """
    Returns the decimal segment of a number (value after the decimal) as a string
    """
    return str(value).split('.')[1]


def py_static(y, pu, yc):
    """
    Static p-y model developed by Matlock

    Parameters
    ----------------
    y -- displacement
    pu -- ultimate stress
    yc -- ultimate displacement

    Output
    ----------------
    p -- soil resistence pressure
    """
    if y / yc <= 8:
        p = 0.5 * pu * (y / yc) ** (1 / 3)
    else:
        p = pu
    return p


def write_matrix_to_tsv(net, filename=None, df=None):
    """
  This will export the matrix in net.dat or a dataframe (optional df in
  arguments) as a tsv file. Row/column categories will be saved as tuples in
  tsv, which can be read back into the network object.
  """
    import pandas as pd
    if df is None:
        df = net.dat_to_df()
    return df['mat'].to_csv(filename, sep='\t')


def _set_summary_fields(ctx):
    """Sets document summary fields.

    """
    ctx.ext.summary_fields += ctx.doc.acronym, ctx.doc.description


def _check_params(X, metric, p, metric_params):
    """Check the validity of the input parameters"""
    params = zip(['metric', 'p', 'metric_params'], [metric, p, metric_params])
    est_params = X.get_params()
    for param_name, func_param in params:
        if func_param != est_params[param_name]:
            raise ValueError(
                'Got %s for %s, while the estimator has %s for the same parameter.'
                 % (func_param, param_name, est_params[param_name]))


def has_connected_children(bone):
    """ Returns true/false whether a bone has connected children or not.
    """
    t = False
    for b in bone.children:
        t = t or b.use_connect
    return t


def _diff_internal(d1, d2):
    """
        d1 = {'a':'x','b':'y','c':'z'}
        d2 = {'a':'x','b':'u','d':'v'}
        _diff_internal(d1,d2)
        _diff_internald2,d1)
    """
    same = []
    kdiff = []
    vdiff = []
    for key in d1:
        value = d1[key]
        if key in d2:
            if value == d2[key]:
                same.append(key)
            else:
                vdiff.append(key)
        else:
            kdiff.append(key)
    return {'same': same, 'kdiff': kdiff, 'vdiff': vdiff}


def add_symbolic_contents_constraints(namespace):
    """ Add constraints to a namespace that are LinearExpressions of basic
    constraints.

    """
    left = namespace.contents_left
    right = namespace.contents_right
    top = namespace.contents_top
    bottom = namespace.contents_bottom
    namespace.contents_width = right - left
    namespace.contents_height = top - bottom
    namespace.contents_v_center = bottom + namespace.contents_height / 2.0
    namespace.contents_h_center = left + namespace.contents_width / 2.0


@classmethod
def fromrgb(cls, r, g, b, a=1.0):
    """
		Create a :class:`Color` object from the red, green, blue and alpha values
		``r``, ``g``, ``b`` and ``a``. All values will be clipped to the range
		[0; 1].
		"""
    return cls(255 * r, 255 * g, 255 * b, 255 * a)


@classmethod
def get(cls, project_id, feature_name):
    """Retrieve a single feature

        Parameters
        ----------
        project_id : str
            The ID of the project the feature is associated with.
        feature_name : str
            The name of the feature to retrieve

        Returns
        -------
        feature : Feature
            The queried instance
        """
    path = cls._build_url(project_id, feature_name)
    return cls.from_location(path)


def target_move_down():
    """Move particle target down in the list

    """
    pass


def time_convert(x):
    """ converts hh:mm:ss to seconds """
    h, m, s = map(int, x.decode().split(':'))
    return (h * 60 + m) * 60 + s


def remove_bucket(resource, bucket_name):
    """Remove a bucket."""
    response = resource.Bucket(bucket_name).delete()
    return response


def classinit_sound_quantizer(cls):
    """
        Decorator that adds the static quantizer table to class *cls*.
        """
    cls._quantizer = [0] * 256
    for i in range(1, 129):
        cls._quantizer[-i] = cls._quantizer[i] = i.bit_length()
    return cls


def getuser():
    """
    Function to get the username from the environment or password database.

    First try various environment variables, then the password
    database.  This works on Windows as long as USERNAME is set.

    @return username
    @rtype str
    """
    import os
    for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
        user = os.environ.get(name)
        if user:
            return user
    import pwd
    return pwd.getpwuid(os.getuid())[0]


@classmethod
def printInfo(cls):
    """ Simple function (mainly for debugging) that prints basic
        information about this Domain. """
    print('Domain: %s' % cls._name)
    print('     objects: %s' % len(cls._objects))
    print('   protocols: %s' % len(cls._protocols))
    print('     viewers: %s' % len(cls._viewers))
    print('     wizards: %s' % len(cls._wizards))


@classmethod
def _builddefn(cls, defn, args):
    """Parse an alias definition into a tree and marks substitutions

        This function marks alias argument references as ``_aliasarg``. The
        parsing rule is provided by ``_parse()``.

        ``args`` is a list of alias argument names, or None if the alias
        is declared as a symbol.

        >>> from . import pycompat
        >>> parsemap = {
        ...     b'$1 or foo': (b'or', (b'symbol', b'$1'), (b'symbol', b'foo')),
        ...     b'$1 or $bar':
        ...         (b'or', (b'symbol', b'$1'), (b'symbol', b'$bar')),
        ...     b'$10 or baz':
        ...         (b'or', (b'symbol', b'$10'), (b'symbol', b'baz')),
        ...     b'"$1" or "foo"':
        ...         (b'or', (b'string', b'$1'), (b'string', b'foo')),
        ... }
        >>> class aliasrules(basealiasrules):
        ...     _parse = staticmethod(parsemap.__getitem__)
        ...     _trygetfunc = staticmethod(lambda x: None)
        >>> builddefn = aliasrules._builddefn
        >>> def pprint(tree):
        ...     s = prettyformat(tree, (b'_aliasarg', b'string', b'symbol'))
        ...     print(pycompat.sysstr(s))
        >>> args = [b'$1', b'$2', b'foo']
        >>> pprint(builddefn(b'$1 or foo', args))
        (or
          (_aliasarg '$1')
          (_aliasarg 'foo'))
        >>> try:
        ...     builddefn(b'$1 or $bar', args)
        ... except error.ParseError as inst:
        ...     print(pycompat.sysstr(parseerrordetail(inst)))
        invalid symbol '$bar'
        >>> args = [b'$1', b'$10', b'foo']
        >>> pprint(builddefn(b'$10 or baz', args))
        (or
          (_aliasarg '$10')
          (symbol 'baz'))
        >>> pprint(builddefn(b'"$1" or "foo"', args))
        (or
          (string '$1')
          (string 'foo'))
        """
    tree = cls._parse(defn)
    if args:
        args = set(args)
    else:
        args = set()
    return cls._relabelargs(tree, args)


def to_upper(string):
    """The upper case version of a string"""
    return string.upper()


def dbh___default(path, contenttype, extension, roottag, nsurl):
    """ Default Handler - Responds Default for All """
    return 'db_default'


def latex(input):
    """Create the latex output version of the input."""
    if isinstance(input, float):
        input = '%.4f' % input
        return '{' + str(input) + '}'
    elif isinstance(input, int):
        return '{' + str(input) + '}'
    elif isinstance(input, dict):
        return str(input).replace('{', '').replace('}', '').replace("'", ''
            ).replace('_', '')
    else:
        return ''


def begin():
    """
        Start a new transaction.
        """


def pad_name(text, pad_length):
    """Pad text to the pad length with the character."""
    if len(text) % 2 == 0:
        return '{:^{length}}'.format(' ' + text, length=pad_length)
    else:
        return '{:^{length}}'.format(text, length=pad_length)


def map_attr(attr, keys, values, fg):
    """Map the values to the `attr` attribute of elements in fg.

    If keys are singletons, assumes that they are nodes. In all other cases,
    assumes they are edges.
    """
    assert len(keys) == len(values)
    if len(tuple(keys[0])) == 1:
        for node, value in zip(keys, values):
            fg.nodes[node][attr] = value
    else:
        for edge, value in zip(keys, values):
            fg.edges[edge][attr] = value


@classmethod
def _get_doc(cls):
    """Return documentary of class

        By default it returns docstring of class, but it can be overridden
        for example for cases like merging own docstring with parent
        """
    return cls.__doc__


def mk_pat_db_internal(inputFilePath, outputFilePath):
    """
        Generate ``g_pattern_database[]`` declaration header file.
    """
    with open(inputFilePath, 'r') as fin:
        with open(outputFilePath, 'w') as fout:
            fout.write('static char const g_pattern_database[] =\n')
            for line in fin:
                fout.write('"%s\\n"\n' % line.strip('\n'))
            fout.write(';\n')


def remove_dollars(text):
    """remove dollars from start/end of text"""
    while text.startswith('$'):
        text = text[1:]
    while text.endswith('$'):
        text = text[0:-1]
    return text


def repository_enabled_for_checks(repository, consistency):
    """
    Given a repository name and a consistency configuration dict, return whether the repository
    is enabled to have consistency checks run.
    """
    if not consistency.get('check_repositories'):
        return True
    return repository in consistency['check_repositories']


def add(key, value):
    """ Add the key and value, not overwriting any previous value. """


@staticmethod
def _eval_expectation(command, response, future):
    """Evaluate the response from Redis to see if it matches the expected
        response.

        :param command: The command that is being evaluated
        :type command: tredis.client.Command
        :param bytes response: The response value to check
        :param future: The future representing the execution of the command
        :type future: tornado.concurrent.Future
        :return:
        """
    if isinstance(command.expectation, int) and command.expectation > 1:
        future.set_result(response == command.expectation or response)
    else:
        future.set_result(response == command.expectation)


def _add_reprozip_merge_arguments(parser):
    """Add arguments to `parser` for sub-command `reprozip-merge`."""
    p = parser
    p.add_argument('outfile', help='Filepath to merged pack file.')
    p.add_argument('pack_files', nargs='+', help='Pack files to merge.')


def _is_sunder(name):
    """Returns True if a _sunder_ name, False otherwise."""
    return name[0] == name[-1] == '_' and name[1:2] != '_' and name[-2:-1
        ] != '_' and len(name) > 2


def mat2L(edge_matrix):
    """
    Convert a matrix denoting network connectivity (edges or flows) to a list
    denoting edges

    Parameters
    ----------
    edge_matrix   : array
                    where rows denote network edge origins, columns denote
                    network edge destinations, and non-zero entries denote the
                    existence of an edge between a given origin and destination

    Returns
    -------
     edge_list    : list
                    of tuples where each tuple is of the form (o,d) where o is an
                    origin id and d is a destination id

    """
    if len(edge_matrix.shape) != 2:
        raise AttributeError(
            'Matrix of network edges should be two dimensionswith edge origins on one axis and edge destinations on thesecond axis with non-zero matrix entires denoting an edgebetween and origin and destination'
            )
    edge_list = []
    rows, cols = edge_matrix.shape
    for row in range(rows):
        for col in range(cols):
            if edge_matrix[row, col] != 0:
                edge_list.append((row, col))
    return edge_list


def delete_change_set(ChangeSetName=None, StackName=None):
    """
    Deletes the specified change set. Deleting change sets ensures that no one executes the wrong change set.
    If the call successfully completes, AWS CloudFormation successfully deleted the change set.
    See also: AWS API Documentation

    :example: response = client.delete_change_set(
        ChangeSetName='string',
        StackName='string'
    )

    :type ChangeSetName: string
    :param ChangeSetName: [REQUIRED]
            The name or Amazon Resource Name (ARN) of the change set that you want to delete.

    :type StackName: string
    :param StackName: If you specified the name of a change set to delete, specify the stack name or ID (ARN) that is associated with it.

    :rtype: dict
    :return: {}

    """
    pass


def col_fill_nan(data, cols, fill_with=0):
    """
    Fills nans in a specific column or a range of
    columns, using np.isnull() through pandas.

    This is for the cases where some nans are dropped,
    but some nans are converted in to zero (or other)
    first.

    """
    if data[cols].dtype == 'O':
        fill_with = str(fill_with)
    if isinstance(cols, list) is False:
        cols = [cols]
    for col in cols:
        cols = [cols]
        data = data[col].fillna(fill_with)
    return data


def _get_type_name(type_name) ->str:
    """Mypy API of type name has changed from callable to property."""
    return type_name() if callable(type_name) else type_name


@staticmethod
def delete_alarm(alarm_id):
    """Delete an alarm and its history data."""


def validate_arn(arn: str) ->bool:
    """Returns true if the provided ARN appears to follow the expected structure of an ARN."""
    arn_arr = arn.split(':')
    if len(arn_arr) < 6:
        return False
    if arn_arr[0] != 'arn':
        return False
    return True


def get_is_ntuples(dic):
    """
    Determine data class from dic : XYDATA or NTUPLES
    """
    is_ntuples = False
    try:
        dataclass = dic['DATACLASS'][0]
        if dataclass.strip() == 'NTUPLES':
            is_ntuples = True
    except KeyError:
        pass
    return is_ntuples


def _sans_ext(path):
    """
    Removes the file extension.
    This differs from Path.stem, which returns the final path component
    stripped of its extension. This returns the full path stripped of its
    extension.

    >>> Path('a/b.c').sans_ext()
    PosixPath('a/b')

    """
    return path.parent / path.stem


def ExtractName(names, default=None):
    """
     Extract "name" field from XML entries.
     @param names : XML entry
     @default : if it fails to extract from the designated XML entry, return the default value ("None").
     @return default or the name extracted
    """
    if len(names) == 1:
        return names[0].getcontent()
    else:
        for name in names:
            if name.getLcId() == 1033:
                return name.getcontent()
    return default


def basis_function_ders(degree, knot_vector, span, knot, order):
    """ Computes derivatives of the basis functions for a single parameter.

    Implementation of Algorithm A2.3 from The NURBS Book by Piegl & Tiller.

    :param degree: degree, :math:`p`
    :type degree: int
    :param knot_vector: knot vector, :math:`U`
    :type knot_vector: list, tuple
    :param span: knot span, :math:`i`
    :type span: int
    :param knot: knot or parameter, :math:`u`
    :type knot: float
    :param order: order of the derivative
    :type order: int
    :return: derivatives of the basis functions
    :rtype: list
    """
    left = [(1.0) for _ in range(degree + 1)]
    right = [(1.0) for _ in range(degree + 1)]
    ndu = [[(1.0) for _ in range(degree + 1)] for _ in range(degree + 1)]
    for j in range(1, degree + 1):
        left[j] = knot - knot_vector[span + 1 - j]
        right[j] = knot_vector[span + j] - knot
        saved = 0.0
        r = 0
        for r in range(r, j):
            ndu[j][r] = right[r + 1] + left[j - r]
            temp = ndu[r][j - 1] / ndu[j][r]
            ndu[r][j] = saved + right[r + 1] * temp
            saved = left[j - r] * temp
        ndu[j][j] = saved
    ders = [[(0.0) for _ in range(degree + 1)] for _ in range(min(degree,
        order) + 1)]
    for j in range(0, degree + 1):
        ders[0][j] = ndu[j][degree]
    a = [[(1.0) for _ in range(degree + 1)] for _ in range(2)]
    for r in range(0, degree + 1):
        s1 = 0
        s2 = 1
        a[0][0] = 1.0
        for k in range(1, order + 1):
            d = 0.0
            rk = r - k
            pk = degree - k
            if r >= k:
                a[s2][0] = a[s1][0] / ndu[pk + 1][rk]
                d = a[s2][0] * ndu[rk][pk]
            if rk >= -1:
                j1 = 1
            else:
                j1 = -rk
            if r - 1 <= pk:
                j2 = k - 1
            else:
                j2 = degree - r
            for j in range(j1, j2 + 1):
                a[s2][j] = (a[s1][j] - a[s1][j - 1]) / ndu[pk + 1][rk + j]
                d += a[s2][j] * ndu[rk + j][pk]
            if r <= pk:
                a[s2][k] = -a[s1][k - 1] / ndu[pk + 1][r]
                d += a[s2][k] * ndu[r][pk]
            ders[k][r] = d
            j = s1
            s1 = s2
            s2 = j
    r = float(degree)
    for k in range(1, order + 1):
        for j in range(0, degree + 1):
            ders[k][j] *= r
        r *= degree - k
    return ders


def islist(value):
    """Report whether the given value is a sequence."""
    return isinstance(value, (list, tuple))


def p_import_from_plus_1(p):
    """import_from_plus : DOT"""
    p[0] = 1


def combine_tilechains(tilechain_list):
    """
    Function which takes a tilechain_list as exported by combine_multiple_tiles()
    :param tilechain_list:
    :return:
    """
    combined_tcs = []
    for i in tilechain_list:
        combined_tcs = [*combined_tcs, *i]
    return combined_tcs


@staticmethod
def _get_Id(Id, L):
    """parse the IdL or IdR argument of __init__"""
    if Id is None:
        return [None] * (L + 1)
    else:
        try:
            return list(Id)
        except TypeError:
            return [Id] * (L + 1)


def command_error_fmt(cmd_name, exception):
    """Format error message given command and exception."""
    return 'pyleus {0}: error: {1}'.format(cmd_name, str(exception))


def LOG10(number):
    """
    Calculates the log base 10 of a number and returns the result as a double.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/log10/
    for more details
    :param number: The number or field of number
    :return: Aggregation operator
    """
    return {'$log10': number}


@classmethod
def get_asset_and_components(cls, session, asset_key):
    """Get information about individual asset & its components
        Component may be a PSU that belongs to a server or PDU outlets

        Args:
            session: database session
            asset_key(int): query by key

        Returns:
            dict: asset details with it's 'labels' and components as 'children' (sorted by key)
        """
    results = session.run(
        """
            MATCH (n:Asset { key: $key }) OPTIONAL MATCH (n)-[:HAS_COMPONENT]->(c)
            RETURN n as asset, labels(n) as labels, collect(c) as children
            """
        , key=int(asset_key))
    record = results.single()
    asset = dict(record['asset'])
    asset['labels'] = record['labels']
    children = []
    if record['children']:
        children = sorted(list(map(lambda x: x['key'], record['children'])))
    asset['children'] = children
    return asset


@classmethod
def _get_arguments(cls, data, max_args=-1):
    """Parse data into a list of arguments.

        Any un-parsed arguments (either because max was reached or because a
        delimiter was opened and not closed) will be returned as the last
        element of the resulting list.

        :param str data: The data to be broken down into arguments
        :param int max_args: The maximum number of arguments to parse,
                             if less than zero, all arguments are parsed
        :returns list: The parsed arguments

        """
    args = []
    while data and max_args != 0:
        arg, data = cls._one_argument(data)
        if arg:
            args.append(arg)
        if max_args > 0:
            max_args -= 1
    if data:
        args.append(data)
    return args


def authorize_security_group_egress(DryRun=None, GroupId=None,
    SourceSecurityGroupName=None, SourceSecurityGroupOwnerId=None,
    IpProtocol=None, FromPort=None, ToPort=None, CidrIp=None, IpPermissions
    =None):
    """
    [EC2-VPC only] Adds one or more egress rules to a security group for use with a VPC. Specifically, this action permits instances to send traffic to one or more destination IPv4 or IPv6 CIDR address ranges, or to one or more destination security groups for the same VPC. This action doesn't apply to security groups for use in EC2-Classic. For more information, see Security Groups for Your VPC in the Amazon Virtual Private Cloud User Guide . For more information about security group limits, see Amazon VPC Limits .
    Each rule consists of the protocol (for example, TCP), plus either a CIDR range or a source group. For the TCP and UDP protocols, you must also specify the destination port or port range. For the ICMP protocol, you must also specify the ICMP type and code. You can use -1 for the type or code to mean all types or all codes.
    Rule changes are propagated to affected instances as quickly as possible. However, a small delay might occur.
    See also: AWS API Documentation

    :example: response = client.authorize_security_group_egress(
        DryRun=True|False,
        GroupId='string',
        SourceSecurityGroupName='string',
        SourceSecurityGroupOwnerId='string',
        IpProtocol='string',
        FromPort=123,
        ToPort=123,
        CidrIp='string',
        IpPermissions=[
            {
                'IpProtocol': 'string',
                'FromPort': 123,
                'ToPort': 123,
                'UserIdGroupPairs': [
                    {
                        'UserId': 'string',
                        'GroupName': 'string',
                        'GroupId': 'string',
                        'VpcId': 'string',
                        'VpcPeeringConnectionId': 'string',
                        'PeeringStatus': 'string'
                    },
                ],
                'IpRanges': [
                    {
                        'CidrIp': 'string'
                    },
                ],
                'Ipv6Ranges': [
                    {
                        'CidrIpv6': 'string'
                    },
                ],
                'PrefixListIds': [
                    {
                        'PrefixListId': 'string'
                    },
                ]
            },
        ]
    )

    :type DryRun: boolean
    :param DryRun: Checks whether you have the required permissions for the action, without actually making the request, and provides an error response. If you have the required permissions, the error response is DryRunOperation . Otherwise, it is UnauthorizedOperation .

    :type GroupId: string
    :param GroupId: [REQUIRED]
            The ID of the security group.

    :type SourceSecurityGroupName: string
    :param SourceSecurityGroupName: The name of a destination security group. To authorize outbound access to a destination security group, we recommend that you use a set of IP permissions instead.

    :type SourceSecurityGroupOwnerId: string
    :param SourceSecurityGroupOwnerId: The AWS account number for a destination security group. To authorize outbound access to a destination security group, we recommend that you use a set of IP permissions instead.

    :type IpProtocol: string
    :param IpProtocol: The IP protocol name or number. We recommend that you specify the protocol in a set of IP permissions instead.

    :type FromPort: integer
    :param FromPort: The start of port range for the TCP and UDP protocols, or an ICMP type number. We recommend that you specify the port range in a set of IP permissions instead.

    :type ToPort: integer
    :param ToPort: The end of port range for the TCP and UDP protocols, or an ICMP type number. We recommend that you specify the port range in a set of IP permissions instead.

    :type CidrIp: string
    :param CidrIp: The CIDR IPv4 address range. We recommend that you specify the CIDR range in a set of IP permissions instead.

    :type IpPermissions: list
    :param IpPermissions: A set of IP permissions. You can't specify a destination security group and a CIDR IP address range.
            (dict) --Describes a security group rule.
            IpProtocol (string) --The IP protocol name (tcp , udp , icmp ) or number (see Protocol Numbers ).
            [EC2-VPC only] Use -1 to specify all protocols. When authorizing security group rules, specifying -1 or a protocol number other than tcp , udp , icmp , or 58 (ICMPv6) allows traffic on all ports, regardless of any port range you specify. For tcp , udp , and icmp , you must specify a port range. For 58 (ICMPv6), you can optionally specify a port range; if you don't, traffic for all types and codes is allowed when authorizing rules.
            FromPort (integer) --The start of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 type number. A value of -1 indicates all ICMP/ICMPv6 types.
            ToPort (integer) --The end of port range for the TCP and UDP protocols, or an ICMP/ICMPv6 code. A value of -1 indicates all ICMP/ICMPv6 codes for the specified ICMP type.
            UserIdGroupPairs (list) --One or more security group and AWS account ID pairs.
            (dict) --Describes a security group and AWS account ID pair.
            UserId (string) --The ID of an AWS account. For a referenced security group in another VPC, the account ID of the referenced security group is returned.
            [EC2-Classic] Required when adding or removing rules that reference a security group in another AWS account.
            GroupName (string) --The name of the security group. In a request, use this parameter for a security group in EC2-Classic or a default VPC only. For a security group in a nondefault VPC, use the security group ID.
            GroupId (string) --The ID of the security group.
            VpcId (string) --The ID of the VPC for the referenced security group, if applicable.
            VpcPeeringConnectionId (string) --The ID of the VPC peering connection, if applicable.
            PeeringStatus (string) --The status of a VPC peering connection, if applicable.

            IpRanges (list) --One or more IPv4 ranges.
            (dict) --Describes an IPv4 range.
            CidrIp (string) --The IPv4 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv4 address, use the /32 prefix.

            Ipv6Ranges (list) --[EC2-VPC only] One or more IPv6 ranges.
            (dict) --[EC2-VPC only] Describes an IPv6 range.
            CidrIpv6 (string) --The IPv6 CIDR range. You can either specify a CIDR range or a source security group, not both. To specify a single IPv6 address, use the /128 prefix.

            PrefixListIds (list) --(Valid for AuthorizeSecurityGroupEgress , RevokeSecurityGroupEgress and DescribeSecurityGroups only) One or more prefix list IDs for an AWS service. In an AuthorizeSecurityGroupEgress request, this is the AWS service that you want to access through a VPC endpoint from instances associated with the security group.
            (dict) --The ID of the prefix.
            PrefixListId (string) --The ID of the prefix.

    """
    pass


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

        :param SharedContentCopyType val:
        :rtype: EventType
        """
    return cls('shared_content_copy', val)


def add_to_scene_history(current_scene_db, timestamp, notebook, library,
    outputpath):
    """adds a notebook to the scene history"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(current_scene_db)
    cur = conn.cursor()
    add_to_scene_history = (
        'INSERT INTO "History"(Timestamp, Notebook, Library, OutputPath) VALUES (?,?,?, ?)'
        )
    cur.execute(add_to_scene_history, (timestamp, notebook, library,
        outputpath))
    conn.commit()
    conn.close()


def return_elem_or_list(args):
    """Utility function to get a single element if len(args) == 1.

    Args:
        * args: A list of args.

    Returns:
        If args contains only one item, returns a single element.
        Else, returns args.
    """
    return args[0] if len(args) == 1 else args


def assign_exit_code(opt_succeeded, gulp_errors, parser_errors,
    single_point_only):
    """ given the error messages, assign an exit code """
    if '**** Too many failed attempts to optimise ****' in gulp_errors:
        return 'ERROR_OPTIMISE_MAX_ATTEMPTS'
    elif '**** Maximum number of function calls has been reached ****' in gulp_errors:
        return 'ERROR_OPTIMISE_MAX_CALLS'
    elif opt_succeeded is False and not single_point_only:
        return 'ERROR_OPTIMISE_UNSUCCESFUL'
    elif gulp_errors:
        return 'ERROR_GULP_UNHANDLED'
    elif parser_errors:
        return 'ERROR_PARSING_STDOUT'
    elif opt_succeeded is None and not single_point_only:
        return 'ERROR_GULP_UNHANDLED'
    return None


@classmethod
def sensible_default(cls, num_workers: int, dimension: int) ->'Pruning':
    """ Very conservative pruning
        - keep at least 100 elements, or 7 times num_workers, whatever is biggest
        - keep at least 3 x min_len, or up to 10 x min_len if it does not exceed 1gb of data

        Parameters
        ----------
        num_workers: int
            number of evaluations which will be run in parallel at once
        dimension: int
            dimension of the optimization space
        """
    min_len = max(100, 7 * num_workers)
    max_len_1gb = 1024 ** 3 // (dimension * 8 * 2)
    max_len = max(3 * min_len, min(10 * min_len, max_len_1gb))
    return cls(min_len, max_len)


@staticmethod
def get_solver_name_from_document_id(solver_document_id: str) ->str:
    """Retrieve solver name from solver's document id."""
    return solver_document_id.rsplit('-', maxsplit=1)[0]


@staticmethod
def create_authentication_from_json(values):
    """Create authentication object from a JSON dict."""
    key_id = values.get('publicKey')
    authentication_type = values.get('type')
    if not key_id:
        raise ValueError(
            f'Invalid authentication definition, "publicKey" is missing: {values}'
            )
    authentication = {'type': authentication_type, 'publicKey': key_id}
    return authentication


def _get_lines(filepath):
    """ Given a filepath, return a list of lines within that file. """
    lines = None
    with open(filepath) as file:
        lines = file.readlines()
    return lines


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

        Args:
            raw_str (Text): The text to parse, as a unicode string.
            parser (:class:`apacheconfig.ApacheConfigParser`): specify the
                parser to use. Can be created by ``native_apache_parser()``.
        Returns:
            :class:`apacheconfig.LeafNode` containing metadata parsed from
            ``raw_str``.
        """
    raw = parser.parse(raw_str)
    return cls(raw[1])


def encode_transition(transition):
    """
    Generate a key string from a transition.

    Both integer and string transition descriptions are handled.
    """
    upper, lower = transition
    upper = str(upper).lower()
    lower = str(lower).lower()
    return '{} -> {}'.format(upper, lower)


def calc_P(elev, seaLevelPressure=101325):
    """
    Compute surface pressure at a particular altitude given a sea level pressure

    elev: meters
    seaLevelPressure: pa
    """
    g = 9.80665
    T0 = 288.15
    L = -0.0065
    M = 0.0289644
    R = 8.3144598
    value = seaLevelPressure * (T0 / (T0 + L * elev)) ** (g * M / (R * L))
    return value


def items(request):
    """
        Called when a items retrieval request has been received.

        @param request: The publish-subscribe request.
        @type request: L{wokkel.pubsub.PubSubRequest}
        @return: A deferred that fires with a C{list} of L{pubsub.Item}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


@staticmethod
def _transform_data(data: dict) ->dict:
    """
        Each CloudStack API call returns a nested dictionary structure. The first level contains only one key indicating
        the API that originated the response. This function removes that first level from the data returned to the
        caller.

        :param data: Response of the API call
        :type data: dict
        :return: Simplified response without the information about the API that originated the response.
        :rtype: dict
        """
    for key in data.keys():
        return_value = data[key]
        if isinstance(return_value, dict):
            return return_value
    return data


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

        :param PaperPublishedLinkCreateDetails val:
        :rtype: EventDetails
        """
    return cls('paper_published_link_create_details', val)


@classmethod
def get_by_id(cls, context, chassis_id):
    """Find a chassis based on its integer ID and return a Chassis object.

        :param cls: the :class:`Chassis`
        :param context: Security context
        :param chassis_id: the ID of a chassis.
        :returns: a :class:`Chassis` object.
        """
    db_chassis = cls.dbapi.get_chassis_by_id(chassis_id)
    chassis = cls._from_db_object(context, cls(), db_chassis)
    return chassis


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 not_found(environ, start_response):
    """Default WSGI 404 app."""
    start_response('404 Not Found', [('Content-Type', 'text/plain')])
    return [
        '404 Not Found\n\nThe server has not found anything matching the Request-URI.'
        ]


def handle_byte_timeout(arg):
    """
    Функция обработки тайм аута приема байта.

    :type arg: int
    :param arg: код таймаута

    :rtype: float
    :return: время в секундах
    """
    if 0 <= arg <= 150:
        return arg * 0.001
    elif 151 <= arg <= 249:
        return (arg - 149) * 0.15
    elif 250 <= arg <= 255:
        return (arg - 248) * 15.0
    else:
        return -1


def _parse_epsilon(line, lines):
    """Parse Energy [eV] Re_eps_xx     Im_eps_xx     Re_eps_zz     Im_eps_zz"""
    split_line = line.split()
    energy = float(split_line[0])
    re_eps_xx = float(split_line[1])
    im_eps_xx = float(split_line[2])
    re_eps_zz = float(split_line[3])
    im_eps_zz = float(split_line[4])
    return {'energy': energy, 're_eps_xx': re_eps_xx, 'im_eps_xx':
        im_eps_xx, 're_eps_zz': re_eps_zz, 'im_eps_zz': im_eps_zz}


def constructFlagQueryURL(protocol, server, ifo):
    """
    Simple url construction method for dqsegdb server flag queries.

    Parameters
    ----------
    protocol : `string`
        Ex: 'https'
    server : `string`
        Ex: 'dqsegdb5.phy.syr.edu'
    ifo : `string`
        Ex: 'L1'
    """
    url1 = protocol + '://' + server + '/dq'
    url2 = '/'.join([url1, ifo])
    return url2


def title_or_id():
    """Return the title if it is not blank and the id otherwise.
        """


def bits_to_ip(bits):
    """
    Returns an IP when provided 32 bits
    :param bits: str ("11000000101010000000000000010111")
    :return: str ("192.168.0.23")
    """
    value = 128
    current = 1
    octet = {'1': '0', '2': '0', '3': '0', '4': '0'}
    for x in range(0, 32):
        if bits[x] == '1':
            octet[str(current)] = int(octet[str(current)]) + value
        if value == 1:
            value = 128
            current += 1
            continue
        value = value / 2
    return str(int(octet['1'])) + '.' + str(int(octet['2'])) + '.' + str(int
        (octet['3'])) + '.' + str(int(octet['4']))


def get_lang(l):
    """Convert language abbr to full names"""
    l = l.strip().lower()
    h = dict(es='spanish', en='english', ar='arabic', it='italian', de='german'
        )
    return h.get(l, l)


def display2classmethod(display):
    """Opposite of classmethod2display.
    """
    L = display.split(' -> ')
    return L[0], L[1]


def is_module(node):
    """Returns whether node is a module node."""
    return node.__class__.__name__ == 'Module'


@staticmethod
def compose_locale(language_code, country_code=None):
    """
        Return the string representation of the locale specified with a ISO
        639-3 alpha-3 code (or alpha-2 code), optionally followed by a dash
        character `-` and a ISO 3166-1 alpha-2 code.

        :param language_code: a ISO 639-3 alpha-3 code (or alpha-2 code).

        :param country_code: a ISO 3166-1 alpha-2 code.

        :return: a string representing a locale.
        """
    return (language_code if country_code is None else
        f'{language_code}-{country_code}')


def _escape_arg(arg):
    """Escape a command line argument for an HTCondor submit file."""
    arg = arg.replace('"', '""').replace("'", "''")
    if ' ' in arg or '\t' in arg:
        arg = "'" + arg + "'"
    return arg


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


def parse_excel_row(row):
    """
    Parse a row in the sheet and return the data.
    """
    number = row[0].value
    title = row[2].value
    doctype = row[1].value
    return number, title, doctype


def af_fade(cutin, cutout, fadein, fadeout):
    """
    Genterate FFmpeg audio fade filter string
    https://ffmpeg.org/ffmpeg-filters.html#afade
    :param cutin: (number) position in the original audio where segment starts
    :param cutout: (number) position in the original audio where segment ends
    :param fadein: (number) length of audio where fade-in applied, in sec
    :param fadeout: (number) length of audio where fade-out applied, in sec
    :return: (str) ffmpeg audio filter string
    """
    a = cutin, fadein, cutout - fadeout, fadeout
    return 'afade=t=in:st={}:d={},afade=t=out:st={}:d={}'.format(*a)


def getSubModuleInfos():
    """Get module infos for any sub modules.

        In a module, this will always return an empty list.
        """


def _get_fig_and_ax(fig):
    """Get figure and current ax. Input can be either a figure or an ax."""
    import matplotlib.pyplot as plt
    if isinstance(fig, plt.Axes):
        ax = fig
        fig = ax.figure
    elif isinstance(fig, plt.Figure):
        ax = fig.gca()
    else:
        raise ValueError('fig should be a matplotlib Figure or Axes instance.')
    return fig, ax


def apply_ROI(data, logfile, top=0, left=0, right=None, bottom=None):
    """
    Apply an ROI to an image or a series of images.

    Args:
        data (2D or 3D array): The source data.
        top (int): the index of the top edge of the ROI.
        left (int): the index of the left edge of the ROI.
        right (int): the index of the right edge of the ROI.
        bottom (int): the index of the bottom edge of the ROI.
    """
    N = len(data.shape)
    if N == 2:
        nx, ny = data.shape
        if right == None:
            right = nx
        if bottom == None:
            bottom = ny
        data_ROI = data[left:right, top:bottom]
    elif N == 3:
        _, nx, ny = data.shape
        if right == None:
            right = nx
        if bottom == None:
            bottom = ny
        data_ROI = data[:, left:right, top:bottom]
    else:
        raise Exception('ROI only defined for 2D and 3D arrays')
    logfile['detector']['ROI_software'] = {}
    logfile['detector']['ROI_software']['top'] = top
    logfile['detector']['ROI_software']['left'] = left
    logfile['detector']['ROI_software']['right'] = right
    logfile['detector']['ROI_software']['bottom'] = bottom
    return data_ROI, logfile


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


@classmethod
def _cachedSqlType(cls):
    """
        Cache the sqlType() into class, because it's heavy used in `toInternal`.
        """
    if not hasattr(cls, '_cached_sql_type'):
        cls._cached_sql_type = cls.sqlType()
    return cls._cached_sql_type


def should_build_with_cython(package, release=None):
    """Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.  If the ``release`` parameter is not specified an attempt is
    made to determine the release flag from `astropy.version`.
    """
    try:
        version_module = __import__(package + '.cython_version', fromlist=[
            'release', 'cython_version'])
    except ImportError:
        version_module = None
    if release is None and version_module is not None:
        try:
            release = version_module.release
        except AttributeError:
            pass
    try:
        cython_version = version_module.cython_version
    except AttributeError:
        cython_version = 'unknown'
    have_cython = False
    try:
        import Cython
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not release or cython_version == 'unknown'):
        return cython_version
    else:
        return False


@classmethod
def get_collection(cls):
    """Return a handle to the database collection for the class"""
    if cls._context_manager.is_draft:
        return getattr(cls.get_db(), '{collection}__draft__'.format(
            collection=cls._collection))
    return getattr(cls.get_db(), cls._collection)


def new():
    """Create a new text data-block

    """
    pass


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def create_provisioning_artifact(AcceptLanguage=None, ProductId=None,
    Parameters=None, IdempotencyToken=None):
    """
    Create a new provisioning artifact for the specified product. This operation will not work with a product that has been shared with you.
    See also: AWS API Documentation

    :example: response = client.create_provisioning_artifact(
        AcceptLanguage='string',
        ProductId='string',
        Parameters={
            'Name': 'string',
            'Description': 'string',
            'Info': {
                'string': 'string'
            },
            'Type': 'CLOUD_FORMATION_TEMPLATE'
        },
        IdempotencyToken='string'
    )

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

    :type ProductId: string
    :param ProductId: [REQUIRED]
            The product identifier.

    :type Parameters: dict
    :param Parameters: [REQUIRED]
            The parameters to use when creating the new provisioning artifact.
            Name (string) --The name assigned to the provisioning artifact properties.
            Description (string) --The text description of the provisioning artifact properties.
            Info (dict) -- [REQUIRED]Additional information about the provisioning artifact properties.
            (string) --
            (string) --

            Type (string) --The type of the provisioning artifact properties.

    :type IdempotencyToken: string
    :param IdempotencyToken: [REQUIRED]
            A token to disambiguate duplicate requests. You can create multiple resources using the same input in multiple requests, provided that you also specify a different idempotency token for each request.
            This field is autopopulated if not provided.

    :rtype: dict
    :return: {
        'ProvisioningArtifactDetail': {
            'Id': 'string',
            'Name': 'string',
            'Description': 'string',
            'Type': 'CLOUD_FORMATION_TEMPLATE',
            'CreatedTime': datetime(2015, 1, 1)
        },
        'Info': {
            'string': 'string'
        },
        'Status': 'AVAILABLE'|'CREATING'|'FAILED'
    }

    :returns:
    (string) --
    (string) --

    """
    pass


@staticmethod
def uncross_reference() ->None:
    """Removes cross-reference links"""
    pass


@staticmethod
def generated_info():
    """
        A string informing the user that a file is automatically generated
        """
    info = 'File automatically generated by tsfpga'
    return info


def group_membership_v1_timeout(group_state: 'GroupState'):
    """
    v1 host timer associated with group GroupState object has expired
    """
    group_state.group_state_logger.debug(
        'NonQuerier MembersPresent: group_membership_v1_timeout')
    return


def op_name(operation):
    """Provide the empty string for anonymous operations."""
    return operation.name.value if operation.name else ''


@classmethod
def fromiter(cls, args, **assumptions):
    """
        Create a new object from an iterable.

        This is a convenience function that allows one to create objects from
        any iterable, without having to convert to a list or tuple first.

        Examples
        ========

        >>> from sympy import Tuple
        >>> Tuple.fromiter(i for i in range(5))
        (0, 1, 2, 3, 4)

        """
    return cls(*tuple(args), **assumptions)


def resolve_order_item_related_set_name(labels):
    """
    Returns a reverse relation manager name to order items for class.
    """
    return ('%sorderitem_set' % labels['model']).lower()


def context_cycle_enum(data_path: str='', reverse: bool=False, wrap: bool=False
    ):
    """Toggle a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param reverse: Reverse, Cycle backwards
    :type reverse: bool
    :param wrap: Wrap, Wrap back to the first/last values
    :type wrap: bool
    """
    pass


def binsizeToResolution(binsize):
    """Return the resolution unit from the bin size

	It is a convenient function to convert binsize into resolution unit.
	It has a support of base (b), kilobase (kb), megabase (mb) and
	gigabase (gb) unit. It also convert binsize to decimal resolution unit as
	shown below in examples.

	Parameters
	----------

	binsize:	int
		bin size

	Returns
	-------
	resolution : str
		resolution unit

	Examples
	--------
		>>> binsizeToResolution(1)
		'1b'
		>>> binsizeToResolution(10)
		'10b'
		>>> binsizeToResolution(10000)
		'10kb'
		>>> binsizeToResolution(100000)
		'100kb'
		>>> binsizeToResolution(125500)
		'125.5kb'
		>>> binsizeToResolution(1000000)
		'1mb'
		>>> binsizeToResolution(1634300)
		'1.6343mb'

	"""
    suffix = {(0): 'b', (1): 'kb', (2): 'mb', (3): 'gb'}
    rest = None
    count = 0
    while 1:
        rest = binsize / 1000 ** count
        if rest >= 1000:
            count += 1
        else:
            break
    if rest - int(rest) == 0:
        resolution = str(int(rest)) + suffix[count]
    else:
        resolution = str(rest) + suffix[count]
    return resolution


def multi_sgd_mom_update(*data, **kwargs):
    """Momentum update function for Stochastic Gradient Descent (SGD) optimizer.

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

    .. math::

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

    It updates the weights using::

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

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

    Defined in src/operator/optimizer_op.cc:L374

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

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

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


def _stack_exists(cf_client, stack_name):
    """Determine if the stack already exists.

    Parameters
    ----------
    stack_name : str
        Name of the stack to find.

    Returns
    -------
    bool
        True if the stack already exists.
    """
    stacks = cf_client.list_stacks()['StackSummaries']
    for stack in stacks:
        if stack['StackStatus'] == 'DELETE_COMPLETE':
            continue
        if stack_name == stack['StackName']:
            return True
    return False


@classmethod
def get(cls, user=None, subject=None, token=None):
    """Fetches a user token.

        :param user:
            User unique ID.
        :param subject:
            The subject of the key. Examples:

            - 'auth'
            - 'signup'
        :param token:
            The existing token needing verified.
        :returns:
            A :class:`UserToken` or None if the token does not exist.
        """
    if user and subject and token:
        return cls.get_key(user, subject, token).get()
    assert subject and token, 'subject and token must be provided to UserToken.get().'
    return cls.query(cls.subject == subject, cls.token == token).get()


def priming(temp, beer_vol, co2):
    """
    Calculate the required weight priming (table) sugar for a given
    volume of beer at a specific temperature for desired CO2 volume.
    Beer temperature should be the temperature that the beer has
    been at the longest.

    From: http://www.straighttothepint.com/priming-sugar-calculator/

    PS = 15.195 * Vbeer * (VCO2 - 3.0378 + (0.050062 * Tferm) -
         (0.00026555 * (Tferm ^ 2))

    :arg temp: Temperature of beer in fahrenheit
    :arg beer_vol: Volume of beer to prime in gallons US
    :arg co2: The volume of CO2 required
    :returns: The amount table sugar required
    """
    return 15.195 * beer_vol * (co2 - 3.0378 + 0.050062 * temp - 0.00026555 *
        temp ** 2)


def footer():
    """
    Return the footer of the LaTeX document.

    :return: LaTeX document footer.
    :rtype: string
    """
    return '\\end{tikzpicture}\n\\end{document}'


def ceildiv(a, b):
    """
    Compute a divided by b and rounded up.
    """
    return -(-a // b)


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 '+'


@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": {
                "fullDisplayName_analyzed": {
                    "type": "text",
                    "index": true
                }
           }
        } """
    return {'items': mapping}


@classmethod
def order_and_label(cls, t):
    """Order and label of a discrete type.

        Helper method for the ternary plots. Implemented only for subclasses of Profile where the initialization
        is made with a dictionary that maps types to voter share, such as :class:`ProfileNoisyDiscrete` or
        :class:`ProfileOrdinal`, but unlike :class:`ProfileHistogram` (where a second dictionary is needed for the
        histograms).

        Parameters
        ----------
        t : object
            A type. Any type that is accepted at a key in the initialization dictionary.

        Returns
        -------
        order : str
            The ranking or weak order.
        label : str
            The label to be used for the corner of the triangle.

        Examples
        --------
            Cf. :meth:`ProfileNoisyDiscrete.order_and_label`.
        """
    raise NotImplementedError


def primitive_uv_sphere_add(segments: int=32, ring_count: int=16, size:
    float=1.0, calc_uvs: bool=False, view_align: bool=False, enter_editmode:
    bool=False, location: float=(0.0, 0.0, 0.0), rotation: float=(0.0, 0.0,
    0.0), layers: bool=(False, False, False, False, False, False, False,
    False, False, False, False, False, False, False, False, False, False,
    False, False, False)):
    """Construct a UV sphere mesh

    :param segments: Segments
    :type segments: int
    :param ring_count: Rings
    :type ring_count: int
    :param size: Size
    :type size: float
    :param calc_uvs: Generate UVs, Generate a default UV map
    :type calc_uvs: bool
    :param view_align: Align to View, Align the new object to the view
    :type view_align: bool
    :param enter_editmode: Enter Editmode, Enter editmode when adding this object
    :type enter_editmode: bool
    :param location: Location, Location for the newly added object
    :type location: float
    :param rotation: Rotation, Rotation for the newly added object
    :type rotation: float
    :param layers: Layer
    :type layers: bool
    """
    pass


def set_debug(debugging):
    """Sets the package testing mode.
    """
    global debug
    debug = debugging


@staticmethod
def p_a2ml_taggedunion_member_list(p):
    """a2ml_taggedunion_member_list : a2ml_taggedunion_member
                                        | a2ml_taggedunion_member a2ml_taggedunion_member_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def _check_agent_token_prior_to_agent_reboot(driver_internal_info):
    """Removes the agent token if it was not pregenerated.

    Removal of the agent token in cases where it is not pregenerated
    is a vital action prior to rebooting the agent, as without doing
    so the agent will be unable to establish communication with
    the ironic API after the reboot. Effectively locking itself out
    as in cases where the value is not pregenerated, it is not
    already included in the payload and must be generated again
    upon lookup.

    :param driver_internal_info: The driver_interal_info dict object
                                 from a Node object.
    """
    if not driver_internal_info.get('agent_secret_token_pregenerated', False):
        driver_internal_info.pop('agent_secret_token', None)


def query_datetime(datetime_value, query):
    """Checks the datetime_value against the query provided.

    The query format is similar to that of MongoDB BSON comparison operators.
    It uses `$eq`, `$gt`, `$gte`, `$lt`, `$lte` and `$ne`. Combine these operators together in a dictionary
    to provide the datetime checking functionality. This is currently used when finding files from Amazon S3, but
    could possibly be used in other areas.

    :param datetime.datetime datetime_value: The datetime value used to check against the query
    :param dict query: The query parameters used to check against the datetime_value
    :return boolean: True if all comparison operators pass, else False
    """
    if '$lte' in query and datetime_value > query['$lte']:
        return False
    elif '$lt' in query and datetime_value >= query['$lt']:
        return False
    elif '$gte' in query and datetime_value < query['$gte']:
        return False
    elif '$gt' in query and datetime_value <= query['$gt']:
        return False
    elif '$eq' in query and datetime_value != query['$eq']:
        return False
    elif '$ne' in query and datetime_value == query['$ne']:
        return False
    return True


def nested_lookup(dictionary, *entry):
    """get a nested entry from a dictionary"""
    try:
        if isinstance(entry, str):
            v = dictionary[entry]
        else:
            v = None
            for e in entry:
                v = v[e] if v is not None else dictionary[e]
    except:
        raise Exception("could not find entry '" + '/'.join(list(entry)) +
            "' in the dictionary")
    return v


def round_to_base(x, base=0.1):
    """ round a number to a specified base

    Parameters
    ----------
    x: float
    base: float

    Returns
    -------
    rounded: float

    Examples
    --------
    >>> round_to_base(21, base=1)
    21.0
    >>> round_to_base(21, base=6)
    24.0
    >>> round_to_base(21, base=.8)
    20.8
    >>> round_to_base(1.1234567, base=1e-5)
    1.12346
    >>> round_to_base(1.1234567, base=0.06)
    1.14

    """
    return float(round(base * round(float(x) / base), len(str(round(1.0 /
        base)))))


@staticmethod
def mysql(connection, config):
    """
        1. Verify id user exist.
        2. If not user exist create DB user.
        3. Verify if database exist.
        4. If DB not exist create DB and assign to user.
        """
    pass


def define(name: str, value: str='') ->str:
    """
    Return C++ macro-string #define name value

    Used for header defines.

    Parameters
    ----------
    name : str
        Name of macro to be defined
    value : str, optional
        Value of defined macro (if any),

    Returns
    -------
    str:
        "#define name" or "#define name value"
    """
    return '#define {} {}'.format(name, value)


def _jaccard(a, b):
    """ Return the Jaccard similarity between two sets a and b. """
    return 1.0 * len(a & b) / len(a | b)


@staticmethod
def _interpret_input_from_face_vertices(faces, purge):
    """Get faces and vertices from a list of faces as points."""
    vertices = []
    face_collector = []
    if purge:
        for f in faces:
            ind = []
            for v in f:
                try:
                    ind.append(vertices.index(v))
                except ValueError:
                    vertices.append(v)
                    ind.append(len(vertices) - 1)
            face_collector.append(tuple(ind))
    else:
        ver_counter = 0
        for f in faces:
            ind = []
            for v in f:
                vertices.append(v)
                ind.append(ver_counter)
                ver_counter += 1
            face_collector.append(tuple(ind))
    return vertices, face_collector


def theta_B3O3OH4_SO4_FW86(T, P):
    """a-a': triborate sulfate [FW86]."""
    theta = 0.1
    valid = T == 298.15
    return theta, valid