def get_paginator(operation_name=None):
    """
    Create a paginator for an operation.

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

    :rtype: L{botocore.paginate.Paginator}
    """
    pass


def interpolate_sequence():
    """Generate ‘in-betweens’ to smoothly interpolate between Grease Pencil frames

    """
    pass


def browse_service(zc, service_type_name, protocol, callback):
    """
    ZeroConf: Browse for services based on service type and protocol

    callback signature: callback(zeroconf, service_type, name, state_change)
        zeroconf: ZeroConf object
        service_type: zeroconf service
        name: service name
        state_change: ServiceStateChange type (Added, Removed)

    Returns ZeroConf object
    """
    from zeroconf import ServiceBrowser
    stn = '_{0}._{1}.local.'.format(service_type_name, protocol)
    browser = ServiceBrowser(zc, stn, handlers=[callback])
    return browser


def change_spacing(delta: int=1):
    """Change font spacing

    :param delta: Delta, Amount to decrease or increase character spacing with
    :type delta: int
    """
    pass


@staticmethod
def robocopy_args(src, dest, delete=False, exclude_files=None, exclude_dirs
    =None, dry_run=False):
    """Robocopy for sheldon

        Args:
          dest: path to local tdir
          src: path to remote (raid) tdir

        Returns:
          subprocess return code from robocopy

          Robocopy return codes:

          0. No files were copied. No failure was encountered. No files were
          mismatched. The files already exist in the destination directory;
          therefore, the copy operation was skipped.
          1. All files were copied successfully.
          2. There are some additional files in the destination directory that are not
          present in the source directory. No files were copied.
          3. Some files were copied. Additional files were present. No failure
          was encountered.
          5. Some files were copied. Some files were mismatched. No failure was
          encountered.
          6. Additional files and mismatched files exist. No files were copied
          and no failures were encountered. This means that the files already
          exist in the destination directory.
          7. Files were copied, a file mismatch was present, and additional files
          were present.
          8. Several files did not copy.
          :param src:
          :param dest:
          :param delete:
          :param exclude_files:
          :param exclude_dirs:
          :param dry_run:

        """
    if exclude_files is None:
        exclude_files = []
    if exclude_dirs is None:
        exclude_dirs = []
    _args = ['robocopy', src, dest, '/MIR' if delete else '/E', '/mt',
        '/W:1', '/R:1']
    if exclude_dirs:
        _args.extend(['/XD', *exclude_dirs])
    if exclude_files:
        _args.extend(['/XF', *exclude_files])
    if dry_run:
        _args.append('/L')
    return list(filter(None, _args))


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


@classmethod
def finish(cls, document):
    """
        Take a assembled document and convert all assembled values to
        finished values.
        """
    target_document = {}
    document_copy = {}
    for field_name, value in document.items():
        maker = cls._instructions[field_name]
        target_document = document.copy()
        with maker.target(target_document):
            document_copy[field_name] = maker(value)
            target_document[field_name] = document_copy[field_name]
    return document_copy


def set_layer_weights_from_single_trained_model(model, trained_model):
    """
    Sets the weights of a Keras model based on an already trained trained_model.

    Parameters
    ----------
    model : ks.models.Model
        Keras model instance withought weights.
    trained_model : ks.models.Model
        Pretrained Keras model used to set the weights for the new model.

    """
    skip_layers = ['dropout', 'input', 'flatten', 'max_pooling',
        'activation', 'concatenate']
    i = -1
    for layer in model.layers:
        i += 1
        skip = False
        for skip_layer_str in skip_layers:
            if skip_layer_str in layer.name:
                skip = True
        if skip:
            continue
        layer.set_weights(trained_model.layers[i].get_weights())


def concat(*data, **kwargs):
    """Joins input arrays along a given axis.

    .. note:: `Concat` is deprecated. Use `concat` instead.

    The dimensions of the input arrays should be the same except the axis along
    which they will be concatenated.
    The dimension of the output array along the concatenated axis will be equal
    to the sum of the corresponding dimensions of the input arrays.

    The storage type of ``concat`` output depends on storage types of inputs

    - concat(csr, csr, ..., csr, dim=0) = csr
    - otherwise, ``concat`` generates output with default storage

    Example::

       x = [[1,1],[2,2]]
       y = [[3,3],[4,4],[5,5]]
       z = [[6,6], [7,7],[8,8]]

       concat(x,y,z,dim=0) = [[ 1.,  1.],
                              [ 2.,  2.],
                              [ 3.,  3.],
                              [ 4.,  4.],
                              [ 5.,  5.],
                              [ 6.,  6.],
                              [ 7.,  7.],
                              [ 8.,  8.]]

       Note that you cannot concat x,y,z along dimension 1 since dimension
       0 is not the same for all the input arrays.

       concat(y,z,dim=1) = [[ 3.,  3.,  6.,  6.],
                             [ 4.,  4.,  7.,  7.],
                             [ 5.,  5.,  8.,  8.]]

    Defined in src/operator/nn/concat.cc:L383

    Parameters
    ----------
    data : NDArray[]
        List of arrays to concatenate
    dim : int, optional, default='1'
        the dimension to be concated.

    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 cmp(x, y):
    """
    Replacement for built-in function cmp that was removed in Python 3

    Compare the two objects x and y and return an integer according to
    the outcome. The return value is negative if x < y, zero if x == y
    and strictly positive if x > y.
    """
    return (x > y) - (x < y)


def split_components_image_filter(*args, **kwargs):
    """Procedural interface for SplitComponentsImageFilter"""
    import itk
    instance = itk.SplitComponentsImageFilter.New(*args, **kwargs)
    return instance.__internal_call__()


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

    The ".dev0" means dirty.

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


def get_multiprocessing(parallel):
    """
    If parallel indicates that we want to do multiprocessing,
    imports the multiprocessing module and sets the parallel
    value accordingly.
    """
    if parallel != 1:
        import multiprocessing
        if parallel <= 0:
            parallel = multiprocessing.cpu_count()
        return parallel, multiprocessing
    return parallel, None


def relate(*pairs):
    """ Given any number of ``(category_name, discriminator)`` pairs
        passed as positional arguments, relate the associated introspectables
        to each other. The introspectable related to each pair must have
        already been added via ``.add`` or ``.add_intr``; a :exc:`KeyError`
        will result if this is not true.  An error will not be raised if any
        pair has already been associated with another.

        This method is not typically called directly, instead it's called
        indirectly by :meth:`pyramid.interfaces.IIntrospector.register`
        """


def make_header(lines):
    """returns one header line from multiple header lines"""
    lengths = map(len, lines)
    max_length = max(lengths)
    for index, line in enumerate(lines):
        if lengths[index] != max_length:
            for i in range(lengths[index], max_length):
                line.append('')
    header = []
    for t, b in zip(*lines):
        if t.strip().endswith('-'):
            c = t.strip() + b
        else:
            c = ' '.join([t.strip(), b.strip()])
        header += [c.strip()]
    return header


@classmethod
def closetab(cls):
    """
        (classmethod) espressomaker.Espresso.closetab()

        Closes the open tab that belongs to this kernel (if any).

        Returns:
            None.

        """
    status = cls()._status()
    try:
        cls()._closetab(pid=cls._temp_pid)
        print('[espressomaker] Espresso tab closed.')
    except AttributeError:
        if status[0] == 0:
            print(
                '[espressomaker] No "caffeinate" processes related to this kernel (nor system) were found.'
                )
        elif status[0] == 1:
            cls()._closetab(pid=status[1])
            print('[espressomaker] Espresso tab closed.')
        elif status[0] == 2:
            print(
                """[espressomaker] No "caffeinate" processes related to this kernel were found but there are other
"caffeinate" processes running on this machine. To kill all, run "Espresso.killall()"."""
                )
    except:
        print(
            'Unexpected error. If you still have any "caffeinate" processes open, run "Espresso.killall()".'
            )
    finally:
        cls._temp_pid = None


def getGroupsForPrincipal(principalid):
    """Get groups the given principal belongs to"""


@staticmethod
def bool2txt(var):
    """Map True to 'true'
        and False to 'false'
        else don't modify value
        """
    if var is True:
        return 'true'
    elif var is False:
        return 'false'
    return var


def pow_mod(x: int, y: int, z: int) ->int:
    """
    int, int, int (or float)
    returns (x^y)mod z
    """
    number = 1
    while y:
        if y & 1:
            number = number * x % z
        y >>= 1
        x = x * x % z
    return number


def _thread_done(gt, *args, **kwargs):
    """Callback function to be passed to GreenThread.link() when we spawn()
    Calls the :class:`ThreadGroup` to notify if.

    """
    kwargs['group'].thread_done(kwargs['thread'])


def attach_group_policy(GroupName=None, PolicyArn=None):
    """
    Attaches the specified managed policy to the specified IAM group.
    You use this API to attach a managed policy to a group. To embed an inline policy in a group, use  PutGroupPolicy .
    For more information about policies, see Managed Policies and Inline Policies in the IAM User Guide .
    See also: AWS API Documentation

    Examples
    The following command attaches the AWS managed policy named ReadOnlyAccess to the IAM group named Finance.
    Expected Output:

    :example: response = client.attach_group_policy(
        GroupName='string',
        PolicyArn='string'
    )

    :type GroupName: string
    :param GroupName: [REQUIRED]
            The name (friendly name, not ARN) of the group to attach the policy to.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type PolicyArn: string
    :param PolicyArn: [REQUIRED]
            The Amazon Resource Name (ARN) of the IAM policy you want to attach.
            For more information about ARNs, see Amazon Resource Names (ARNs) and AWS Service Namespaces in the AWS General Reference .

    :return: response = client.attach_group_policy(
        GroupName='Finance',
        PolicyArn='arn:aws:iam::aws:policy/ReadOnlyAccess',
    )

    print(response)

    """
    pass


def link(detach: bool=False):
    """Use the mouse to create a link between two nodes

    :param detach: Detach, Detach and redirect existing links
    :type detach: bool
    """
    pass


def _sanity_check(name, package, level):
    """Verify arguments are "sane"."""
    if not isinstance(name, str):
        raise TypeError('module name must be str, not {}'.format(type(name)))
    if level < 0:
        raise ValueError('level must be >= 0')
    if level > 0:
        if not isinstance(package, str):
            raise TypeError('__package__ not set to a string')
        elif not package:
            raise ImportError(
                'attempted relative import with no known parent package')
    if not name and level == 0:
        raise ValueError('Empty module name')


def get_exception_message(ex):
    """Build exception message with details.
    """
    template = '{0}: {1!r}'
    return template.format(type(ex).__name__, ex.args)


def welcome():
    """ Displays welcome message to console
    """
    print('=======================')
    print('= Welcome to Blokus! =')
    print('=======================')
    print()


@classmethod
def set_default_mfile(cls, mfile):
    """Set the default MATLAB script file format for MATLAB classes.

        This method is used to set values for all MATLAB
        subclasses.  However, setting this will not update the output
        type for any existing instances.  For these, assign the
        <instance>.inputs.mfile.
        """
    cls._default_mfile = mfile


@staticmethod
def add_real_file(*_, **__):
    """ Nothing to do, the file is most probably already in the real FS.
        Implemented just for interface compatibility. """


def metadata_isdir(name):
    """Is the named metadata a directory?  (like ``os.path.isdir()``)"""


def psi_Na_B3O3OH4_Cl_FW86(T, P):
    """c-a-a': sodium triborate chloride [FW86]."""
    psi = -0.024
    valid = T == 298.15
    return psi, valid


def theme_install(overwrite: bool=True, filepath: str='', filter_folder:
    bool=True, filter_glob: str='*.xml'):
    """Load and apply a Blender XML theme file

    :param overwrite: Overwrite, Remove existing theme file if exists
    :type overwrite: bool
    :param filepath: filepath
    :type filepath: str
    :param filter_folder: Filter folders
    :type filter_folder: bool
    :param filter_glob: filter_glob
    :type filter_glob: str
    """
    pass


@staticmethod
def parse_resource_usage_header(header):
    """parse string like WORKER_TIME-3600=11.7/10000000;DB_QUERY_TIME-21600=4.62/2000 into dict
        """
    if not header:
        return {}
    result = {}
    try:
        for line in header.split(';'):
            right, left = line.split('=')
            metric, time_span = right.split('-')
            used, limit = left.split('/')
            result.setdefault(metric, {}).setdefault(time_span, {})[limit
                ] = float(used)
    except ValueError:
        return {}
    return result


def _validate_term(term: str) ->str:
    """Validates term is a string and check if it is valid."""
    if len(term) == 4 and term.isdigit():
        return term
    raise ValueError('Invalid term')


def gen_input_list(sig_dic):
    """
    For generating List view HTML file for INPUT.
    for each item.
    """
    out_str = (
        """

{1}

    {{{{ postinfo.extinfo['{0}'][0] }}}} {2}

    """
        .format(sig_dic['en'], sig_dic['zh'], sig_dic['dic'][1]))
    return out_str


def replace_by_index(stretch, seq):
    """
    Given a start and end point in a string (in format 'start:end') and a sequence, will replace characters within
    that stretch with the letter N.
    :param stretch: Start and end index to replace (in format 'start:end')
    :param seq: Sequence to change.
    :return: Sequence modified to have Ns where specified by stretch.
    """
    stretch = stretch.split(':')
    start = int(stretch[0])
    end = int(stretch[1])
    seq = seq[:start] + 'N' * (end - start) + seq[end:]
    return seq


def check_pointer(n):
    """
    this function for seprate name and point
    like this  'char *' -> ['char', 1] ,
    'char **' -> ['char', 2]

    if it is not pointer , will return None
    like this 'char' -> ['char', 0]
    """
    w = n.split('*')
    return w[0].strip(), len(w) - 1


def decodeField(value, decode_function):
    """
    Decodes a field value using given decode_function
    :param value:
    :param decode_function:
    :return:
    """
    if value is None:
        return None
    return decode_function(value)


def get_section_id(base_soup):
    """
    학부전공별, 교양필수, 교양선택 등 항목을 선택하는데 필요한 id를 얻는다
    :param base_soup:
    SoupParser.soup_jar['base']
    :return:
    """
    table = base_soup.find('table', {'lsevents':
        "{TabSelect:[{ResponseData:'delta',ClientAction:'submit'},{}]," +
        "Scroll:[{ResponseData:'delta',EnqueueCardinality:'single'},{}]," +
        "Hotkey:[{ResponseData:'delta',ClientAction:'submit'},{}]}"})
    return table.get('id')


@staticmethod
def ctrl(char):
    """
        Calculate the control code for a given key.  For example, this converts
        "a" to 1 (which is the code for ctrl-a).

        :param char: The key to convert to a control code.
        :return: The control code as an integer or None if unknown.
        """
    if not isinstance(char, int):
        char = ord(char.upper())
    return char & 31 if 64 <= char <= 95 else None


def getCombinations(matrix, phenome, genome, pthresh, gthresh):
    """
    Generator to combination of compounds and pathways data
    """
    phenome = sorted(filter(lambda x: x[3] >= pthresh, phenome), key=lambda
        x: x[3], reverse=True)
    genome = sorted(filter(lambda x: x[2] >= 0, genome), key=lambda x: x[2])
    toRemove = []
    for j in genome:
        p = j[0]
        bOne = False
        for i in phenome:
            cid = i[0]
            scateg = i[1]
            if p in matrix[cid][scateg]:
                bOne = True
                break
        if not bOne:
            toRemove.append(j)
    for i in toRemove:
        genome.remove(i)
    out = []
    for i in phenome:
        cid = i[0]
        scateg = i[1]
        cname = i[2]
        pval = i[3]
        for j in genome:
            p = j[0]
            pname = j[1]
            gval = j[2]
            if p in matrix[cid][scateg]:
                out.append((scateg, cid, cname, p, pname, pval, gval))
    for o in sorted(out, key=lambda x: (x[5], x[6]), reverse=True):
        yield o


def get_exit_info(jobreport_dictionary):
    """
    Return the exit code (exitCode) and exit message (exitMsg).
    E.g. (0, 'OK').

    :param jobreport_dictionary:
    :return: exit_code, exit_message
    """
    return jobreport_dictionary['exitCode'], jobreport_dictionary['exitMsg']


def frange(start, stop, increment):
    """
    Custom iterator to iterate in floating point steps.
    :return: Generator of steps between start and stop

    Example:
        for n in frange(0, 4, 0.5):
        print(n)
    """
    x = start
    while x < stop:
        yield x
        x += increment


def imperial_returns(data):
    """
	Calculate Basic Returns of a Price Series
	Uses Formula: (data(t)-data(t-1))-1
	"""
    daily_returns = data / data.shift(1) - 1
    return daily_returns


@classmethod
def add_common_opts(cls, parser):
    """Add options that are common for several plugins.
        """
    for opt in cls.common_opt_names:
        cls._parser_add_opt(parser, opt)


@classmethod
def init_data_options(cls, parser):
    """Set up data input and signal processing options
        """
    cls.arg_channels(parser)
    cls.arg_data(parser)
    cls.arg_signal(parser)


def get_snowball_usage():
    """
    Returns information about the Snowball service limit for your account, and also the number of Snowballs your account has in use.
    The default service limit for the number of Snowballs that you can have at one time is 1. If you want to increase your service limit, contact AWS Support.
    See also: AWS API Documentation

    Examples
    Returns information about the Snowball service limit for your account, and also the number of Snowballs your account has in use.

    :example: response = client.get_snowball_usage()

    :rtype: dict
    :return: {
        'SnowballLimit': 123,
        'SnowballsInUse': 123
    }

    """
    pass


def p(parallel):
    """ adds elements in parallel

    Notes
    ---------
    .. math::

        Z = \\frac{1}{\\frac{1}{Z_1} + \\frac{1}{Z_2} + ... + \\frac{1}{Z_n}}

     """
    z = len(parallel[0]) * [0 + 0 * 1.0j]
    for elem in parallel:
        z += 1 / elem
    return 1 / z


def apply_gravity(repulsion, nodes, gravity, scaling_ratio):
    """
    Iterate through the nodes or edges and apply the gravity directly to the node objects.
    """
    for i in range(0, len(nodes)):
        repulsion.apply_gravitation(nodes[i], gravity / scaling_ratio)


def batch_read(DirectoryArn=None, Operations=None, ConsistencyLevel=None):
    """
    Performs all the read operations in a batch.
    See also: AWS API Documentation

    :example: response = client.batch_read(
        DirectoryArn='string',
        Operations=[
            {
                'ListObjectAttributes': {
                    'ObjectReference': {
                        'Selector': 'string'
                    },
                    'NextToken': 'string',
                    'MaxResults': 123,
                    'FacetFilter': {
                        'SchemaArn': 'string',
                        'FacetName': 'string'
                    }
                },
                'ListObjectChildren': {
                    'ObjectReference': {
                        'Selector': 'string'
                    },
                    'NextToken': 'string',
                    'MaxResults': 123
                }
            },
        ],
        ConsistencyLevel='SERIALIZABLE'|'EVENTUAL'
    )

    :type DirectoryArn: string
    :param DirectoryArn: [REQUIRED]
            The Amazon Resource Name (ARN) that is associated with the Directory . For more information, see arns .

    :type Operations: list
    :param Operations: [REQUIRED]
            A list of operations that are part of the batch.
            (dict) --Represents the output of a BatchRead operation.
            ListObjectAttributes (dict) --Lists all attributes that are associated with an object.
            ObjectReference (dict) -- [REQUIRED]Reference of the object whose attributes need to be listed.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

            NextToken (string) --The pagination token.
            MaxResults (integer) --The maximum number of items to be retrieved in a single call. This is an approximate number.
            FacetFilter (dict) --Used to filter the list of object attributes that are associated with a certain facet.
            SchemaArn (string) --The ARN of the schema that contains the facet.
            FacetName (string) --The name of the facet.

            ListObjectChildren (dict) --Returns a paginated list of child objects that are associated with a given object.
            ObjectReference (dict) -- [REQUIRED]Reference of the object for which child objects are being listed.
            Selector (string) --A path selector supports easy selection of an object by the parent/child links leading to it from the directory root. Use the link names from each parent/child link to construct the path. Path selectors start with a slash (/) and link names are separated by slashes. For more information about paths, see Accessing Objects . You can identify an object in one of the following ways:
            $ObjectIdentifier - An object identifier is an opaque string provided by Amazon Cloud Directory. When creating objects, the system will provide you with the identifier of the created object. An object s identifier is immutable and no two objects will ever share the same object identifier
            /some/path - Identifies the object based on path
            #SomeBatchReference - Identifies the object in a batch call

            NextToken (string) --The pagination token.
            MaxResults (integer) --Maximum number of items to be retrieved in a single call. This is an approximate number.

    :type ConsistencyLevel: string
    :param ConsistencyLevel: Represents the manner and timing in which the successful write or update of an object is reflected in a subsequent read operation of that same object.

    :rtype: dict
    :return: {
        'Responses': [
            {
                'SuccessfulResponse': {
                    'ListObjectAttributes': {
                        'Attributes': [
                            {
                                'Key': {
                                    'SchemaArn': 'string',
                                    'FacetName': 'string',
                                    'Name': 'string'
                                },
                                'Value': {
                                    'StringValue': 'string',
                                    'BinaryValue': b'bytes',
                                    'BooleanValue': True|False,
                                    'NumberValue': 'string',
                                    'DatetimeValue': datetime(2015, 1, 1)
                                }
                            },
                        ],
                        'NextToken': 'string'
                    },
                    'ListObjectChildren': {
                        'Children': {
                            'string': 'string'
                        },
                        'NextToken': 'string'
                    }
                },
                'ExceptionResponse': {
                    'Type': 'ValidationException'|'InvalidArnException'|'ResourceNotFoundException'|'InvalidNextTokenException'|'AccessDeniedException'|'NotNodeException',
                    'Message': 'string'
                }
            },
        ]
    }

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

    """
    pass


def add_to_queryable(func):
    """
    This decorator allows registration a method to an ConstraintsObjects,
    so it can be accessed more easily.
    """
    func.__query_method__ = True
    return func


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 get_sfd(input_values, x):
    """ Take input and position on the bar and gets the resulting sfd.

        :param input_values: Dict containing all the values given at input.

        :param x: position along the length of the bar.

    """
    sfd = 0
    udls = input_values.get('UDLs')
    for i in range(len(udls)):
        udl = udls[i]
        if float(udl[1]) <= x and min(x, float(udl[2])) <= x:
            sfd += float(udl[0]) * (min(x, float(udl[2])) - float(udl[1]))
    point_loads = input_values.get('point_loads')
    for i in range(len(point_loads)):
        point_load = point_loads[i]
        if float(point_load[1]) <= float(x):
            sfd += float(point_load[0])
    return sfd


@classmethod
def open(Cls, filename, flag=None):
    """Open present for compatibility with shelve. flag is ignored; this
        format is always capable of both reading and writing.
        """
    return Cls(filename=filename)


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

    The ".dev0" means dirty.

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


def distance_point_to_plane(pt: 'mathutils.Vector', plane_co:
    'mathutils.Vector', plane_no: 'mathutils.Vector') ->float:
    """Returns the signed distance between a point and a plane (negative when below the normal).

    :param pt: Point
    :type pt: 'mathutils.Vector'
    :param plane_co: A point on the plane
    :type plane_co: 'mathutils.Vector'
    :param plane_no: The direction the plane is facing
    :type plane_no: 'mathutils.Vector'
    """
    pass


def move_point_cat(point, ipoint, to_clust, from_clust, cl_attr_freq,
    membership):
    """Move point between clusters, categorical attributes."""
    membership[to_clust, ipoint] = 1
    membership[from_clust, ipoint] = 0
    for iattr, curattr in enumerate(point):
        cl_attr_freq[to_clust][iattr][curattr] += 1
        cl_attr_freq[from_clust][iattr][curattr] -= 1
    return cl_attr_freq, membership


def start_query_execution(QueryString=None, ClientRequestToken=None,
    QueryExecutionContext=None, ResultConfiguration=None):
    """
    Runs (executes) the SQL query statements contained in the Query string.
    For code samples using the AWS SDK for Java, see Examples and Code Samples in the Amazon Athena User Guide .
    See also: AWS API Documentation

    :example: response = client.start_query_execution(
        QueryString='string',
        ClientRequestToken='string',
        QueryExecutionContext={
            'Database': 'string'
        },
        ResultConfiguration={
            'OutputLocation': 'string',
            'EncryptionConfiguration': {
                'EncryptionOption': 'SSE_S3'|'SSE_KMS'|'CSE_KMS',
                'KmsKey': 'string'
            }
        }
    )

    :type QueryString: string
    :param QueryString: [REQUIRED]
            The SQL query statements to be executed.

    :type ClientRequestToken: string
    :param ClientRequestToken: A unique case-sensitive string used to ensure the request to create the query is idempotent (executes only once). If another StartQueryExecution request is received, the same response is returned and another query is not created. If a parameter has changed, for example, the QueryString , an error is returned.
            Warning
            This token is listed as not required because AWS SDKs (for example the AWS SDK for Java) auto-generate the token for users. If you are not using the AWS SDK or the AWS CLI, you must provide this token or the action will fail.
            This field is autopopulated if not provided.

    :type QueryExecutionContext: dict
    :param QueryExecutionContext: The database within which the query executes.
            Database (string) --The name of the database.

    :type ResultConfiguration: dict
    :param ResultConfiguration: [REQUIRED]
            Specifies information about where and how to save the results of the query execution.
            OutputLocation (string) -- [REQUIRED]The location in S3 where query results are stored.
            EncryptionConfiguration (dict) --If query results are encrypted in S3, indicates the S3 encryption option used (for example, SSE-KMS or CSE-KMS and key information.
            EncryptionOption (string) -- [REQUIRED]Indicates whether Amazon S3 server-side encryption with Amazon S3-managed keys (SSE-S3 ), server-side encryption with KMS-managed keys (SSE-KMS ), or client-side encryption with KMS-managed keys (CSE-KMS) is used.
            KmsKey (string) --For SSE-KMS and CSE-KMS , this is the KMS key ARN or ID.

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

    """
    pass


def register_rpc(name, func):
    """Registers RPC function.

    * http://uwsgi.readthedocs.io/en/latest/RPC.html

    :param str|unicode name:

    :param callable func:

    :rtype: bool

    :raises ValueError: If unable to register function
    """
    return False


def _format_options(virtualenv_ops):
    """Formats the a dictionary of options to be passed as flags to virtualenv."""
    options = []
    for option_name, option_value in virtualenv_ops.items():
        if option_value:
            option = option_name.replace('_', '-')
            option = f'--{option}'
            if not isinstance(option_value, bool):
                option_value = option_value.replace('=', '')
                option += f'={option_value}'
            options.append(option)
    return options


@classmethod
def delete_all(cls):
    """ Delete all the registries. """
    with cls._lock:
        for db_name in list(cls.registries.keys()):
            cls.delete(db_name)


def _LeftMostFace(holes, points):
    """Return (hole,index of hole in holes) where hole has
    the leftmost first vertex.  To be able to handle empty
    holes gracefully, call an empty hole 'leftmost'.
    Assumes holes are sorted by softface."""
    assert len(holes) > 0
    lefti = 0
    lefthole = holes[0]
    if len(lefthole) == 0:
        return lefthole, lefti
    leftv = lefthole[0]
    for i in range(1, len(holes)):
        ihole = holes[i]
        if len(ihole) == 0:
            return ihole, i
        iv = ihole[0]
        if points.pos[iv] < points.pos[leftv]:
            lefti, lefthole, leftv = i, ihole, iv
    return lefthole, lefti


def clone(rolecls, subj):
    """
    Returns a new subject instance with role applied. Both instances refer to
    the same instance dict.

    >>> class Person(object):
    ...     def __init__(self, name): self.name = name
    ...     def am(self): print self.name, 'is'
    >>> class Biker(object):
    ...     __metaclass__ = RoleType
    ...     def bike(self): print self.name, 'bikes'
    ...
    >>> person = Person('Joe')
    >>> biker = Biker(person, method=clone)
    >>> biker # doctest: +ELLIPSIS
    <roles.role.Person+Biker object at 0x...>
    >>> person # doctest: +ELLIPSIS
    <roles.role.Person object at 0x...>
    >>> person is biker
    False
    >>> person.__dict__ is biker.__dict__
    True
    >>> biker.bike()
    Joe bikes

    Note that ``clone`` has a serious downside: since only the instance dict is
    cloned, everything defined in the class (properties, methods) are not
    accessible by the role.
    """
    newsubj = rolecls.__new__(rolecls)
    newsubj.__dict__ = subj.__dict__
    return newsubj


def p_character_whitespace(p):
    """character : K_WHITESPACE
    """
    p[0] = [('whitespace', ())]


def callback_none(params, errors, best_params, best_error, index):
    """Non-verbose callback"""
    pass


def convert_flatten(builder, layer, input_names, output_names, keras_layer):
    """Convert a flatten layer from keras to coreml.

    Parameters
    keras_layer: layer
    ----------
        A keras layer object.

    builder: NeuralNetworkBuilder
        A neural network builder object.
    """
    input_name, output_name = input_names[0], output_names[0]
    blob_order = 0
    if len(keras_layer.input.shape) == 4:
        blob_order = 1
    builder.add_flatten(name=layer, mode=blob_order, input_name=input_name,
        output_name=output_name)


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

        :param SharedContentDownloadDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_download_details', val)


def delete_rule(Name=None):
    """
    Deletes the specified rule.
    You must remove all targets from a rule using  RemoveTargets before you can delete the rule.
    When you delete a rule, incoming events might continue to match to the deleted rule. Please allow a short period of time for changes to take effect.
    See also: AWS API Documentation

    :example: response = client.delete_rule(
        Name='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            The name of the rule.

    """
    pass


def search_device(requirement, devices):
    """
    Returns a sufficient device or None

    :param requirement: The requirement to fulfill
    :type requirement: GPURequirement
    :param devices: The list of available devices
    :type devices: List[GPUDevice]
    :return: A device from the list
    """
    for device in devices:
        if requirement.is_sufficient(device):
            return device
    return None


def unsetRoleForPrincipal(role_id, principal_id):
    """Unset the role for the principal."""


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


def conservative_asm(mnemo, instr, symbols, conservative):
    """
    Asm instruction;
    Try to keep original instruction bytes if it exists
    """
    candidates = mnemo.asm(instr, symbols)
    if not candidates:
        raise ValueError('cannot asm:%s' % str(instr))
    if not hasattr(instr, 'b'):
        return candidates[0], candidates
    if instr.b in candidates:
        return instr.b, candidates
    if conservative:
        for c in candidates:
            if len(c) == len(instr.b):
                return c, candidates
    return candidates[0], candidates


def merge_grouped_mappings(mappings):
    """Merge multiple mappings into a single mapping for drawing"""
    for mapping_group, mapping_value in mappings.items():
        yield mapping_group, mapping_value['mapping']


def expand_abbreviations(data):
    """ Exapand a flattened DefaultDict into a CSV-formatted list of lists
    """
    lines = []
    if data:
        for key in data.keys():
            line = [key]
            for col in data[key]:
                line.append(col)
            lines.append(line)
    if not lines:
        while len(lines) < 10:
            lines.append(['', '', '', '', '', ''])
    return lines


def cellDijFill(pfx, phfx, SGData, parmDict):
    """Returns the filled-out reciprocal cell (A) terms
    from the parameter dictionaries corrected for Dij.

    :param str pfx: parameter prefix ("n::", where n is a phase number)
    :param dict SGdata: a symmetry object
    :param dict parmDict: a dictionary of parameters

    :returns: A,sigA where each is a list of six terms with the A terms
    """
    if SGData['SGLaue'] in ['-1']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A1'] + parmDict[phfx + 'D22'], parmDict[pfx + 'A2'] + parmDict
            [phfx + 'D33'], parmDict[pfx + 'A3'] + parmDict[phfx + 'D12'],
            parmDict[pfx + 'A4'] + parmDict[phfx + 'D13'], parmDict[pfx +
            'A5'] + parmDict[phfx + 'D23']]
    elif SGData['SGLaue'] in ['2/m']:
        if SGData['SGUniq'] == 'a':
            A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[
                pfx + 'A1'] + parmDict[phfx + 'D22'], parmDict[pfx + 'A2'] +
                parmDict[phfx + 'D33'], 0, 0, parmDict[pfx + 'A5'] +
                parmDict[phfx + 'D23']]
        elif SGData['SGUniq'] == 'b':
            A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[
                pfx + 'A1'] + parmDict[phfx + 'D22'], parmDict[pfx + 'A2'] +
                parmDict[phfx + 'D33'], 0, parmDict[pfx + 'A4'] + parmDict[
                phfx + 'D13'], 0]
        else:
            A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[
                pfx + 'A1'] + parmDict[phfx + 'D22'], parmDict[pfx + 'A2'] +
                parmDict[phfx + 'D33'], parmDict[pfx + 'A3'] + parmDict[
                phfx + 'D12'], 0, 0]
    elif SGData['SGLaue'] in ['mmm']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A1'] + parmDict[phfx + 'D22'], parmDict[pfx + 'A2'] + parmDict
            [phfx + 'D33'], 0, 0, 0]
    elif SGData['SGLaue'] in ['4/m', '4/mmm']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A0'] + parmDict[phfx + 'D11'], parmDict[pfx + 'A2'] + parmDict
            [phfx + 'D33'], 0, 0, 0]
    elif SGData['SGLaue'] in ['6/m', '6/mmm', '3m1', '31m', '3']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A0'] + parmDict[phfx + 'D11'], parmDict[pfx + 'A2'] + parmDict
            [phfx + 'D33'], parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], 0, 0
            ]
    elif SGData['SGLaue'] in ['3R', '3mR']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A0'] + parmDict[phfx + 'D11'], parmDict[pfx + 'A0'] + parmDict
            [phfx + 'D11'], parmDict[pfx + 'A3'] + parmDict[phfx + 'D23'],
            parmDict[pfx + 'A3'] + parmDict[phfx + 'D23'], parmDict[pfx +
            'A3'] + parmDict[phfx + 'D23']]
    elif SGData['SGLaue'] in ['m3m', 'm3']:
        A = [parmDict[pfx + 'A0'] + parmDict[phfx + 'D11'], parmDict[pfx +
            'A0'] + parmDict[phfx + 'D11'], parmDict[pfx + 'A0'] + parmDict
            [phfx + 'D11'], 0, 0, 0]
    return A


def locatie_adres_adapter(obj, request=None):
    """
    Adapter for rendering
    :class:`oe_geoutils.data.models.LocatieAdres` to json.

    Add the adapter to `jsonpublish`
    from jsonpublish import register_adapter
    register_adapter(LocatieAdres, locatie_adres_adapter)

    Add the adapter to your :class:`pyramid.renderers.JSON` json_renderer
    from pyramid.renderers import JSON
    json_renderer = JSON()
    json_renderer.add_adapter(LocatieAdres, locatie_adres_adapter)
    """
    locatie_adres = {'id': obj.id, 'type': obj.type, 'provincie': {
        'niscode': obj.provincie_niscode, 'naam': obj.provincie_naam},
        'gemeente': {'niscode': obj.gemeente_niscode, 'naam': obj.
        gemeente_naam, 'id': obj.gemeente_crab_id}, 'deelgemeente': {
        'niscode': obj.deelgemeente_niscode, 'naam': obj.deelgemeente_naam},
        'huisnummer_id': obj.huisnummer_id, 'huisnummer': obj.huisnummer,
        'subadres_id': obj.subadres_id, 'subadres': obj.subadres, 'straat':
        obj.straat, 'straat_id': obj.straat_id, 'postcode': obj.postcode,
        'land': obj.land}
    return locatie_adres


def decode(text):
    """ Converts an arbitrary string to byte string in UTF-8. On failure
    returns the given string.

    @param text: string to be converted
    @type text: string
    """
    if type(text) is str:
        return text.encode('utf-8')
    encoding_lst = [('iso-8859-15',), ('utf-8',), ('latin-1',), ('utf-8',
        'replace')]
    for encoding in encoding_lst:
        try:
            return text.decode(*encoding).encode('utf-8')
        except:
            return text


def parse_range(textrange):
    """Parse a patch range, handling the "1" special-case

    :param textrange: The text to parse
    :type textrange: str
    :return: the position and range, as a tuple
    :rtype: (int, int)
    """
    tmp = textrange.split(b',')
    if len(tmp) == 1:
        pos = tmp[0]
        range = b'1'
    else:
        pos, range = tmp
    pos = int(pos)
    range = int(range)
    return pos, range


def output_group_regression_funcs(group: list):
    """
    Take list of Evolution objects and output their
    best regressions to a "regression_modules" subdir.
    """
    for cr_ev in group:
        cr_ev.output_best_regression_function_as_module()


def check_special_cases(instance, json_data):
    """
    This functions checks special cases of plugins to be serialized accordingly
    :param instance:
    :return: returns json_data with particular fields
    """
    model_name = instance._meta.model_name
    app_label = instance._meta.app_label
    return json_data


def wait(processes):
    """waits on a list of processes"""
    while processes:
        for p in processes:
            if p.poll() is not None:
                print('Process {} ({}) ended with exit code {}'.format(p.
                    desc, p.pid, p.returncode))
                processes.remove(p)


def _split_line(line: str, size: int=3, prefix: int=4, strip: str=' |') ->[str
    ]:
    """
    Evenly split a string while stripping elements
    """
    line = line[prefix:]
    ret = []
    while len(line) >= size:
        ret.append(line[:size].strip(strip))
        line = line[size:]
    line = line.strip(strip)
    if line:
        ret.append(line)
    return ret


def parse_festival_dict(festival_location):
    """For OALD; yields word,part-of-speech,pronunciation"""
    ret = []
    for line in open(festival_location):
        line = line.strip()
        if '((pos' in line:
            line = line[:line.index('((pos')]
        if line.startswith('( "'):
            line = line[3:]
        line = line.replace('"', '').replace('(', '').replace(')', '')
        try:
            word, pos, pronunc = line.split(None, 2)
        except ValueError:
            continue
        if pos not in ['n', 'v', 'a', 'cc', 'dt', 'in', 'j', 'k', 'nil',
            'prp', 'uh']:
            continue
        yield word.lower(), pos, pronunc


def init_standard_poly(basetensor, ind, x):
    """Initialize the 1 and x1,...,xn before starting the recursion.

    Parameters
    ----------
    basetensor : numpy.ndarray
        The ``num_dims+1``-dimensional array considered, with samples
        along the first dimension. For each sample we have ``num_dims``
        -dimensional subarrays with non-zero values on the edges.
    ind : numpy.ndarray
        Instance of the class ``NDArrayManager`` created in the
        ``RecursiveExpansion.execute`` method and passed when
        calling this function.
    x : numpy.ndarray
        A two-dimensional numpy array passed to
        ``RecursiveExpansion.execute``. The recursion will be evaluated
        on the data contained. Observations of
        variables are stored in the rows of the array, individual variables
        are stored in the columns. This means that one row contains one
        particular observation/measurement of all variables, and one
        column contains all observations/measurements of one particular
        variable.
    """
    ind.zeroAllBut(0, 0)
    basetensor[ind.all + ind.getCurrent()] = 1.0
    for i in range(x.shape[1]):
        ind.zeroAllBut(i, 1)
        basetensor[ind.all + ind.getCurrent()] = x[:, (i)]


def get_3grams(string):
    """ Return the set of different tri-grams in a string
    """
    string = '  ' + string + '  '
    return list(zip(string, string[1:], string[2:]))


@classmethod
def _normalize_unit(cls, unit):
    """Resolve a unit to its real name if it's an alias.

        :param unit str: the unit to normalize
        :return: the normalized unit, or None one isn't found
        :rtype: Union[None, str]
        """
    if unit in cls.UNITS_IN_SECONDS:
        return unit
    return cls.UNIT_ALIASES_REVERSE.get(unit, None)


def where(condition=None, x=None, y=None, name=None, attr=None, out=None,
    **kwargs):
    """Return the elements, either from x or y, depending on the condition.

    Given three ndarrays, condition, x, and y, return an ndarray with the elements from x or y,
    depending on the elements from condition are true or false. x and y must have the same shape.
    If condition has the same shape as x, each element in the output array is from x if the
    corresponding element in the condition is true, and from y if false.

    If condition does not have the same shape as x, it must be a 1D array whose size is
    the same as x's first dimension size. Each row of the output array is from x's row
    if the corresponding element from condition is true, and from y's row if false.

    Note that all non-zero values are interpreted as ``True`` in condition.

    Examples::

      x = [[1, 2], [3, 4]]
      y = [[5, 6], [7, 8]]
      cond = [[0, 1], [-1, 0]]

      where(cond, x, y) = [[5, 2], [3, 8]]

      csr_cond = cast_storage(cond, 'csr')

      where(csr_cond, x, y) = [[5, 2], [3, 8]]

    Defined in src/operator/tensor/control_flow_op.cc:L57

    Parameters
    ----------
    condition : Symbol
        condition array
    x : Symbol
    y : Symbol

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

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


@staticmethod
def is_message(msg: str) ->bool:
    """
        Helper for detecting if message (string) is a "message" or
        "chat message" message.
        """
    if msg.startswith('chat: msg:') or msg.startswith('message:'):
        return True
    return False


def collection_new(nested: bool=True):
    """Add a new collection inside selected collection

    :param nested: Nested, Add as child of selected collection
    :type nested: bool
    """
    pass


@classmethod
def make(cls, event_type, event_data):
    """Creates a new TreeEvent tuple.

        :returns: A :class:`~kazoo_sasl.recipe.cache.TreeEvent` instance.
        """
    assert event_type in (cls.NODE_ADDED, cls.NODE_UPDATED, cls.
        NODE_REMOVED, cls.CONNECTION_SUSPENDED, cls.CONNECTION_RECONNECTED,
        cls.CONNECTION_LOST, cls.INITIALIZED)
    return cls((event_type, event_data))


def QuotedEscaped(s):
    """Convert a string into a literal value that can be used in Python source.

    This just calls C{repr}.  No point in getting all complex when the language
    already gives us what we need.

    @rtype: C{str}
    """
    return repr(s)


def _get_zip_urls(year):
    """Return urls for zip files based on pattern.

    Parameters
    ----------
    year : string
        4 digit year in string format 'YYYY'.

    Returns
    -------
    dict
    """
    suffix = f'oesm{year[2:]}'
    code = 4
    return {'national':
        f'https://www.bls.gov/oes/special.requests/{suffix}nat.zip',
        'state': f'https://www.bls.gov/oes/special.requests/{suffix}st.zip',
        'area': f'https://www.bls.gov/oes/special.requests/{suffix}ma.zip',
        'industry':
        f'https://www.bls.gov/oes/special.requests/{suffix}in{code}.zip'}


def p_testlist_safe_plus_2(p):
    """testlist_safe_plus : testlist_safe_plus COMMA old_test"""
    p[0] = p[1] + [p[3]]


def no_metar_returner(location, dates, end_dates, start_time_hours,
    end_time_hours, contents, number_of_flights, replace_key=
    'METAR_INFORMATION'):
    """Replaces the key word in a cell with note that no METAR information was
    available from the day"""
    metar_text = ''
    for flight in range(number_of_flights):
        year = str(dates[flight])[:4]
        year_end = str(end_dates[flight])[:4]
        month = str(dates[flight])[4:6]
        month_end = str(end_dates[flight])[4:6]
        day = str(dates[flight])[6:8]
        day_end = str(end_dates[flight])[6:8]
        metar_text += ('    "No METARs for ' + str(location[flight]) +
            ' for the date ' + day + '/' + month + '/' + year +
            ' to the date ' + day_end + '/' + month_end + '/' + year_end +
            ' from a starting time of ' + str(start_time_hours[flight]) +
            ':00 and an end time of ' + str(int(end_time_hours[flight]) - 1
            ) + ':59.\\n",\n')
    metar_text = metar_text[:-2]
    metar_replacement = ('\n  {\n ' + '  "cell_type": "markdown",\n' +
        '   "metadata": {},\n' + '   "source": [\n' + '    "' + replace_key +
        '"\n' + '   ]\n' + '  },')
    metar_information = ('  {\n ' + '  "cell_type": "markdown",\n' +
        '   "metadata": {},\n' + '   "source": [\n' +
        '    "
Metar Information
\\n",
    "\\n",
""" +
        metar_text + '\n   ]\n' + '  },')
    contents = contents.replace(metar_replacement, metar_information)
    return contents


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

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


def get_cigar(var):
    """
    Return the cigar string describing how to align an
    alternate allele to the reference allele
    """
    return var.INFO.get('CIGAR')


def default_config():
    """Return a dict with the default config values."""
    return {'list': {'name': 'sqlite', 'config': {'directory':
        '~/.taskforge.d'}}, 'server': {'port': 8080, 'list': {'name':
        'sqlite', 'config': {'directory': '~/.taskforge.d'}}}}


@classmethod
def from_str(cls, value: str) ->'TDivision':
    """
        Construct from a JSON string (eg. a POST payload).

        Returns:
            Model instance based on the JSON string.

        """
    ...


def parse_accept_header(accept):
    """
    Parse the Accept header *accept*, returning a list with 3-tuples of
    [(str(media_type), dict(params), float(q_value)),] ordered by q values.

    If the accept header includes vendor-specific types like::

        application/vnd.yourcompany.yourproduct-v1.1+json

    It will actually convert the vendor and version into parameters and
    convert the content type into `application/json` so appropriate content
    negotiation decisions can be made.

    Default `q` for values that are not specified is 1.0
    """
    result = []
    if accept == 'text/*,image/*;application/*;*/*;':
        return [('*/*', {}, 1.0)]
    for media_range in accept.split(','):
        parts = media_range.split(';')
        media_type = parts.pop(0).strip()
        media_params = []
        if media_type.find('/') == -1:
            result.append(('*/*', {}, 1.0))
            continue
        typ, subtyp = media_type.split('/')
        if '+' in subtyp:
            vnd, sep, extra = subtyp.partition('+')
            if vnd.startswith('vnd'):
                if '-v' in vnd:
                    vnd, sep, rest = vnd.rpartition('-v')
                    if len(rest):
                        try:
                            version = media_params.append(('version', float
                                (rest)))
                        except ValueError:
                            version = 1.0
                media_params.append(('vendor', vnd.replace('vnd.', '')))
                media_type = '/'.join([typ, extra])
        q = 1.0
        for part in parts:
            key, value = part.lstrip().split('=', 1)
            key = key.strip()
            value = value.strip()
            if key == 'q':
                q = float(value)
            else:
                media_params.append((key, value))
        result.append((media_type, dict(media_params), q))
    result.sort(key=lambda r: -r[2])
    return result


def validate(reference, attempt):
    """
        Returns True is attempt hashes to reference, False otherwise.
        """


def t_expval(nu):
    """
    Expectation of Student's t random variables.
    """
    return 0


def format_xml(element):
    """
    Format an XML element, e.g. Beaker job description, for printing.

    :param element: XML element to format.
    """
    prettyfied = element.prettify()
    return prettyfied


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def CDLIDENTICAL3CROWS(df):
    """
    Identical Three Crows
    """


def clipMinMax(size, minSize, maxSize):
    """
    Clip the size so it is bigger then minSize but smaller than maxSize.
    """
    return size.expandedTo(minSize).boundedTo(maxSize)


def addCommonArguments(ap):
    """
    Add commandline arguments common to all clients
    """
    ap.add_argument('-k', '--key', default='', help=
        'key used to refer to the record. If not set the accounting server will create the key. Specifying an existing key will overwrite the existing record. Default: "" - not set'
        )
    ap.add_argument('-T', '--type', default='storage', help=
        'type of the resource accounted. Default: storage')
    ap.add_argument('-m', '--measure_time', default='', help=
        'measurement time of the accounting record if different from the current time. Default: "" - not set'
        )
    ap.add_argument('-C', '--comment', default='', help=
        'arbitrary comment (goes into the meta dictionary). Default: "" - not set'
        )
    ap.add_argument('-t', '--test', action='store_true', help=
        "Dry run. Don't push data to server - run only locally Default: off")
    ap.add_argument('-v', '--verbose', action='store_true', help=
        'return the key of the accounting record created. Default: off')


def get_overlapping_usernames(source_user_df, target_user_df,
    mapping_file_path=None) ->list:
    """
    Creates a list of usernames that appear in the source connection and the target connection.
    :param pd.DataFrame source_user_df: a Pandas DataFrame populated with source connection user details
    :param pd.DataFrame target_user_df: a Pandas DataFrame populated with target connection user details
    :param str mapping_file_path: (optional) the file path for the mapping file CSV
    :return: overlapping_usernames
    """
    if mapping_file_path:
        source_usernames = set(source_user_df['target_username'])
    else:
        source_usernames = set(source_user_df['source_username'])
    target_usernames = set(target_user_df['target_username'])
    overlapping_usernames = source_usernames.intersection(target_usernames)
    return list(overlapping_usernames)


def p_body(p):
    """string_body : '{' string_list '}'
       asg_body    : '{' asg_list    '}'
       rule_body   : '{' rule_list   '}'
    """
    p[0] = p[2]


def lightcurves_to_zipfile(dataset, lcfnames, outzipfile):
    """
    This writes light curves to a zip associated with dataset.

    """


def perm_orbit(p, i):
    """
    Returns the orbit of an integer `i` under the permutation `p`

    EXAMPLES::

        sage: from surface_dynamics.misc.permutation import perm_orbit
        sage: perm_orbit([0,3,1,2],2)
        [2, 1, 3]
    """
    res = [i]
    j = p[i]
    while j != i:
        res.append(j)
        j = p[j]
    return res


def protocolVersion():
    """OAI-PMH protocol version (should always be '2.0')
        """


def pgettext_tip(msgid: str, msgctxt: str):
    """Try to translate the given msgid (with optional msgctxt), if tooltips’ translation is enabled.

    :param msgid: The string to translate.
    :type msgid: str
    :param msgctxt: The translation context (defaults to BLT_I18NCONTEXT_DEFAULT).
    :type msgctxt: str
    :return:  The translated string (or msgid if no translation was found).
    """
    pass


@classmethod
def from_json(cls, user_id, timestamp, json):
    """Builds a MessageRead object from JSON provided by the API.

        Args:
            user_id: An integer Messenger ID of the user who triggered the
                    event.
            timestamp: An integer timestamp (in milliseconds since epoch) of
                    the event.
            json: A dict containing the JSON representation that is converted
                  into the MessageRead object.

        Returns:
            A MessageRead object.

        """
    return cls(user_id, timestamp, json['watermark'], json['seq'])


def getid(obj):
    """Extracts object ID.

    Abstracts the common pattern of allowing both an object or an
    object's ID (UUID) as a parameter when dealing with relationships.
    """
    try:
        return obj.id
    except AttributeError:
        return obj


def assure_tuple_or_list(obj):
    """Given an object, wrap into a tuple if not list or tuple
    """
    if isinstance(obj, list) or isinstance(obj, tuple):
        return obj
    return obj,


def get_views(key):
    """ store here all views
        think of cut single view, to parts
        store data with alpha layer

        info - not used for now
    """
    data = {'view_00': 1, 'view_01': 1, 'view_02': 1, 'view_03': 1}
    return data[key]


@classmethod
def abulk(cls, x):
    """
        calculate the bulk (relaxed) lattice parameter of the Al_{x}Ga_{1-x}As
        alloy
        """
    return cls.aGaAs + 0.0078 * x


def get_canvas_width() ->int:
    """Returns the canvas width.

    :return:  The canvas width.
    """
    pass


def publish(requestor, service, nodeIdentifier, items):
    """
        Called when a publish request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to publish to.
        @type nodeIdentifier: C{unicode}
        @param items: The items to be published as elements.
        @type items: C{list} of C{Element<twisted.words.xish.domish.Element>}
        @return: deferred that fires on success.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


def fill_grid(span: int=1, offset: int=0, use_interp_simple: bool=False):
    """Fill grid from two loops

    :param span: Span, Number of sides (zero disables)
    :type span: int
    :param offset: Offset, Number of sides (zero disables)
    :type offset: int
    :param use_interp_simple: Simple Blending
    :type use_interp_simple: bool
    """
    pass


def format_symbol(s):
    """
    Output a consistent format for expected symbols we expect the user to
    input as-is.
    """
    return '`{0}`'.format(s)


@classmethod
def parse(cls, options):
    """parse command line options and load configuration"""
    config_file = options.get('config')
    data_file = options.get('data')
    config = cls(config_file, data_file)
    return config


def create_all(graph):
    """
    Create all database tables.

    """
    graph.dynamodb.create_schema()


@classmethod
def validate_security(cls, app, ssl_options=None):
    """Check the application's security.

        Show messages, or abort if necessary, based on the security configuration.
        """
    if not app.ip:
        warning = (
            'WARNING: The Jupyter server is listening on all IP addresses')
        if ssl_options is None:
            app.log.warning(warning +
                ' and not using encryption. This is not recommended.')
        if not app.password and not app.token:
            app.log.warning(warning +
                ' and not using authentication. This is highly insecure and not recommended.'
                )
    elif not app.password and not app.token:
        app.log.warning(
            'All authentication is disabled.  Anyone who can connect to this server will be able to run code.'
            )


def distinct(lst, uniqueness_function):
    """ Returns a list in the same order with just the elements with a distinct
	value on the uniqueness_function.
	I.e.: `distinct([1, 5, 7, 9], lambda x: x % 3)` would return [1, 5, 9]."""
    values = []
    keys = []
    for v in lst:
        k = uniqueness_function(v)
        if k not in keys:
            keys.append(k)
            values.append(v)
    return values


def get_homopol_run(var):
    """
    Return the largest contiguous homopolymer run of the variant allele,
    or None if it isn't present in the VCF.
    """
    return var.INFO.get('HRun')


def respond_to_SIGHUP(signal_number, frame, logger=None):
    """raise the KeyboardInterrupt which will cause the app to effectively
    shutdown, closing all it resources.  Then, because it sets 'restart' to
    True, the app will reread all the configuration information, rebuild all
    of its structures and resources and start running again"""
    global restart
    restart = True
    if logger:
        logger.info('detected SIGHUP')
    raise KeyboardInterrupt


def abuts(a, b):
    """Return True if a and b "touch" the same interbase coordinate without overlapping (symmetric)"""
    return a.start == b.end or a.end == b.start


def expected(decorator, func):
    """ Decorate ``func`` with ``decorator`` if ``func`` is not wrapped yet. """
    return decorator(func) if not hasattr(func, '_api') else func


def read_numpy(fh, byteorder, dtype, count, offsetsize):
    """Read tag data from file and return as numpy array."""
    dtype = 'b' if dtype[-1] == 's' else byteorder + dtype[-1]
    return fh.read_array(dtype, count)


def is_integer_like(val):
    """Returns validation of a value as an integer."""
    try:
        int(val)
        return True
    except (TypeError, ValueError, AttributeError):
        return False


def provider_parser(subparser):
    """Module provider for Aliyun"""
    subparser.description = """
        Aliyun Provider requires an access key id and access secret with full rights on dns.
        Better to use RAM on Aliyun cloud to create a specified user for the dns operation.
        The referrence for Aliyun DNS production:
        https://help.aliyun.com/product/29697.html"""
    subparser.add_argument('--auth-key-id', help=
        'specify access key id for authentication')
    subparser.add_argument('--auth-secret', help=
        'specify access secret for authentication')


def is_bytes(obj):
    """Helper method to see if the object is a bytestring.

    >>> is_bytes(b'foo')
    True
    """
    return type(obj) is bytes


@classmethod
def count(cls):
    """Returns the number of items in the enumeration."""
    return len(cls.__members__)


@staticmethod
def getCreateTable():
    """Create the table to hold the addresses"""
    return 'create table ipv4addr (addr char(15))'


def score_substitute(a_c1, a_c2):
    """Score substitution of two characters.

    Args:
      a_c1 (str): first word to compare
      a_c2 (str): second word to compare

    Returns:
      int: 2 if the last characters of both words are equal, -3 otherwise

    """
    return 2 if a_c1[-1] == a_c2[-1] else -3


def support_mapper(support, package):
    """
    Update support and bug tracking url.
    https://getcomposer.org/doc/04-schema.md#support
    """
    package.bug_tracking_url = support.get('issues') or None
    package.code_view_url = support.get('source') or None
    return package


@classmethod
def param(cls, names, *, values=None, units=None, limits=None, funcs=None):
    """Add modifiers to a specific parameter.

        See Action for more information.
        """
    return super().param(names, cls.build_converter(values=values, units=
        units, limits=limits, funcs=funcs))


def _translate_message(message):
    """Translate the Message model to a dict."""
    return {'id': message['id'], 'project_id': message['project_id'],
        'request_id': message['request_id'], 'resource_type': message[
        'resource_type'], 'resource_uuid': message.get('resource_uuid'),
        'event_id': message['event_id'], 'detail_id': message['detail_id'],
        'action_id': message['action_id'], 'message_level': message[
        'message_level'], 'created_at': message['created_at'], 'expires_at':
        message.get('expires_at')}


def check_notwanted(zelf, *args, **kwargs):
    """ whether an object is not desired. """
    not_want = args[0]
    for key, value in not_want.items():
        if key == 'format':
            continue
        if key not in zelf:
            continue
        if value in zelf[key]:
            return True
    return False


@classmethod
def purge(cls):
    """Clear the expression compilation cache."""
    cls._CACHE.clear()


def validate(*args, **kwargs):
    """function to validate the data in kwargs"""
    fields_to_check = args
    errors = []
    for field in fields_to_check:
        if kwargs.get(field) is None or kwargs.get(field).strip() == '':
            errors.append('{} is required and cannot be empty'.format(field))
    return not len(errors) > 0, errors


def farthest_point_in_path(pt, path):
    """returns (|path.seg.point(t)-pt|, t, seg_idx) where t and seg_idx
    maximize the distance between pt and curve path[idx].point(t) for 0<=t<=1
    and any seg_idx.
    :rtype : object
    :param pt:
    :param path:
    Warning:  Multiple such global maxima can exist.  This will only return
    one."""
    return path.radialrange(pt)[1]


def aggregate_sart(data, sub_num):
    """
    Aggregate data from the SART task.

    Calculates various summary statistics for the SART task for a given subject.

    Parameters
    ----------
    data : dataframe
        Pandas dataframe containing a single subjects trial data for the task.
    sub_num : str
        Subject number to which the data file belongs.

    Returns
    -------
    stats : list
        List containing the calculated data for the subject.
    """
    follow_error_rt = data.loc[data.accuracy.shift() == 0, 'RT'].mean()
    follow_correct_rt = data.loc[data.accuracy.shift() == 1, 'RT'].mean()
    total_rt = data['RT'].mean()
    total_rtsd = data['RT'].std()
    total_rtcov = total_rtsd / total_rt
    frequent_rt = data[data['stimulus'] != 3]['RT'].mean()
    frequent_rtsd = data[data['stimulus'] != 3]['RT'].std()
    frequent_rtcov = frequent_rtsd / frequent_rt
    infrequent_rt = data[data['stimulus'] == 3]['RT'].mean()
    infrequent_rtsd = data[data['stimulus'] == 3]['RT'].std()
    infrequent_rtcov = infrequent_rtsd / infrequent_rt
    sart_error_count = data[data['stimulus'] == 3]['key press'].sum()
    sart_errors_num_items = data[data['stimulus'] == 3].shape[0]
    sart_errors_prop = sart_error_count / sart_errors_num_items
    return [sub_num, follow_error_rt, follow_correct_rt, total_rt,
        total_rtsd, total_rtcov, frequent_rt, frequent_rtsd, frequent_rtcov,
        infrequent_rt, infrequent_rtsd, infrequent_rtcov, sart_error_count,
        sart_errors_prop, sart_errors_num_items]


def type_of_tag(tag):
    """
    Returns type of a tag.

    :param tag: tag ID
    :type tag: int
    :rtype: int

    Examples:

        >>> type_of_tag(HEADER)
        2
        >>> type_of_tag(MASK)
        6

    """
    return tag & 255


def to_kusto_datetime(dt):
    """format date strings to kusto literals"""
    for t in ('now', 'ago'):
        if dt.startswith(t):
            return dt
    return 'datetime(' + str(dt) + ')'


def _effect_level(effect_size, method='cohend'):
    """
    Determines magnitude of effect size.
    """
    if not isinstance(method, str):
        raise TypeError('method must be of type str')
    if method not in ['cohend', 'cliffdelta']:
        raise ValueError(
            "method must be one of the following strings: 'cohend', 'cliffdelta'"
            )
    effect_size = abs(effect_size)
    if method == 'cliffdelta':
        if effect_size < 0.147:
            return 'negligible'
        elif effect_size < 0.33:
            return 'small'
        elif effect_size < 0.474:
            return 'medium'
        else:
            return 'large'
    if method == 'cohend':
        if effect_size < 0.2:
            return 'negligible'
        elif effect_size < 0.5:
            return 'small'
        elif effect_size < 0.8:
            return 'medium'
        else:
            return 'large'


def stroke_flip():
    """Change direction of the points of the selected strokes

    """
    pass


def lookup(obj, name):
    """
    Return attribute or item with the given name in collection `obj`.

    :raise LookupError:
      If `obj` has no attribute nor item with the given name.

    This is meant for cases when different versions of an API may
    either return a dictionary (hence, key/``__getitem__``-based
    lookup) or an object/namespace (hence, ``.``/``getattr``-style
    lookup) and you want to handle them in a uniform way.

    The following examples demo it::

      >>> D = {'a':1, 'b':2}
      >>> lookup(D, 'a')
      1
      >>> lookup(D, 'c')
      Traceback (most recent call last):
        ...
      LookupError: Object ... has no attribute nor key named `c`

      >>> class X(object):
      ...   a = 1
      ...   b = 2
      >>> x = X()
      >>> lookup(x, 'a')
      1
      >>> lookup(x, 'c')
      Traceback (most recent call last):
        ...
      LookupError: Object ... has no attribute nor key named `c`
    """
    try:
        return getattr(obj, name)
    except AttributeError:
        pass
    try:
        return obj[name]
    except (KeyError, TypeError):
        pass
    raise LookupError('Object {0} has no attribute nor key named `{1}`'.
        format(obj, name))


def get(object):
    """Get the value of the field for the given object."""


@staticmethod
def void_request():
    """
        Get a transaction void :class:`paynlsdk.api.transaction.voidauthorization.Request` instance

        :return: Transaction void request instance
        :rtype: paynlsdk.api.transaction.voidauthorization.Request
        """
    from paynlsdk.api.transaction.voidauthorization import Request
    return Request()


def dual_edges(overstrand, graph):
    """
    Find the set of crossings and edges of the dual graph encountered
    by moving along the link starting at startcep for length crossings.
    Also returns the next crossing entry point immediately after.
    """
    edges_crossed = []
    for cep in overstrand:
        f1 = graph.edge_to_face[cep]
        f2 = graph.edge_to_face[cep.opposite()]
        edges_crossed.append(graph.edges_between(f1, f2).pop())
    endpoint = overstrand[-1].next()
    final_f1 = graph.edge_to_face[endpoint]
    final_f2 = graph.edge_to_face[endpoint.opposite()]
    edges_crossed.append(graph.edges_between(final_f1, final_f2).pop())
    return edges_crossed


def VariableType(VariableType):
    """
            Variable Type (eg. WaterLevel or Discharge)
        """
    return VariableType


def p_const_map_item(p):
    """const_map_item : const_value ':' const_value """
    p[0] = [p[1], p[3]]


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Alignak live state history'
    return 'livesynthesisretention'


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

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

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

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


def write_length(l, o):
    """ Put a 32-bit length into four bytes in o

    Equivalent to struct.pack('<i', l), but suitable for numba-jit
    """
    right_byte_mask = 255
    for _ in range(4):
        o.write_byte(l & right_byte_mask)
        l >>= 8


@staticmethod
def export_path(config: dict) ->str:
    """
        Method to get the rundeck export file in absolute
        path format.

        :param config: The `Rundeck` section of the configuration.
        :returns: The file path of rundeck resources to export to.
        """
    return config.get('export_path', '') if config else ''


def _cli_download_url(cli):
    u"""Download from 'url' into file 'fname'"""
    verbose = False
    try:
        verbose = cli.OUT.isatty()
    except AttributeError:
        pass
    verbose = verbose and not cli.quiet
    if cli.fname.EXISTS:
        raise cli.Error(42, 'file %s already exists' % cli.fname)
    cli.fname.download(cli.url, chunksize=cli.chunksize, ticker=verbose,
        pipe=cli.OUT)
    if verbose:
        cli.OUT.write("download of '%s' succeed\n" % cli.fname)


def zoom_in(zoomfacx: float=0.0, zoomfacy: float=0.0):
    """Zoom in the view

    :param zoomfacx: Zoom Factor X
    :type zoomfacx: float
    :param zoomfacy: Zoom Factor Y
    :type zoomfacy: float
    """
    pass


def dix_entiers_carre():
    """
    fait la somme des dix premiers entiers au carré

    :returns: nombre réel

    .. faqref::
        :tag: python
        :title: Quelle est la différence entre return et print ?

        La fonction ``print`` sert à afficher un résultat sur la sortie standard.
        Elle peut être utilisée à tout moment
        mais elle n'a pas d'impact sur le déroulement programme. Le mot-clé ``return``
        n'est utilisé que dans une fonction. Lorsque le programme rencontre
        une instruction commençant par ``return``, il quitte la fonction
        et transmet le résultat à l'instruction qui a appelé la fonction.
        La fonction ``print`` ne modifie pas votre algorithme. La fonction ``return``
        spécifie le résultat de votre fonction : elle modifie l'algorithme.

    .. exref::
        :title: calcul de la somme des dix premiers entiers au carré
        :tag: Base

        Ce calcul simple peut s'écrire de diffèrentes manières.

        .. runpython::
            :showcode:

            s = 0
            for i in range(1,11):
                s += i**2

            print(s)

        D'une façon abrégée :

        .. runpython::
            :showcode:

            s = sum ( [ i**2 for i in range(1,11) ] )

            print(s)
    """
    s = 0
    for i in range(1, 11):
        s += i ** 2
    return s


def break_clusters(entrez_records: dict, guaranteed: list) ->None:
    """
    Sets the `cluster_rep` variable to True for each EntrezRecord with its num_id found in guaranteed.

    :param entrez_records: Dictionary mapping unique TreeSAPP numerical IDs to Cluster instances
    :param guaranteed: List of sequences to be set to cluster representatives to ensure they are retained downstream
    :return: None
    """
    for num_id in entrez_records:
        if num_id in guaranteed:
            er = entrez_records[num_id]
            er.cluster_rep = True
    return


def lambd_CO2_SO4_HMW84(T, P):
    """n-a: carbon-dioxide sulfate [HMW84]."""
    lambd = 0.097
    valid = T == 298.15
    return lambd, valid


def _partition_data(datavol, roivol, roivalue, maskvol=None, zeroe=True):
    """ Extracts the values in `datavol` that are in the ROI with value `roivalue` in `roivol`.
    The ROI can be masked by `maskvol`.

    Parameters
    ----------
    datavol: numpy.ndarray
        4D timeseries volume or a 3D volume to be partitioned

    roivol: numpy.ndarray
        3D ROIs volume

    roivalue: int or float
        A value from roivol that represents the ROI to be used for extraction.

    maskvol: numpy.ndarray
        3D mask volume

    zeroe: bool
        If true will remove the null timeseries voxels.  Only applied to timeseries (4D) data.

    Returns
    -------
    values: np.array
        An array of the values in the indicated ROI.
        A 2D matrix if `datavol` is 4D or a 1D vector if `datavol` is 3D.
    """
    if maskvol is not None:
        indices = (roivol == roivalue) * (maskvol > 0)
    else:
        indices = roivol == roivalue
    if datavol.ndim == 4:
        ts = datavol[(indices), :]
    else:
        ts = datavol[indices]
    if zeroe:
        if datavol.ndim == 4:
            ts = ts[(ts.sum(axis=1) != 0), :]
    return ts


@classmethod
def unit_attname(cls, unit_str):
    """
        Retrieve the unit attribute name for the given unit string.
        For example, if the given unit string is 'metre', return 'm'.
        Raise an exception if an attribute cannot be found.
        """
    lower = unit_str.lower()
    if unit_str in cls.UNITS:
        return unit_str
    elif lower in cls.UNITS:
        return lower
    elif lower in cls.LALIAS:
        return cls.LALIAS[lower]
    else:
        raise Exception(
            'Could not find a unit keyword associated with "%s"' % unit_str)


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

        :param DeviceChangeIpWebDetails val:
        :rtype: EventDetails
        """
    return cls('device_change_ip_web_details', val)


def axlbool(value):
    """ convert suds.sax.text.Text to python bool
    """
    if value is None:
        return None
    if not value:
        return False
    if value.lower() == 'true':
        return True
    return False


def _is_name_start(css, pos):
    """Return true if the given character is a name-start code point."""
    c = css[pos]
    return c in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_' or ord(
        c) > 127


@staticmethod
def _sentence_tokenizer_merge_matches(match):
    """ Best way we found to deal with repeating groups"""
    start, end = match.span()
    return match.string[start:end] + '<SPLIT>'


def bin_extractor(fname, offset, length):
    """Extract a junk of data from a file.
    """
    fp = open(fname)
    fp.seek(offset)
    data = fp.read(length)
    return data


@classmethod
def matches(cls, element):
    """
        class method to verify that this enhancer is appropriate
        for the provided webelement
        """
    return cls.__TAG__.lower() == element.tag_name.lower()


def get_flag_param_decals_from_bool(option_name: str) ->str:
    """Return a '--do/not-do' style flag param"""
    name = option_name.replace('_', '-')
    return f'--{name}/--no-{name}'


@staticmethod
def from_config(config, section, option):
    """Obtain the value of this type from a RawConfigParser.

        Receives a RawConfigParser instance, a str section name, and the str
        option in that section to retrieve.

        The implementation may assume the option exists in the RawConfigParser
        instance.

        Implementations are not expected to validate the value. But, they
        should return the appropriate Python type.
        """


def find_key_in_list(key, key_list):
    """
    Look for the right corresponding key in a list.

    key has to start with an given key from the list and the longest key
    will be returned.

    Parameters
    ----------
    key : str
        Given key.
    key_list : list of str
        Valid keys to be checked against.

    Returns
    -------
    found_key : :class:`str` or :class:`None`
        The best match. None if nothing was found.
    """
    found = []
    for try_key in key_list:
        if key.startswith(try_key):
            found.append(try_key)
    if found:
        found_key = max(found, key=len)
        if found_key:
            return found_key
    return None


def hub_timer_stacks(state=False):
    """Toggles whether or not the hub records the stack when timers are set.
    To inspect the stacks of the current timers, call :func:`format_hub_timers`
    at critical junctures in the application logic.
    """
    from eventlet.hubs import timer
    timer._g_debug = state


def __call__(cls, *args, **kwds):
    """Instantiate cls after preprocessing its token definitions."""
    if '_tokens' not in cls.__dict__:
        cls._all_tokens = {}
        cls._tmpname = 0
        if hasattr(cls, 'token_variants') and cls.token_variants:
            pass
        else:
            cls._tokens = cls.process_tokendef('', cls.get_tokendefs())
    return type.__call__(cls, *args, **kwds)


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

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


def path_join(part1, part2):
    """join two url paths."""
    if len(part2) == 0:
        return part1
    sep = '/'
    if part1[-1] == sep:
        sep = ''
    return part1 + sep + part2


def get_day_today_quote(dropna=False):
    """
    得到今日个股实时股价数据（包括停牌的股）
    :param dropna: 是否删除空行（即是否包括停牌的股）
    :return: DataFrame
    """
    pass


def patch_build_step():
    """
    Changes the default attributes on BuildStep so that:

    - alwaysRun = False
    - flunkOnFailure = True
    - flunkOnWarnings = False
    - haltOnFailure = True
    - warnOnFailure = False
    - warnOnWarnings = True

    I.e.: A build step must always cause the build to fail if it fails and, in that case, BuildBot
    must not execute other build steps in a builder.
    """
    from buildbot.process.buildstep import BuildStep
    BuildStep.alwaysRun = False
    BuildStep.flunkOnFailure = True
    BuildStep.flunkOnWarnings = False
    BuildStep.haltOnFailure = True
    BuildStep.warnOnFailure = False
    BuildStep.warnOnWarnings = True


def __new__(metacls, __name__, __bases__, __dict__):
    """Add include constructer to class."""
    cls = super().__new__(metacls, __name__, __bases__, __dict__)
    cls.add_constructor('!include', cls.construct_include)
    cls.add_constructor('include!', cls.construct_include)
    return cls


def w2cw(w, e):
    """Transform from *w* value to column *w* count value, using the
    *e.css('cw')* (column width) as column measure."""
    gw = e.gw
    cw = e.css('cw', 0)
    if cw + gw:
        return (w + gw) / (cw + gw)
    return 0


def snomed_to_umls(cdb, pickle_path):
    """ Map SNOMED CDB to UMLS concepts
    """
    import pickle
    data = pickle.load(open(pickle_path, 'rb'))
    for key in data.keys():
        for umls_cui in data[key]:
            if 'S-' in str(key):
                cui = key
            else:
                cui = 'S-' + str(key)
            if cui in cdb.cui2info:
                if 'umls' in cdb.cui2info[cui]:
                    cdb.cui2info[cui]['umls'].append(umls_cui)
                else:
                    cdb.cui2info[cui]['umls'] = [umls_cui]


def do_get_user_info(author, appkey):
    """
    Get a struct with user info
    """
    return {'userid': author.id, 'firstname': getattr(author.user,
        'first_name', ''), 'lastname': getattr(author.user, 'last_name', ''
        ), 'nickname': author.user.username, 'email': author.user.email,
        'url': author.get_absolute_url()}


def load_zope(finder, module):
    """the zope package is distributed in multiple packages and they need to be
       stitched back together again."""
    module.ExtendPath()


def add_argument_branch(parser):
    """Add a ``--branch`` argument to the parser."""
    parser.add_argument('-b', '--branch', help=
        """The GitHub branch to use to {} the package(s).
Cannot specify both the branch and the tag."""
        .format(parser.get_command_name()))


@staticmethod
def shape(tensor):
    """Return the shape of a tensor"""
    raise NotImplementedError


def _get_output_dict(obj, name, func):
    """ return an output dict.  """
    out = func(obj)
    if isinstance(out, dict):
        return out
    else:
        if name.startswith('get_'):
            name = name[4:]
        elif name.startswith('_get_'):
            name = name[5:]
        return {name: out}


def material_drop(object: str='Object', material: str='Material'):
    """Drag material to object in Outliner

    :param object: Object, Target Object
    :type object: str
    :param material: Material, Target Material
    :type material: str
    """
    pass


def expm1(data=None, out=None, name=None, **kwargs):
    """Returns ``exp(x) - 1`` computed element-wise on the input.

    This function provides greater precision than ``exp(x) - 1`` for small values of ``x``.

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

       - expm1(default) = default
       - expm1(row_sparse) = row_sparse
       - expm1(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_logexp.cc:L224

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

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

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


def exclude_paths(root, exclude, dockerfile, client):
    """
    Exclude paths from the build context.

    * root: root file path
    * exclude: exclude patterns
    * dockerfile: *Dockerfile* file-path in the context
    * client: containerization context
    * **return:** filtered files
    """
    files = client.exclude_paths_from_context(root, exclude, dockerfile)
    return files


@staticmethod
def piece_file(input_f, chunk_size):
    """
        Provides a streaming interface to file data in chunks of even size, which
        avoids memoryerrors from loading whole files into RAM to pass to `pieces`.
        """
    chunk = input_f.read(chunk_size)
    total_bytes = 0
    while chunk:
        yield chunk
        chunk = input_f.read(chunk_size)
        total_bytes += len(chunk)


def indent(input_string: str, indentation: int) ->str:
    """
    Indent the given string.

        :param input_string: The string to indent. If the string spans several lines, every line will be indented
                             (assumed separator \\\\n).
        :param indentation: Number of spaces used to indent every line of the input string.

    """
    return ' ' * indentation + input_string.replace('\n', '\n' + ' ' *
        indentation)


def _getitem_from_frame(f_locals, key, default=None):
    """
    f_locals is not guaranteed to have .get(), but it will always
    support __getitem__. Even if it doesnt, we return ``default``.
    """
    try:
        return f_locals[key]
    except Exception:
        return default


def formula_2016_01_01(foyer_fiscal, period, parameters):
    """
        Investissements dans les DOM-TOM dans le cadre d'une entreprise.
        """
    fhaa = foyer_fiscal('fhaa', period)
    fhab = foyer_fiscal('fhab', period)
    fhac = foyer_fiscal('fhac', period)
    fhae = foyer_fiscal('fhae', period)
    fhaf = foyer_fiscal('fhaf', period)
    fhag = foyer_fiscal('fhag', period)
    fhah = foyer_fiscal('fhah', period)
    fhaj = foyer_fiscal('fhaj', period)
    fhak = foyer_fiscal('fhak', period)
    fhal = foyer_fiscal('fhal', period)
    fham = foyer_fiscal('fhal', period)
    fhao = foyer_fiscal('fhao', period)
    fhap = foyer_fiscal('fhap', period)
    fhaq = foyer_fiscal('fhaq', period)
    fhar = foyer_fiscal('fhar', period)
    fhat = foyer_fiscal('fhat', period)
    fhau = foyer_fiscal('fhau', period)
    fhav = foyer_fiscal('fhav', period)
    fhaw = foyer_fiscal('fhaw', period)
    fhay = foyer_fiscal('fhay', period)
    fhba = foyer_fiscal('fhba', period)
    fhbb = foyer_fiscal('fhbb', period)
    fhbe = foyer_fiscal('fhbe', period)
    fhbg = foyer_fiscal('fhbg', period)
    fhbi = foyer_fiscal('fhbi', period)
    fhbj = foyer_fiscal('fhbj', period)
    fhbk = foyer_fiscal('fhbk', period)
    fhbm = foyer_fiscal('fhbm', period)
    fhbn = foyer_fiscal('fhbn', period)
    fhbo = foyer_fiscal('fhbo', period)
    fhbp = foyer_fiscal('fhbp', period)
    fhbr = foyer_fiscal('fhbr', period)
    fhbs = foyer_fiscal('fhbs', period)
    fhbt = foyer_fiscal('fhbt', period)
    fhbu = foyer_fiscal('fhbu', period)
    fhbw = foyer_fiscal('fhbw', period)
    fhbx = foyer_fiscal('fhbx', period)
    fhby = foyer_fiscal('fhby', period)
    fhbz = foyer_fiscal('fhbz', period)
    fhcb = foyer_fiscal('fhcb', period)
    fhcc = foyer_fiscal('fhcc', period)
    fhcd = foyer_fiscal('fhcd', period)
    fhce = foyer_fiscal('fhce', period)
    fhcg = foyer_fiscal('fhcg', period)
    fhci = foyer_fiscal('fhci', period)
    fhcj = foyer_fiscal('fhcj', period)
    fhck = foyer_fiscal('fhck', period)
    fhcm = foyer_fiscal('fhcm', period)
    fhcn = foyer_fiscal('fhcn', period)
    fhco = foyer_fiscal('fhco', period)
    fhcp = foyer_fiscal('fhcp', period)
    fhcr = foyer_fiscal('fhcr', period)
    fhcs = foyer_fiscal('fhcs', period)
    fhct = foyer_fiscal('fhct', period)
    fhcu = foyer_fiscal('fhcu', period)
    fhcw = foyer_fiscal('fhcw', period)
    fhnu = foyer_fiscal('fhnu', period)
    fhnv = foyer_fiscal('fhnv', period)
    fhnw = foyer_fiscal('fhnw', period)
    fhny = foyer_fiscal('fhny', period)
    fhpa = foyer_fiscal('fhpa', period)
    fhpb = foyer_fiscal('fhpb', period)
    fhpd = foyer_fiscal('fhpd', period)
    fhpe = foyer_fiscal('fhpe', period)
    fhpf = foyer_fiscal('fhpf', period)
    fhph = foyer_fiscal('fhph', period)
    fhpi = foyer_fiscal('fhpi', period)
    fhpj = foyer_fiscal('fhpj', period)
    fhpl = foyer_fiscal('fhpl', period)
    fhpm = foyer_fiscal('fhpm', period)
    fhpn = foyer_fiscal('fhpn', period)
    fhpo = foyer_fiscal('fhpo', period)
    fhpp = foyer_fiscal('fhpp', period)
    fhpr = foyer_fiscal('fhpr', period)
    fhps = foyer_fiscal('fhps', period)
    fhpt = foyer_fiscal('fhpt', period)
    fhpu = foyer_fiscal('fhpu', period)
    fhpw = foyer_fiscal('fhpw', period)
    fhpx = foyer_fiscal('fhpx', period)
    fhpy = foyer_fiscal('fhpy', period)
    fhqe = foyer_fiscal('fhqe', period)
    fhqf = foyer_fiscal('fhqf', period)
    fhqg = foyer_fiscal('fhqg', period)
    fhqi = foyer_fiscal('fhqi', period)
    fhqo = foyer_fiscal('fhqo', period)
    fhqp = foyer_fiscal('fhqp', period)
    fhqr = foyer_fiscal('fhqr', period)
    fhqv = foyer_fiscal('fhqv', period)
    fhrg = foyer_fiscal('fhrg', period)
    fhri = foyer_fiscal('fhri', period)
    fhrj = foyer_fiscal('fhrj', period)
    fhrk = foyer_fiscal('fhrk', period)
    fhrl = foyer_fiscal('fhrl', period)
    fhrm = foyer_fiscal('fhrm', period)
    fhro = foyer_fiscal('fhro', period)
    fhrp = foyer_fiscal('fhrp', period)
    fhrq = foyer_fiscal('fhrq', period)
    fhrr = foyer_fiscal('fhrr', period)
    fhrt = foyer_fiscal('fhrt', period)
    fhru = foyer_fiscal('fhru', period)
    fhrv = foyer_fiscal('fhrv', period)
    fhrw = foyer_fiscal('fhrw', period)
    fhry = foyer_fiscal('fhry', period)
    fhsa = foyer_fiscal('fhsa', period)
    fhsb = foyer_fiscal('fhsb', period)
    fhsc = foyer_fiscal('fhsc', period)
    fhse = foyer_fiscal('fhse', period)
    fhsf = foyer_fiscal('fhsf', period)
    fhsg = foyer_fiscal('fhsg', period)
    fhsh = foyer_fiscal('fhsh', period)
    fhsj = foyer_fiscal('fhsj', period)
    fhsk = foyer_fiscal('fhsk', period)
    fhsl = foyer_fiscal('fhsl', period)
    fhsm = foyer_fiscal('fhsm', period)
    fhso = foyer_fiscal('fhso', period)
    fhsp = foyer_fiscal('fhsp', period)
    fhsq = foyer_fiscal('fhsq', period)
    fhsr = foyer_fiscal('fhsr', period)
    fhst = foyer_fiscal('fhst', period)
    fhsu = foyer_fiscal('fhsu', period)
    fhsv = foyer_fiscal('fhsv', period)
    fhsw = foyer_fiscal('fhsw', period)
    fhsz = foyer_fiscal('fhsz', period)
    fhta = foyer_fiscal('fhta', period)
    fhtb = foyer_fiscal('fhtb', period)
    fhtd = foyer_fiscal('fhtd', period)
    return (fhci + fhcj + fhck + fhcm + fhcn + fhco + fhcp + fhcr + fhcs +
        fhct + fhcu + fhcw + fhbi + fhbj + fhbk + fhbm + fhbn + fhbo + fhbp +
        fhbr + fhbs + fhbt + fhbu + fhbw + fhbx + fhby + fhbz + fhcb + fhcc +
        fhcd + fhce + fhcg + fhaa + fhab + fhac + fhae + fhaf + fhag + fhah +
        fhaj + fhak + fhal + fham + fhao + fhap + fhaq + fhar + fhat + fhau +
        fhav + fhaw + fhay + fhba + fhbb + fhbe + fhbg + fhsa + fhsb + fhsf +
        fhsg + fhsc + fhsh + fhse + fhsj + fhsk + fhsl + fhsp + fhsq + fhsm +
        fhsr + fhso + fhst + fhsu + fhsv + fhsw + fhsz + fhta + fhtb + fhtd +
        fhnu + fhnv + fhnw + fhny + fhpa + fhpb + fhpd + fhpe + fhpf + fhph +
        fhpi + fhpj + fhpl + fhpm + fhpn + fhpo + fhpp + fhpr + fhps + fhpt +
        fhpu + fhpw + fhpx + fhpy + fhqe + fhqf + fhqg + fhqi + fhqo + fhqp +
        fhqr + fhqv + fhrg + fhri + fhrj + fhrk + fhrl + fhrm + fhro + fhrp +
        fhrq + fhrr + fhrt + fhru + fhrv + fhrw + fhry)


def translate_aa_change_vep(pos_field, aa_change_field):
    """
    Translate an amino acid change in snpeff 4.1+ to 3.6 form.

    :param str aa_change_field: The field containing the aa change
    :return: The changed amino acid(s) in the for <REF><POS><ALT>
    :rtype: str

    >>> translate_aa_change_vep('144-145', 'GC/-')
    'GC144'
    >>> translate_aa_change_vep('479-480', 'DS/X')
    'DS479?'
    >>> translate_aa_change_vep('87-88', '-/QL')
    '-87QL'
    >>> translate_aa_change_vep('100', 'G/R')
    'G100R'
    >>> translate_aa_change_vep('102-103', 'W/X')
    'W102?'
    >>> translate_aa_change_vep('17', 'Y/*')
    'Y17*'
    >>> translate_aa_change_vep('174', 'YR/W')
    'YR174W'
    >>> translate_aa_change_vep('175', 'R/WL')
    'R175WL'
    >>> translate_aa_change_vep('175', 'R')
    'R175R'
    """
    aa_change_field = aa_change_field.split('/')
    if len(aa_change_field) == 1:
        aa_change_field = aa_change_field + aa_change_field
    pos_field = pos_field.split('/')[0].split('-')[0]
    if aa_change_field[1].endswith('X'):
        aa_change_field[1] = '?'
    elif aa_change_field[1] == '-':
        aa_change_field[1] = ''
    prefix, pos, suffix = aa_change_field[0], pos_field, aa_change_field[1]
    return prefix + pos + suffix


def argmax_channel(data=None, out=None, name=None, **kwargs):
    """Returns argmax indices of each channel from the input array.

    The result will be an NDArray of shape (num_channel,).

    In case of multiple occurrences of the maximum values, the indices corresponding to the first occurrence
    are returned.

    Examples::

      x = [[ 0.,  1.,  2.],
           [ 3.,  4.,  5.]]

      argmax_channel(x) = [ 2.,  2.]

    Defined in src/operator/tensor/broadcast_reduce_op_index.cc:L97

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

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

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


def as_float(width, height):
    """Return a decimal ratio like 1.7777...."""
    return width / height


def _const_compare_digest_backport(a, b):
    """
    Compare two digests of equal length in constant time.

    The digests must be of type str/bytes.
    Returns True if the digests match, and False otherwise.
    """
    result = abs(len(a) - len(b))
    for l, r in zip(bytearray(a), bytearray(b)):
        result |= l ^ r
    return result == 0


def data_unlink():
    """Unlink active Grease Pencil data-block

    """
    pass