@staticmethod
def _parse_flag(key, value, param):
    """Parses both standard --flag and --on/--off switch style of flags
        This is complicated by the fact that the following values are accepted in the command file:
        - flag: False
        - flag: True
        - on: True
        - on: False
        - off: True
        - off: False
        This creates semantic difficulties.

        For a standard flag, the behavior depends on the default value. In click a flag with a
        default value of True becomes False when the flag is used, and a flag with a default value
        of False becomes True when the flag is used. In the command file, a value of True is
        interpreted to mean that the user wants to pass the flag into the command, which leads to
        the following truth table:

        Default | Value | Result
        -------------------------
        True    | True  | False
        True    | False | True
        False   | True  | True
        False   | False | False

        For switch-style flags, the behavior does not depend on the default value of the flag.
        Instead, using the --on/--off example, --on always results in True, and --off always
        results in False. Therefore, an "on: False" value in the command file is equivalent to
        "off: True", and an "off: False" value in the command file is equivalent to "on: True".
        The secondary name in this example is --off.
        This yields the following truth table (using the --on/--off example):

        Name | Secondary | Value | Result
        ---------------------------------
        on   | False     | True  | True
        on   | False     | False | False
        off  | True      | True  | False
        off  | True      | False | True
        """
    is_switch_flag = bool(param.secondary_opts)
    if not is_switch_flag:
        return value != param.default
    else:
        is_using_secondary = ('--' + key in param.secondary_opts or '-' +
            key in param.secondary_opts)
        return value != is_using_secondary


def start_application(ApplicationName=None, InputConfigurations=None):
    """
    Starts the specified Amazon Kinesis Analytics application. After creating an application, you must exclusively call this operation to start your application.
    After the application starts, it begins consuming the input data, processes it, and writes the output to the configured destination.
    The application status must be READY for you to start an application. You can get the application status in the console or using the  DescribeApplication operation.
    After you start the application, you can stop the application from processing the input by calling the  StopApplication operation.
    This operation requires permissions to perform the kinesisanalytics:StartApplication action.
    See also: AWS API Documentation

    :example: response = client.start_application(
        ApplicationName='string',
        InputConfigurations=[
            {
                'Id': 'string',
                'InputStartingPositionConfiguration': {
                    'InputStartingPosition': 'NOW'|'TRIM_HORIZON'|'LAST_STOPPED_POINT'
                }
            },
        ]
    )

    :type ApplicationName: string
    :param ApplicationName: [REQUIRED]
            Name of the application.

    :type InputConfigurations: list
    :param InputConfigurations: [REQUIRED]
            Identifies the specific input, by ID, that the application starts consuming. Amazon Kinesis Analytics starts reading the streaming source associated with the input. You can also specify where in the streaming source you want Amazon Kinesis Analytics to start reading.
            (dict) --When you start your application, you provide this configuration, which identifies the input source and the point in the input source at which you want the application to start processing records.
            Id (string) -- [REQUIRED]Input source ID. You can get this ID by calling the DescribeApplication operation.
            InputStartingPositionConfiguration (dict) -- [REQUIRED]Point at which you want the application to start processing records from the streaming source.
            InputStartingPosition (string) --The starting position on the stream.
            LATEST - Start reading just after the most recent record in the stream.
            TRIM_HORIZON - Start reading at the last untrimmed record in the stream, which is the oldest record available in the stream. This option is not available for an Amazon Kinesis Firehose delivery stream.
            LAST_STOPPED_POINT - Resume reading from where the application last stopped reading.

    :rtype: dict
    :return: {}

    :returns:
    (dict) --

    """
    pass


def mapper(val):
    """A mapping from data space to axis space"""
    raise NotImplementedError


def _nbaLeague(x):
    """Takes in initials of league and returns numeric API Code

    Input Values: "NBA", "WNBA", or "NBADL"

    Used in: _Draft.Anthro(), _Draft.Agility(), _Draft.NonStationaryShooting(),
    _Draft.SpotUpShooting(), _Draft.Combine()

    """
    leagues = {'NBA': '00', 'WNBA': '10', 'NBADL': '20'}
    try:
        return leagues[x.upper()]
    except:
        raise ValueError(
            "Please use one of the following values for League: 'NBA', 'WNBA', 'NBADL'"
            )


def particle_system_remove():
    """Remove the selected particle system

    """
    pass


@classmethod
def read_iter(cls, file_name, start=None, stop=None, step=None, atom_i=None):
    """
        Create an iterator over each frame of the given trajectory file
        in the selected range.

        Parameters
        ----------
        file_name : str
            The path of the file to be read.
            A file-like-object cannot be used.
        start : int, optional
            The frame index, where file parsing is started. If no value
            is given, parsing starts at the first frame.
            The index starts at 0.
        stop : int, optional
            The exclusive frame index, where file parsing ends.
            If no value is given, parsing stops at the end of file.
            The index starts at 0.
        step : int, optional
            If this value is set, the function reads only every n-th
            frame from the file.
        atom_i : ndarray, dtype=int, optional
            If this parameter is set, only the atoms at the given
            indices are read from each frame.

        Yields
        ------
        coord : ndarray, dtype=float32, shape=(n,3)
            The atom coordinates in the current frame.
        box : ndarray, dtype=float32, shape=(3,3)
            The box vectors of the current frame.
        time : float
            the simlation time of the current frame in *ps*.

        See also
        --------
        read_iter_structure

        Notes
        -----
        The `step` parameter does currently not work for *DCD* files.
        """
    traj_type = cls.traj_type()
    with traj_type(file_name, 'r') as f:
        if start is None:
            start = 0
        if start != 0:
            f.read(n_frames=start, stride=None, atom_indices=atom_i)
        if stop is None:
            n_frames = None
        else:
            n_frames = stop - start
        if step is not None and n_frames is not None:
            n_frames = (n_frames - 1) // step + 1
        frame_i = 0
        while True:
            if n_frames is not None and frame_i >= n_frames:
                break
            result = f.read(1, stride=step, atom_indices=atom_i)
            if len(result[0]) == 0:
                break
            coord, box, time = cls.process_read_values(result)
            coord = coord[0]
            box = box[0] if box is not None else None
            time = float(time[0]) if time is not None else None
            yield coord, box, time
            frame_i += 1


def _assemble_master_key_providers(primary_provider, *providers):
    """Given one or more MasterKeyProvider instance, loads first MasterKeyProvider instance
    with all remaining MasterKeyProvider instances.

    :param primary_provider: MasterKeyProvider to use as the primary (ie: generates the Data Key)
    :type primary_provider: aws_encryption_sdk.key_providers.base.MasterKeyProvider
    :param *providers: MasterKeyProviders to add to primary_provider
    :returns: primary_provider with all other providers added to it
    :rtype: aws_encryption_sdk.key_providers.base.MasterKeyProvider
    """
    for provider in providers:
        primary_provider.add_master_key_provider(provider)
    return primary_provider


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

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


def channel_squeeze(x, groups):
    """
    Channel squeeze operation.

    Parameters:
    ----------
    x : Tensor
        Input tensor.
    groups : int
        Number of groups.

    Returns
    -------
    Tensor
        Resulted tensor.
    """
    batch, channels, height, width = x.size()
    channels_per_group = channels // groups
    x = x.view(batch, channels_per_group, groups, height, width).sum(dim=2)
    return x


def sec_to_m(num):
    """
    >>> sec_to_m(66)
    '01:06'
    """
    template = '%02d:%02d'
    minute = 0
    second = 0
    if num < 59:
        second = num
    elif num > 60:
        minute = num / 60
        second = num % 60
    return template % (minute, second)


def midpoint_point_point(a, b):
    """Compute the midpoint of two points lying in the XY-plane.

    Parameters
    ----------
    a : sequence of float
        XYZ coordinates of the first point.
    b : sequence of float
        XYZ coordinates of the second point.

    Returns
    -------
    list
        XYZ coordinates of the midpoint.

    """
    return [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1]), 0.5 * (a[2] + b[2])]


def reorder(bdd, order=None):
    """Apply Rudell's sifting algorithm to `bdd`.

    @param order: reorder to this specific order,
        if `None` then invoke group sifting
    @type order: `dict: str -> int` that maps
        variable names to levels
    """


def getKYratioDifference(Economy, param_name, param_count, center, spread,
    dist_type):
    """
    Finds the difference between simulated and target capital to income ratio in an economy when
    a given parameter has heterogeneity according to some distribution.

    Parameters
    ----------
    Economy : cstwMPCmarket
        An object representing the entire economy, containing the various AgentTypes as an attribute.
    param_name : string
        The name of the parameter of interest that varies across the population.
    param_count : int
        The number of different values the parameter of interest will take on.
    center : float
        A measure of centrality for the distribution of the parameter of interest.
    spread : float
        A measure of spread or diffusion for the distribution of the parameter of interest.
    dist_type : string
        The type of distribution to be used.  Can be "lognormal" or "uniform" (can expand).

    Returns
    -------
    diff : float
        Difference between simulated and target capital to income ratio for this economy.
    """
    Economy(LorenzBool=False, ManyStatsBool=False)
    Economy.distributeParams(param_name, param_count, center, spread, dist_type
        )
    Economy.solve()
    diff = Economy.calcKYratioDifference()
    print('getKYratioDifference tried center = ' + str(center) +
        ' and got ' + str(diff))
    return diff


def append_resource_info(main_curr, chunk_db):
    """
    Append the resource info from a chunk_db
    to the main database.
    """
    cmd = 'attach ? as toMerge'
    main_curr.execute(cmd, (chunk_db,))
    cmd = 'INSERT INTO resources SELECT * FROM toMerge.resources'
    main_curr.execute(cmd)
    cmd = 'detach toMerge'
    main_curr.execute(cmd)


def escape_ansi(line):
    """It removes the ansi codes from a string."""
    import re
    ansi_escape = re.compile('(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]')
    return ansi_escape.sub('', line)


def years_since_vernal_equinox(dt):
    """Fractional years since last March 20, noon UTC (assumed time of
    vernal equinox)."""
    year_start = type(dt)(dt.year, 3, 20, 12)
    year_end = type(dt)(dt.year + 1, 3, 20, 12)
    return (dt - year_start).total_seconds() / (year_end - year_start
        ).total_seconds()


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

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

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


def ode_runge_kutta_4(func, x, q, time, dt):
    """
    ODE integration using 4th-order Runge-Kutta approximation.

    Parameters
    ----------
    func : function
        Function defining the system dynamics.

    x : (dim_x, ) ndarray
        Previous system state.

    q : (dim_q, ) ndarray
        System (process) noise.

    time : (dim_par, ) ndarray
        Time index.

    dt : float
        Discretization step.

    Returns
    -------
    : (dim_x, ) ndarray
        State in the next time step.
    """
    dt2 = 0.5 * dt
    k1 = func(x, q, time)
    k2 = func(x + dt2 * k1, q, time)
    k3 = func(x + dt2 * k2, q, time)
    k4 = func(x + dt * k3, q, time)
    return x + dt / 6 * (k1 + 2 * (k2 + k3) + k4)


def show_one_level(open: bool=True):
    """Expand/collapse all entries by one level

    :param open: Open, Expand all entries one level deep
    :type open: bool
    """
    pass


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

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

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


def generate_supper_efficiency_lower_bound():
    """ Returns lower bound of the inverse of efficiency score for
        a super efficiency envelopment model.

        Note:
            This function only works with output-oriented envelopment models.

        Returns:
            double: 0, since efficiency score might be greater
                than 1 for super efficient output-oriented envelopment model.
    """
    return 0


def iterbytes(b):
    """Iterate over bytes, returning bytes instead of ints (python3)"""
    if isinstance(b, memoryview):
        b = b.tobytes()
    i = 0
    while True:
        a = b[i:i + 1]
        i += 1
        if a:
            yield a
        else:
            break


def parse_dos_file(dos_lines):
    """
    Parses the returned DOS.X files.
    Structure:
    (100(1x,e10.3))   e,totdos,interstitial,vac1,vac2,
    (at(i),i=1,ntype),((q(l,i),l=1,LMAX),i=1,ntype)
    where e is the energy in eV (= 1/27.2 htr) at(i) is the local DOS of a
    single atom of the i'th atom-type and q(l,i) is the l-resolved DOS at
    the i'th atom but has to be multiplied by the number of atoms of this type.

    :param dos_lines: string of the read in dos file
    :param number_of_atom_types: integer, number of atom types
    """
    return 0


def _assign_renderer(class_reference, base_path, engine=None):
    """
    Assign the renderer to the given controller-type class.

    `class_reference` is a reference to a class type, not an instance of a class.

    The first argument called `source` is a name of the package containing templates and static contents.

    The second argument called `renderer_type` is a name of a renderer-type class used to override the default renderer.

    To use this, suppose we have a class called `DummyController` and later instantiate
    a variable `dummy_controller` as an instance of class `DummyController`. `class_reference`
    will be `DummyController`, not `dummy_controller`.

    Note that this method is not for direct use. You can invoke via `@renderer` or the
    configuration file only via `tori.application.Application`.

    Additionally, the arguments might be different if the renderer is not the default one.
    """
    class_reference._template_base_path = base_path
    class_reference._template_engine = engine
    return class_reference


def backimage_move():
    """Move Node backdrop

    """
    pass


def kwargs_to_dict(kwargs):
    """Return the kwargs dictionary list as a dictionary instead."""
    out_dict = {}
    for key, value in kwargs.items():
        out_dict[key] = value
    return out_dict


def custom_rstrip(s: str) ->str:
    """
    A custom rstrip that only strips the last Enter if it exists,
    keeping the other whitespace characters. This allows outputing
    values with whitespace formatting at the end, while handling
    the most common case of a single echo with an enter.

    """
    if s and s[-1] == '\n':
        s = s[0:-1]
    return s


def _build_simple_row(padded_cells, rowfmt):
    """Format row according to DataRow format without padding."""
    begin, sep, end = rowfmt
    return (begin + sep.join(padded_cells) + end).rstrip()


def logMessage(message):
    """Logs the message at the appropriate place."""


def write_binary_symbol(fd):
    """
        Write a binary symbol
    """
    fd.write(str.encode('\x00B'))


def _parse_flight_condition(mach_line):
    """reads a flight condition line"""
    mach = float(mach_line[0:10].strip())
    alt = float(mach_line[10:20].strip())
    pstag = float(mach_line[20:30].strip())
    tstag = float(mach_line[30:40].strip())
    igas = int(mach_line[40:41].strip())
    nalpha_beta = int(mach_line[41:43].strip())
    try:
        ideriv = int(mach_line[43].strip())
        dangle = float(mach_line[45:55].strip())
    except:
        raise
    assert igas in [0, 1], igas
    return mach, alt, pstag, tstag, igas, nalpha_beta, ideriv, dangle


@classmethod
def handle_fork(cls):
    """
        Called after a forking.  This should cleanup any remaining reactor state
        from the parent process.
        """
    pass


def remplace_couleur(grille, couleur_originale, nouvelle_couleur):
    """ Remplace toutes les occurences de `couleur_originale` dans la grille
    par `nouvelle_couleur`.
    """
    grille[grille == couleur_originale] = nouvelle_couleur


def count_uniq_by_field(data_frame, field):
    """Count unique values for field

    Args:
        data_frame (DataFrame): data
        field (str): field name

    Returns:
        list: Statistics for HTTP responses
    """
    http_stats = data_frame.proto_code.value_counts().rename_axis(field
        ).reset_index(name='count')
    percent = data_frame.proto_code.value_counts(normalize=True) * 100
    http_stats['percent'] = percent.values
    return http_stats


def channel_shuffle2(x, channels_per_group):
    """
    Channel shuffle operation from 'ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices,'
    https://arxiv.org/abs/1707.01083. The alternative version.

    Parameters:
    ----------
    x : Symbol or NDArray
        Input tensor.
    channels_per_group : int
        Number of channels per group.

    Returns
    -------
    Symbol or NDArray
        Resulted tensor.
    """
    return x.reshape((0, -4, channels_per_group, -1, -2)).swapaxes(1, 2
        ).reshape((0, -3, -2))


def select(extend: bool=False, deselect_all: bool=False, location: float=(
    0.0, 0.0)):
    """Select tracking markers

    :param extend: Extend, Extend selection rather than clearing the existing selection
    :type extend: bool
    :param deselect_all: Deselect On Nothing, Deselect all when nothing under the cursor
    :type deselect_all: bool
    :param location: Location, Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds
    :type location: float
    """
    pass


def __filter_overlap(index):
    """Filters indexes in list if they overlap."""
    if len(index) == 2:
        return index
    index_f = []
    i = 0
    j = i + 1
    while j < len(index):
        if index[i][1] > index[j][0]:
            index[i] = min(index[i][0], index[j][1]), max(index[i][0],
                index[j][1])
            j += 1
        else:
            index_f += [index[i]]
            i = j
            j += 1
    index_f += [index[i]]
    return index_f[:i + 1]


def split_by_group_count(lst, group_count):
    """按组个数，尽可能平均分配列表中的元素到各个组中。
	"""
    import math
    groups = []
    sorted_list = sorted(lst)
    list_size = len(sorted_list)
    if group_count >= list_size:
        groups.append(lst)
    else:
        group_size = int(list_size / group_count)
        for group_index in range(0, group_count):
            start_index = group_size * group_index
            end_index = group_size * (group_index + 1)
            end_index = (list_size if group_index == group_count - 1 else
                end_index)
            group = sorted_list[start_index:end_index]
            groups.append(group)
    return groups


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 __delitem__(name):
    """ Remove the object from this folder stored under ``name``.

        ``name`` must be a Unicode object or a bytestring object.

        If ``name`` is a bytestring object, it must be decodable using the
        system default encoding or the UTF-8 encoding.

        If no object is stored in the folder under ``name``, raise a
        :exc:`KeyError`.

        When the object stored under ``name`` is removed from this folder,
        remove its ``__parent__`` and ``__name__`` values.

        When this method is called, emit an ``IObjectWillBeRemoved`` event
        before the object loses its ``__name__`` or ``__parent__`` values.
        Emit an ``IObjectRemoved`` after the object loses its ``__name__``
        and ``__parent__`` value,
        """


def _get_name(applicant):
    """
    The <person> element is nested in the <name> element and contains fields
    that identify the subject in the request.
    """
    person = {'person': {'first': applicant['first_name'], 'last':
        applicant['last_name']}}
    mid_name = applicant.get('middle_name')
    if mid_name:
        person['person']['middle'] = mid_name
    return person


def is_none_type(tp) ->bool:
    """Checks whether a type is a `None' type."""
    return tp is type(None)


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

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

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


def login_name(key):
    """
        Get user login name for a user or an internal user id.
        """


def is_int(obj):
    """
    True & False is not considered valid integers even if python considers them 1 & 0 in some versions
    """
    return isinstance(obj, int) and not isinstance(obj, bool)


def as_undir(g):
    """view of g as an undirected graph"""
    return g.to_undirected(as_view=True)


def is_tagged(item_type, item_id, user_id, tag):
    """Did <user_id> apply tag <tag> on <item_type> <item_id>?"""


def getid(obj):
    """Get obj's uuid or object itself if no uuid

    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.uuid
    except AttributeError:
        return obj


def ex_path(path):
    """
    Take a path that is sent to the Sub and expand it if it is a string or not
    """
    if path is None:
        return []
    elif isinstance(path, str):
        return path.split(',')
    elif isinstance(path, list):
        return path
    return []


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


def update_on_value(tdict, tkey, value, first=True):
    """
    Update target dictionary and set tdict[tkey] to value, if value exists and
    is not None. If the value in question is a sequence, first controls,
    whether only the first element should be used as value.
    """
    if value is not None:
        if first and isinstance(value, (list, tuple)):
            if len(value) > 0:
                tdict[tkey] = value[0]
        else:
            tdict[tkey] = value


def field_erected_tank_purchase_cost(V):
    """
    Return the purchase cost [USD] of a single, field-erected vessel assuming
    stainless steel construction material.

    Parameters
    ----------
    V : float
        Volume of tank [m^3].

    Returns
    -------
    Cp : float
        Purchase cost [USD].

    Notes
    -----
    The purchase cost is given by [1]_.

    If :math:`V < 2 \\cdot 10^3`:

        :math:`C_p^{2007} = 32500.0 + 79.35 V`

    Otherwise:

        :math:`C_p^{2007} = 125000.0 + 47.1 V`

    Examples
    --------
    >>> from biosteam.units._tank import field_erected_vessel_purchase_cost
    >>> field_erected_vessel_purchase_cost(300)
    112610.0

    """
    if V < 2000.0:
        Cp = 65000.0 + 158.7 * V
    else:
        Cp = 250000.0 + 94.2 * V
    return Cp


def asXML():
    """ Render a full XML representation of a lock for WebDAV,
        used when returning the value of a newly created lock. """


@staticmethod
def _update_cap_gain_income(cap_gain_change, calc):
    """
        Implement capital gain change induced by behavioral responses.
        """
    calc.records.p23250 = calc.records.p23250 + cap_gain_change
    return calc


def graph_select_box(xmin: int=0, xmax: int=0, ymin: int=0, ymax: int=0,
    wait_for_input: bool=True, deselect: bool=False, extend: bool=True):
    """Select curve points using box selection

    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param wait_for_input: Wait for Input
    :type wait_for_input: bool
    :param deselect: Deselect, Deselect rather than select items
    :type deselect: bool
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


@classmethod
def export_journal(cls, journal):
    """Returns a string representation of an entire journal."""
    vars = {'journal': journal, 'entries': journal.entries, 'tags': journal
        .tags}
    return cls.template.render_block('journal', **vars)


def bc_robin(matrix_lhs, matrix_rhs, positions, grad_n_bc, a_val, b_val, c_val
    ):
    """
    Function to enforce the Boundary Condition in the Robin formalism:

                    a * (df / dn) + b * f + c = O

    Parameters
    ----------
    matrix_lhs: Left Hand Side square matrix (shape (size_i_w * size_j_ns)^2)
    matrix_rhs: Right Hand Side vector (shape (size_i_w * size_j_ns))
    positions: indices of lines corresponding to the patch being processed
    grad_n_bc: normal gradient to boundary nodes
    a_val: value of the "a" Robin parameter
    b_val: value of the "b" Robin parameter
    c_val: value of the "a" Robin parameter

    Returns
    -------
    Altered left-hand side matrix and right-hand side vector
    """
    for row in positions:
        if grad_n_bc.count_nonzero():
            matrix_lhs[(row), :] = a_val * grad_n_bc[(row), :]
        matrix_lhs[row, row] += b_val
    matrix_rhs[positions] = -c_val
    return matrix_lhs, matrix_rhs


def get():
    """Return information about a web app's configuration"""
    raise NotImplementedError


def face_vert_separate(face: 'bmesh.types.BMFace', vert: 'bmesh.types.BMVert'):
    """Rip a vertex in a face away and add a new vertex.

    :param face: The face to separate.
    :type face: 'bmesh.types.BMFace'
    :param vert: A vertex in the face to separate.
    :type vert: 'bmesh.types.BMVert'
    """
    pass


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

        :param SmarterSmartSyncPolicyChangedType val:
        :rtype: EventType
        """
    return cls('smarter_smart_sync_policy_changed', val)


def sign(x):
    """Sign of a number.  Note only works for single values, not arrays."""
    return -1 if x < 0 else 1


def _dlib_proc(obj_func, pp, space_params, is_int, result_queue, i, space_vals
    ):
    """
    Add/overwrite problem params with params given from dlib,
    then run objective function and put the result in the given queue
    """
    for j, key in enumerate(space_params):
        pp[key] = int(space_vals[j]) if is_int[j] else space_vals[j]
    result = obj_func(**pp, pid=i)
    result_queue.put((i, result))


@classmethod
def get_default(cls):
    """
        Return default parameters for this model.
        """
    return {'name': cls.model_name, 'defaults': cls.defaults}


def param_name(p):
    """Extract parameter name from attributes.

    Examples
    --------
    - ``fix_x`` -> ``x``
    - ``error_x`` -> ``x``
    - ``limit_x`` -> ``x``

    """
    prefix = ['limit_', 'error_', 'fix_']
    for prf in prefix:
        if p.startswith(prf):
            i = len(prf)
            return p[i:]
    return p


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

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


def get_link_href(result_object, link_relation):
    """
    Given a result_object (returned by a previous API call), return
    the link href for a link relation.

    'result_object' a JSON object returned by a previous API call. May not
    be None.
    'link_relation' the link relation for which href is required.

    Returns None if the link does not exist.
    """
    assert result_object is not None
    result = None
    link = result_object['_links'].get(link_relation)
    if link:
        result = link.get('href')
    return result


def removeSub(sub):
    """Remove a sub-registry to the node.

        .. caution:: This method should *not* be used manually. It is
            automatically called by `setNext`. To remove a registry from the
            tree, use ``sub.setNext(None)`` instead!
        """


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


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

        :param str val:
        :rtype: AddMemberSelectorError
        """
    return cls('unverified_dropbox_id', val)


@classmethod
def endpoint(cls):
    """Return the :class:`sandman.model.Model`'s endpoint.

        :rtype: string

        """
    endpoint = ''
    if cls.__endpoint__ is not None:
        return cls.__endpoint__
    elif cls.__from_class__ is not None:
        endpoint = cls.__from_class__.__name__.lower()
    else:
        endpoint = cls.__tablename__.lower()
    if not endpoint.endswith('s'):
        endpoint += 's'
    return endpoint


def parse_secs_to_str(duration=0) ->str:
    """
    Do the reverse operation of :py:func:`parse_str_to_secs`.

    Parse a number of seconds to a human-readable string.
    The string has the form XdXhXmXs. 0 units are removed.

    :param int duration: The duration, in seconds.
    :return: A formatted string containing the duration.
    :rtype: :py:class:`str`

    >>> parse_secs_to_str(3601)
    '1h1s'
    """
    secs, mins, hours, days = 0, 0, 0, 0
    result = ''
    secs = duration % 60
    mins = duration % 3600 // 60
    hours = duration % 86400 // 3600
    days = duration // 86400
    result += '%dd' % days if days else ''
    result += '%dh' % hours if hours else ''
    result += '%dm' % mins if mins else ''
    result += '%ds' % secs if secs else ''
    if not result:
        result = '0s'
    return result


def _create_dimensions(dim_names, dim_lens, rootgrp):
    """Create the dimensions in the NetCDF file."""
    for dim in zip(dim_names, dim_lens):
        rootgrp.createDimension(dim[0], dim[1])


@staticmethod
def _normalize(data):
    """Normalize data to the range [0, 1].

        This is done by substracting to each value its integer part, leaving only
        the decimal part, and then shifting the sign of the negative values.
        """
    data = data - data.astype(int)
    data[data < 0] = -data[data < 0]
    return data


@staticmethod
def _column_value(obj, key):
    """ Returns the value from a queryset item
        """
    if isinstance(obj, dict):
        return obj.get(key, None)
    return getattr(obj, key, None)


def pformat(obj, verbose=False):
    """Prettyprint an object.  Either use the `pretty` library or the
    builtin `pprint`.
    """
    try:
        from pretty import pretty
        return pretty(obj, verbose=verbose)
    except ImportError:
        from pprint import pformat
        return pformat(obj)


def mode(list_):
    """ Return the mode of a list. """
    return max(set(list_), key=list(list_).count)


def escape_line_delimited_text(text: str) ->str:
    """
    Convert a single text possibly containing newlines and other troublesome whitespace
    into a string suitable for writing and reading to a file where newlines will
    divide up the texts.

    Args:
      text: The text to convert.

    Returns:
      The text with newlines and whitespace taken care of.
    """
    return text.replace('\n', ' ').strip()


def extract_value(field, obj):
    """
    >>> js = {'id': 123, 'user': {'name': 'mary'}}
    >>> extract_value('id', js)
    123
    >>> extract_value('user', js)
    {'name': 'mary'}
    >>> extract_value('user.name', js)
    'mary'
    >>> extract_value('-', js)
    {'id': 123, 'user': {'name': 'mary'}}
    >>> extract_value('not_valid', js)
    """
    if field == '-':
        return obj
    parts = field.split('.')
    for p in parts:
        obj = obj.get(p)
        if obj is None:
            break
    return obj


@classmethod
def from_pretrained(cls, vocab, name, **cfg):
    """Create a PyTT_TokenVectorEncoder instance using pre-trained weights
        from a PyTorch Transformer model, even if it's not installed as a
        spaCy package.

        vocab (spacy.vocab.Vocab): The spaCy vocab to use.
        name (unicode): Name of pre-trained model, e.g. 'bert-base-uncased'.
        RETURNS (PyTT_TokenVectorEncoder): The token vector encoder.
        """
    cfg['from_pretrained'] = True
    cfg['pytt_name'] = name
    model = cls.Model(**cfg)
    self = cls(vocab, model=model, **cfg)
    return self


def swap():
    """Swap order of selected strips within tracks

    """
    pass


def p_trailer_2(p):
    """trailer : LPAR arglist RPAR"""
    p[0] = p[2]


def info():
    """One line upgrade description."""
    return 'Separation of groups and accounts modules.'


def stem_ip_addr(ip_addr, subnets_to_keep):
    """Return the first N subnets of the IP address"""
    split = ip_addr.split('.')
    return '.'.join(split[:subnets_to_keep])


@classmethod
def del_obj(cls, tenant_id, obj):
    """Delete the tenant obj. """
    del cls.serv_obj_dict[tenant_id]


def rolling_apply(df, window, func, shift=1, *args, **kwargs):
    """Calculate rolling apply() to all columns of a pandas dataframe

    Function can be used by ApplyFunc module.

    :param pd.DataFrame df: input pandas dataframe
    :param int window: size of rolling window.
    :param func: function to be applied
    :param int shift: size of shift. default is 1.
    :param args: args passed on to function
    :param kwargs: kwargs passed on to function
    :return: df with rolling results of function applied to all columns
    """
    return df.shift(shift).rolling(window).apply(func, raw=False, args=args,
        **kwargs)


def vif(img_true, img_test):
    """
    Implemented later..
    """
    pass


def caller_module(level=2, sys=sys):
    """Return the module object from which the call was made. For instance, if
    A defined in module M makes a call to B and B, by calling this function,
    can know the module of the caller."""
    module_globals = sys._getframe(level).f_globals
    module_name = module_globals.get('__name__') or '__main__'
    module = sys.modules[module_name]
    return module


def is_message(message):
    """
    Checks that message has msg data.
    Return (from, to, encoding, message) or None.
    """
    try:
        if message['action'] == 'msg':
            return message['from'], message['to'], message['encoding'
                ], message['message']
    except Exception:
        pass
    return None


def weakchecksum(data):
    """
    Generates a weak checksum from an iterable set of bytes.
    """
    a = b = 0
    l = len(data)
    for i in range(l):
        a += data[i]
        b += (l - i) * data[i]
    return b << 16 | a, a, b


def _channels_list_to_dict(channels):
    """ Helper function to parse a list of channels to a dict of channels

    The keys will be `channel_(i+1)`, where i is the index of the list of
    channels. These keys will be used to make the different channels
    available in the Comlink object via e.g. `comlink.channel_1`.

    Parameters
    ----------

    channels : list
        List of ComlinkChannel objects

    Returns
    -------

    channel_dict : dict

    """
    channel_dict = {}
    for i, channel in enumerate(channels):
        channel_dict['channel_' + str(i + 1)] = channel
    return channel_dict


def set_persistent_base():
    """Reset the copy of the mesh that is being sculpted on

    """
    pass


def set_http_caching(request, gateway='crab', region='permanent'):
    """
    Set an HTTP Cache Control header on a request.

    :param pyramid.request.Request request: Request to set headers on.
    :param str gateway: What gateway are we caching for? Defaults to `crab`.
    :param str region: What caching region to use? Defaults to `permanent`.
    :rtype: pyramid.request.Request
    """
    crabpy_exp = request.registry.settings.get(
        'crabpy.%s.cache_config.%s.expiration_time' % (gateway, region), None)
    if crabpy_exp is None:
        return request
    ctime = int(int(crabpy_exp) * 1.05)
    request.response.cache_expires(ctime, public=True)
    return request


def make_variogram_3D(nug, nst, it1, cc1, azi1, dip1, hmax1, hmed1, hmin1,
    it2=1, cc2=0, azi2=0, dip2=0, hmax2=0, hmed2=0, hmin2=0):
    """Make a dictionary of variogram parameters for application with spatial
    estimation and simulation.

    :param nug: Nugget constant (isotropic)
    :param nst: Number of structures (up to 2)
    :param it1: Structure of 1st variogram (1: Spherical, 2: Exponential, 3: Gaussian)
    :param cc1: Contribution of 2nd variogram
    :param azi1: Azimuth of 1st variogram
    :param dip1: Dip of 1st variogram
    :param hmax1: Range in major direction (Horizontal)
    :param hmed1: Range in minor direction (Horizontal)
    :param hmin1: Range in vertical direction
    :param it2: Structure of 2nd variogram (1: Spherical, 2: Exponential, 3: Gaussian)
    :param cc2: Contribution of 2nd variogram
    :param azi2: Azimuth of 2nd variogram
    :param dip1: Dip of 2nd variogram
    :param hmax2: Range in major direction (Horizontal)
    :param hmed2: Range in minor direction (Horizontal)
    :param hmin2: Range in vertical direction
    :return: TODO
    """
    if cc2 == 0:
        nst = 1
    var = dict([('nug', nug), ('nst', nst), ('it1', it1), ('cc1', cc1), (
        'azi1', azi1), ('dip1', dip1), ('hmax1', hmax1), ('hmed1', hmed1),
        ('hmin1', hmin1), ('it2', it2), ('cc2', cc2), ('azi2', azi2), (
        'dip2', dip2), ('hmax2', hmax2), ('hmed2', hmed2), ('hmin2', hmin2)])
    if nug + cc1 + cc2 != 1:
        print(
            '\x1b[0;30;41m make_variogram Warning: sill does not sum to 1.0, do not use in simulation \x1b[0m'
            )
    if (cc1 < 0 or cc2 < 0 or nug < 0 or hmax1 < 0 or hmax2 < 0 or hmin1 <
        0 or hmin2 < 0):
        print(
            '\x1b[0;30;41m make_variogram Warning: contributions and ranges must be all positive \x1b[0m'
            )
    if hmax1 < hmed1 or hmax2 < hmed2:
        print(
            '\x1b[0;30;41m make_variogram Warning: major range should be greater than minor range \x1b[0m'
            )
    return var


@classmethod
def _check_exist_hash(cls, hash_key):
    """
        指定されたハッシュキーのレコードがあるか判定する

        :param hash_key: 検索対象値
        :return: bool
        """
    return hash_key in cls._mapped


def _stringify(text):
    """
    Get the text as a string representation

    @param text: Something convertible to str
    @return: Printable string
    """
    try:
        text = str(text)
    except UnicodeEncodeError:
        text = text.encode('utf-8')
    return text


def BoundToDiff(a, dim=-1):
    """
    Calculate the first order difference between
    neighbors along dimension
    """
    from numpy import diff
    return diff(a, axis=dim)


def to_table(stream_set):
    """
    Returns string representation of the data in tabular form using the tabulate
    library.
    """
    try:
        from tabulate import tabulate
    except ImportError:
        raise ImportError(
            'Please install tabulate to use this transformation function.')
    return tabulate(stream_set.to_dict(), headers='keys')


def shortest_torus_path_length(source, destination, width, height):
    """Get the length of a shortest path from source to destination using
    wrap-around links.

    See http://jhnet.co.uk/articles/torus_paths for an explanation of how this
    method works.

    Parameters
    ----------
    source : (x, y, z)
    destination : (x, y, z)
    width : int
    height : int

    Returns
    -------
    int
    """
    w, h = width, height
    x = destination[0] - source[0]
    y = destination[1] - source[1]
    z = destination[2] - source[2]
    x, y = x - z, y - z
    x %= w
    y %= h
    length = x if x > y else y
    wrap_x = w - x + y
    if wrap_x < length:
        length = wrap_x
    wrap_y = x + h - y
    if wrap_y < length:
        length = wrap_y
    dx = w - x
    dy = h - y
    wrap_xy = dx if dx > dy else dy
    if wrap_xy < length:
        return wrap_xy
    else:
        return length


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


def list_replace(subject_list, replacement, string):
    """
    To replace a list of items by a single replacement
    :param subject_list: list
    :param replacement: string
    :param string: string
    :return: string
    """
    for s in subject_list:
        string = string.replace(s, replacement)
    return string


def layer_new(name: str=''):
    """Add new mask layer for masking

    :param name: Name, Name of new mask layer
    :type name: str
    """
    pass


def get_char(value):
    """Get the Unicode char."""
    return chr(value)


def pull(ctx, path_base):
    """Pulls new data from a remote repository master branch.

    Any local changes will be lost.

    """
    with ctx.cd(path_base):
        ctx.run('git reset --hard')
        ctx.run('git pull origin master')


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


def format_currency(value, places=2, show_zero=True):
    """
    Formats value currency format like: $1,500.25

    :param places:
        number of decimal places to show.
    :param show_zero:
        When true, zero should be formatted.
        When false, zero should be empty string.
    """
    if value in (0, None) and not show_zero:
        return ''
    return '${value:,.{precision}f}'.format(value=value or 0, precision=places)


def forcefield_toggle():
    """Toggle object’s force field

    """
    pass


def _recv_n_set_rq(event):
    """Logging handler when an N-SET-RQ is received.

    Parameters
    ----------
    event : events.Event
        The evt.EVT_DIMSE_RECV event that occurred.
    """
    pass


@classmethod
def getWizards(cls):
    """ Return all Wizard subclasses from all plugins for this domain."""
    return cls.__getSubclasses('wizards', cls._wizardClass)


def describe_load_balancer_attributes(LoadBalancerName=None):
    """
    Describes the attributes for the specified load balancer.
    See also: AWS API Documentation

    Examples
    This example describes the attributes of the specified load balancer.
    Expected Output:

    :example: response = client.describe_load_balancer_attributes(
        LoadBalancerName='string'
    )

    :type LoadBalancerName: string
    :param LoadBalancerName: [REQUIRED]
            The name of the load balancer.

    :rtype: dict
    :return: {
        'LoadBalancerAttributes': {
            'CrossZoneLoadBalancing': {
                'Enabled': True|False
            },
            'AccessLog': {
                'Enabled': True|False,
                'S3BucketName': 'string',
                'EmitInterval': 123,
                'S3BucketPrefix': 'string'
            },
            'ConnectionDraining': {
                'Enabled': True|False,
                'Timeout': 123
            },
            'ConnectionSettings': {
                'IdleTimeout': 123
            },
            'AdditionalAttributes': [
                {
                    'Key': 'string',
                    'Value': 'string'
                },
            ]
        }
    }

    """
    pass


def handle_loopback(erlport, method, *args, **kwargs):
    """Loopback request. Send back `args` and `kwargs` a tuple. Primarily used
    for Erlang to Python validation"""
    return list(args), kwargs


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

        :param PaperDefaultFolderPolicyChangedType val:
        :rtype: EventType
        """
    return cls('paper_default_folder_policy_changed', val)


def chunks(lst, size):
    """Yield successive sized chunks from lst."""
    for i in range(0, len(lst), size):
        yield lst[i:i + size]


def sig_stars(p):
    """Return a R-style significance string corresponding to p values."""
    if p < 0.001:
        return '***'
    elif p < 0.01:
        return '**'
    elif p < 0.05:
        return '*'
    elif p < 0.1:
        return '.'
    return ''


def _dof(mean_tau, sd_tau2):
    """
    Returns the degrees of freedom for the chi-2 distribution from the mean and
    variance of the uncertainty model, as reported in equation 5.5 of Al Atik
    (2015)
    """
    return 2.0 * mean_tau ** 4.0 / sd_tau2 ** 2.0


def fix_field_cache(model):
    """
    Remove duplicate entries in the field cache of the specified model
    in order to fix Django issue #10808
    """
    new_cache = []
    used_fields = {}
    for parent in model._meta.get_parent_list():
        for f in parent._meta.local_fields:
            used_fields[f.name] = f
            used_fields[f.attname] = f
    for f in model._meta.local_fields:
        if not (used_fields.get(f.name) or used_fields.get(f.attname) or None):
            new_cache.append(f)
    model._meta.local_fields = new_cache


def parse_path(s3_datapath):
    """
    Return bucket and prefix from full s3 path.

    Parameters
    ----------
    s3_datapath : str
        path to a bucket.
        Should be of the form s3://bucket/prefix/.

    Returns
    -------
    tuple
        bucket and prefix.
    """
    bucket_path = str(s3_datapath).split('//')[1]
    parts = bucket_path.split('/')
    bucket = parts[0].strip('/')
    prefix = '/'.join(parts[1:])
    return bucket, prefix


def elem2rec_detailed(ar, elem, with_navinfo=True, **rec):
    """Adds additional information for this record, used only by detail
        views.

        The "navigation information" is a set of pointers to the next,
        previous, first and last record relative to this record in
        this report.  (This information can be relatively expensive
        for records that are towards the end of the queryset.  See
        `/blog/2010/0716`, `/blog/2010/0721`, `/blog/2010/1116`,
        `/blog/2010/1207`.)

        recno 0 means "the requested element exists but is not
        contained in the requested queryset".  This can happen after
        changing the quick filter (search_change) of a detail view.

        """
    rh = ar.ah
    rec = ar.elem2rec1(rh, elem, None, **rec)
    if ar.actor.hide_top_toolbar or ar.bound_action.action.hide_top_toolbar:
        rec.update(title=ar.get_detail_title(elem))
    else:
        rec.update(title=ar.get_breadcrumbs(elem))
    rec.update(id=elem.pk)
    if ar.actor.editable:
        rec.update(disable_delete=rh.actor.disable_delete(elem, ar))
    if rh.actor.show_detail_navigator and with_navinfo:
        rec.update(navinfo=rh.actor.get_navinfo(ar, elem))
    if ar.actor.parameters:
        rec.update(param_values=ar.actor.params_layout.params_store.pv2dict
            (ar, ar.param_values))
    return rec


@classmethod
def _camel_case(cls, text, first_upper=False):
    """
        Transform text to camelCase or CamelCase

        :param text:
        :param first_upper: first symbol must be upper?
        :return:
        """
    result = ''
    need_upper = False
    for pos, symbol in enumerate(text):
        if symbol == '_' and pos > 0:
            need_upper = True
        else:
            if need_upper:
                result += symbol.upper()
            else:
                result += symbol.lower()
            need_upper = False
    if first_upper:
        result = result[0].upper() + result[1:]
    return result


@classmethod
def encode_conjure_union_type(cls, obj):
    """Encodes a conjure union into json"""
    encoded = {}
    encoded['type'] = obj.type
    for attr, field_definition in obj._options().items():
        if field_definition.identifier == obj.type:
            attribute = attr
            break
    else:
        raise ValueError('could not find attribute for union ' +
            'member {0} of type {1}'.format(obj.type, obj.__class__))
    defined_field_definition = obj._options()[attribute]
    encoded[defined_field_definition.identifier] = cls.do_encode(getattr(
        obj, attribute))
    return encoded


def convert_windows_newlines(file_name):
    """
    Helper function for converting windows newlines in a file as a preprocessing step in case users make samplesheet
    in excel.

    Args:
    file_name (str): name of file to convert to unix newlines.

    """
    with open(file_name) as input:
        file_text = input.read()
    file_text = file_text.replace('\r', '\n')
    with open(file_name, 'w') as output:
        output.write(file_text)


def bbox_from_xywh(xywh):
    """Convert a bounding box from a numeric dict to a numeric list representation."""
    return xywh['x'], xywh['y'], xywh['x'] + xywh['w'], xywh['y'] + xywh['h']


def clean_string_columns(frame):
    """Removes excess whitespace from column names.
    (I always have to look this up otherwise)
    """
    return frame.columns.str.strip()


def duplicates(base, items):
    """Get an iterator of items similar but not equal to the base.

    @param base: base item to perform comparison against
    @param items: list of items to compare to the base
    @return: generator of items sorted by similarity to the base

    """
    for item in items:
        if item.similarity(base) and not item.equality(base):
            yield item


@classmethod
def var(cls, var_name, view=None, name=None, dtype=None, **kwargs) ->'url':
    """Implements having url-arguments. dtype is the casting argument.
        the default cast-type is str as Django."""
    route = f'{dtype}:{var_name}' if dtype else str(var_name)
    return cls(f'<{route}>', view, name, **kwargs)


def json_to_yaml(content):
    """
    TODO: convert json to yaml
    """
    return content


def _check_type(type_, value):
    """Return true if *value* is an instance of the specified type
    or if *value* is the specified type.
    """
    return value is type_ or isinstance(value, type_)


def raise_unexpected(code):
    """Called from with in an except block.

    Re-raises the exception if we don't know how to handle it.

    """
    if code != 401:
        raise


def uncomment():
    """Convert selected comment to text

    """
    pass


def __call__(input_stream, env):
    """Create a request object to handle the given inputs

        A request is created and configured with a publication object.
        """


def is_adb_server_opend():
    """判断ADB Server是否开启
    """
    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.bind(('localhost', 5037))
        sock.close()
        return False
    except:
        return True


def expand_indent(line):
    """Return the amount of indentation.

    Tabs are expanded to the next multiple of 8.

    >>> expand_indent('    ')
    4
    >>> expand_indent('\\t')
    8
    >>> expand_indent('       \\t')
    8
    >>> expand_indent('        \\t')
    16
    """
    if '\t' not in line:
        return len(line) - len(line.lstrip())
    result = 0
    for char in line:
        if char == '\t':
            result = result // 8 * 8 + 8
        elif char == ' ':
            result += 1
        else:
            break
    return result


def chartDistribution(distribution, outputfile=None):
    """
    Convenience function for displaying a matplotlib chart of an isotopic distribution
    generated by isotopicDistribution().
    """
    import matplotlib.pyplot as pyt
    from numpy import arange
    while distribution[-1] < 0.001:
        distribution = distribution[:-1]
    pyt.bar(list(range(0, len(distribution) + 1)), [0] + distribution,
        width=0.3, align='center')
    pyt.xticks(arange(1, len(distribution)))
    pyt.yticks(arange(0, 110, 10))
    pyt.ylim((0, 110))
    pyt.show()
    if outputfile:
        pyt.savefig(outputfile)


def format_card(card_num):
    """
    Formats card numbers to remove any spaces, unnecessary characters, etc

    Input: Card number, integer or string
    Output: Correctly formatted card number, string
    """
    import re
    card_num = str(card_num)
    return re.sub('\\D', '', card_num)


def multires_external_pack():
    """Pack displacements from an external file

    """
    pass


def put_integration(restApiId=None, resourceId=None, httpMethod=None, type=
    None, integrationHttpMethod=None, uri=None, credentials=None,
    requestParameters=None, requestTemplates=None, passthroughBehavior=None,
    cacheNamespace=None, cacheKeyParameters=None, contentHandling=None):
    """
    Represents a put integration.
    See also: AWS API Documentation

    :example: response = client.put_integration(
        restApiId='string',
        resourceId='string',
        httpMethod='string',
        type='HTTP'|'AWS'|'MOCK'|'HTTP_PROXY'|'AWS_PROXY',
        integrationHttpMethod='string',
        uri='string',
        credentials='string',
        requestParameters={
            'string': 'string'
        },
        requestTemplates={
            'string': 'string'
        },
        passthroughBehavior='string',
        cacheNamespace='string',
        cacheKeyParameters=[
            'string',
        ],
        contentHandling='CONVERT_TO_BINARY'|'CONVERT_TO_TEXT'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            Specifies a put integration request's API identifier.

    :type resourceId: string
    :param resourceId: [REQUIRED]
            Specifies a put integration request's resource ID.

    :type httpMethod: string
    :param httpMethod: [REQUIRED]
            Specifies a put integration request's HTTP method.

    :type type: string
    :param type: [REQUIRED]
            Specifies a put integration input's type.

    :type integrationHttpMethod: string
    :param integrationHttpMethod: Specifies a put integration HTTP method. When the integration type is HTTP or AWS, this field is required.

    :type uri: string
    :param uri: Specifies a put integration input's Uniform Resource Identifier (URI). When the integration type is HTTP or AWS, this field is required. For integration with Lambda as an AWS service proxy, this value is of the 'arn:aws:apigateway:region:lambda:path/2015-03-31/functions/functionArn/invocations' format.

    :type credentials: string
    :param credentials: Specifies whether credentials are required for a put integration.

    :type requestParameters: dict
    :param requestParameters: A key-value map specifying request parameters that are passed from the method request to the back end. The key is an integration request parameter name and the associated value is a method request parameter value or static value that must be enclosed within single quotes and pre-encoded as required by the back end. The method request parameter value must match the pattern of method.request.{location}.{name} , where location is querystring , path , or header and name must be a valid and unique method request parameter name.
            (string) --
            (string) --

    :type requestTemplates: dict
    :param requestTemplates: Represents a map of Velocity templates that are applied on the request payload based on the value of the Content-Type header sent by the client. The content type value is the key in this map, and the template (as a String) is the value.
            (string) --
            (string) --

    :type passthroughBehavior: string
    :param passthroughBehavior: Specifies the pass-through behavior for incoming requests based on the Content-Type header in the request, and the available mapping templates specified as the requestTemplates property on the Integration resource. There are three valid values: WHEN_NO_MATCH , WHEN_NO_TEMPLATES , and NEVER .
            WHEN_NO_MATCH passes the request body for unmapped content types through to the integration back end without transformation.
            NEVER rejects unmapped content types with an HTTP 415 'Unsupported Media Type' response.
            WHEN_NO_TEMPLATES allows pass-through when the integration has NO content types mapped to templates. However if there is at least one content type defined, unmapped content types will be rejected with the same 415 response.

    :type cacheNamespace: string
    :param cacheNamespace: Specifies a put integration input's cache namespace.

    :type cacheKeyParameters: list
    :param cacheKeyParameters: Specifies a put integration input's cache key parameters.
            (string) --

    :type contentHandling: string
    :param contentHandling: Specifies how to handle request payload content type conversions. Supported values are CONVERT_TO_BINARY and CONVERT_TO_TEXT , with the following behaviors:
            CONVERT_TO_BINARY : Converts a request payload from a Base64-encoded string to the corresponding binary blob.
            CONVERT_TO_TEXT : Converts a request payload from a binary blob to a Base64-encoded string.
            If this property is not defined, the request payload will be passed through from the method request to integration request without modification, provided that the passthroughBehaviors is configured to support payload pass-through.

    :rtype: dict
    :return: {
        'type': 'HTTP'|'AWS'|'MOCK'|'HTTP_PROXY'|'AWS_PROXY',
        'httpMethod': 'string',
        'uri': 'string',
        'credentials': 'string',
        'requestParameters': {
            'string': 'string'
        },
        'requestTemplates': {
            'string': 'string'
        },
        'passthroughBehavior': 'string',
        'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT',
        'cacheNamespace': 'string',
        'cacheKeyParameters': [
            'string',
        ],
        'integrationResponses': {
            'string': {
                'statusCode': 'string',
                'selectionPattern': 'string',
                'responseParameters': {
                    'string': 'string'
                },
                'responseTemplates': {
                    'string': 'string'
                },
                'contentHandling': 'CONVERT_TO_BINARY'|'CONVERT_TO_TEXT'
            }
        }
    }

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

    """
    pass


def any(name, alternates):
    """Return a named group pattern matching list of alternates."""
    return '(?P<%s>' % name + '|'.join(alternates) + ')'


def _get_best_indexes(logits, n_best_size):
    """Get the n-best logits from a list."""
    index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse
        =True)
    best_indexes = []
    for i in range(len(index_and_score)):
        if i >= n_best_size:
            break
        best_indexes.append(index_and_score[i][0])
    return best_indexes


def brush_copy():
    """Copy current Grease Pencil drawing brush

    """
    pass


def dupli_offset_from_cursor():
    """Set offset used for DupliGroup based on cursor position

    """
    pass


def measure_relative(S):
    """Calculate the "measure-relative" score as defined in the paper

    Args:
        S (List[List[int]]): accuracy counts as defined in the paper

    Returns:
        score (float): measure-relative score
    """
    return (S[0][1] - S[1][0]) / (S[0][0] + S[1][1] + S[0][1] + S[1][0])


def chunks(items, size):
    """Break up items, an iterable, into chunks of length size."""
    for i in range(0, len(items), size):
        yield items[i:i + size]


def updateOrder(order):
    """Revise the order of keys, replacing the current ordering.

        order is a list or a tuple containing the set of existing keys in
        the new order. `order` must contain ``len(keys())`` items and cannot
        contain duplicate keys.

        Raises ``TypeError`` if order is not a tuple or a list.

        Raises ``ValueError`` if order contains an invalid set of keys.
        """


def initialize_policy_engine(engine):
    """Initialize the policy engine using the API."""
    engine.persistent_load_policies()
    engine.create_default_policies()
    engine.persistent_load_rules()


def __ne__(A, other):
    """Returns true if both objects are not equal"""
    return not A == other


@classmethod
def get_url_name(cls):
    """ This name will be used by generic relationships to membership model for URL creation """
    return '{}-{}'.format(cls._meta.app_label, cls.__name__.lower())


def _pick_external_repo_priority(session, tag):
    """pick priority after current ones, leaving space for later insertions"""
    repolist = session.getTagExternalRepos(tag_info=tag)
    if not repolist:
        priority = 5
    else:
        priority = (repolist[-1]['priority'] + 7) // 5 * 5
    return priority


def put_configuration_recorder(ConfigurationRecorder=None):
    """
    Creates a new configuration recorder to record the selected resource configurations.
    You can use this action to change the role roleARN and/or the recordingGroup of an existing recorder. To change the role, call the action on the existing configuration recorder and specify a role.
    See also: AWS API Documentation

    :example: response = client.put_configuration_recorder(
        ConfigurationRecorder={
            'name': 'string',
            'roleARN': 'string',
            'recordingGroup': {
                'allSupported': True|False,
                'includeGlobalResourceTypes': True|False,
                'resourceTypes': [
                    'AWS::EC2::CustomerGateway'|'AWS::EC2::EIP'|'AWS::EC2::Host'|'AWS::EC2::Instance'|'AWS::EC2::InternetGateway'|'AWS::EC2::NetworkAcl'|'AWS::EC2::NetworkInterface'|'AWS::EC2::RouteTable'|'AWS::EC2::SecurityGroup'|'AWS::EC2::Subnet'|'AWS::CloudTrail::Trail'|'AWS::EC2::Volume'|'AWS::EC2::VPC'|'AWS::EC2::VPNConnection'|'AWS::EC2::VPNGateway'|'AWS::IAM::Group'|'AWS::IAM::Policy'|'AWS::IAM::Role'|'AWS::IAM::User'|'AWS::ACM::Certificate'|'AWS::RDS::DBInstance'|'AWS::RDS::DBSubnetGroup'|'AWS::RDS::DBSecurityGroup'|'AWS::RDS::DBSnapshot'|'AWS::RDS::EventSubscription'|'AWS::ElasticLoadBalancingV2::LoadBalancer'|'AWS::S3::Bucket'|'AWS::SSM::ManagedInstanceInventory'|'AWS::Redshift::Cluster'|'AWS::Redshift::ClusterSnapshot'|'AWS::Redshift::ClusterParameterGroup'|'AWS::Redshift::ClusterSecurityGroup'|'AWS::Redshift::ClusterSubnetGroup'|'AWS::Redshift::EventSubscription',
                ]
            }
        }
    )

    :type ConfigurationRecorder: dict
    :param ConfigurationRecorder: [REQUIRED]
            The configuration recorder object that records each configuration change made to the resources.
            name (string) --The name of the recorder. By default, AWS Config automatically assigns the name 'default' when creating the configuration recorder. You cannot change the assigned name.
            roleARN (string) --Amazon Resource Name (ARN) of the IAM role used to describe the AWS resources associated with the account.
            recordingGroup (dict) --Specifies the types of AWS resource for which AWS Config records configuration changes.
            allSupported (boolean) --Specifies whether AWS Config records configuration changes for every supported type of regional resource.
            If you set this option to true , when AWS Config adds support for a new type of regional resource, it automatically starts recording resources of that type.
            If you set this option to true , you cannot enumerate a list of resourceTypes .
            includeGlobalResourceTypes (boolean) --Specifies whether AWS Config includes all supported types of global resources (for example, IAM resources) with the resources that it records.
            Before you can set this option to true , you must set the allSupported option to true .
            If you set this option to true , when AWS Config adds support for a new type of global resource, it automatically starts recording resources of that type.
            The configuration details for any global resource are the same in all regions. To prevent duplicate configuration items, you should consider customizing AWS Config in only one region to record global resources.
            resourceTypes (list) --A comma-separated list that specifies the types of AWS resources for which AWS Config records configuration changes (for example, AWS::EC2::Instance or AWS::CloudTrail::Trail ).
            Before you can set this option to true , you must set the allSupported option to false .
            If you set this option to true , when AWS Config adds support for a new type of resource, it will not record resources of that type unless you manually add that type to your recording group.
            For a list of valid resourceTypes values, see the resourceType Value column in Supported AWS Resource Types .
            (string) --

    """
    pass


def check_word(p, tok=None, dep=None, up_tok=None, up_dep=None, precede=None):
    """
    Returns an indicator and a marker
    If parameters match any word in the sentence:
        returns 1, markers for each occurance
    Else:
        returns 0, []
    """
    toks = []
    for ind, x in enumerate(p):
        if tok != None and x['tok'].lower() not in tok:
            continue
        if dep != None and x['dep'] not in dep:
            continue
        if up_tok != None and ('up' not in x or p[x['up']]['tok'].lower()
             not in up_tok):
            continue
        if up_dep != None and p[x['up']]['dep'] not in up_dep:
            continue
        if precede != None and (len(p) <= ind + 1 or p[ind + 1]['tok'] not in
            precede):
            continue
        if up_tok != None:
            toks += [[(x['tok'], ind), (p[x['up']]['tok'].lower(), x['up'])]]
        else:
            toks += [[(x['tok'], ind)]]
    if toks != []:
        return 1, toks
    else:
        return 0, []


def write_html_footer(file):
    """Write HTML footer."""
    message = """

        Copyright ©2020 Alexander Willner
        """
    file.write(message)


def value(entry):
    """
    check if the string entry can

    Parameters
    ----------
    entry: str
        an entry of type str

    Returns
    -------
    bool
        True if the input can become an integer, False otherwise

    Notes
    -----
    returns 'type' for the entry 'type', although type is a code object

    """
    try:
        val = eval(entry)
        if isinstance(val, type):
            return entry
        else:
            return val
    except:
        return entry


def p_table_display(p):
    """ table_display : "{" maybe_nline tablemaker maybe_nline "}"
                      | "{" maybe_nline "}" """
    if len(p) == 4:
        p[0] = ['TABLE']
    else:
        p[0] = ['TABLE'] + p[3]


def get_list_sub_key_string(index, key_string):
    """
    Helper function to add the given index to preceding keys.
    Handles the case, if key is the first key and key_string is None.

    :param index: The index to add to the key_string
    :param key_string: The string containing the preceding keys
    :return: A string concatenation of key_string and index
    """
    if key_string is None:
        sub_key_string = '[{}]'.format(index)
    else:
        sub_key_string = '{}[{}]'.format(key_string, index)
    return sub_key_string


def change_tags_for_resource(ResourceType=None, ResourceId=None, AddTags=
    None, RemoveTagKeys=None):
    """
    Adds, edits, or deletes tags for a health check or a hosted zone.
    For information about using tags for cost allocation, see Using Cost Allocation Tags in the AWS Billing and Cost Management User Guide .
    See also: AWS API Documentation

    :example: response = client.change_tags_for_resource(
        ResourceType='healthcheck'|'hostedzone',
        ResourceId='string',
        AddTags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        RemoveTagKeys=[
            'string',
        ]
    )

    :type ResourceType: string
    :param ResourceType: [REQUIRED]
            The type of the resource.
            The resource type for health checks is healthcheck .
            The resource type for hosted zones is hostedzone .

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            The ID of the resource for which you want to add, change, or delete tags.

    :type AddTags: list
    :param AddTags: A complex type that contains a list of the tags that you want to add to the specified health check or hosted zone and/or the tags that you want to edit Value for.
            You can add a maximum of 10 tags to a health check or a hosted zone.
            (dict) --A complex type that contains information about a tag that you want to add or edit for the specified health check or hosted zone.
            Key (string) --The value of Key depends on the operation that you want to perform:
            Add a tag to a health check or hosted zone : Key is the name that you want to give the new tag.
            Edit a tag : Key is the name of the tag that you want to change the Value for.
            Delete a key : Key is the name of the tag you want to remove.
            Give a name to a health check : Edit the default Name tag. In the Amazon Route 53 console, the list of your health checks includes a Name column that lets you see the name that you've given to each health check.
            Value (string) --The value of Value depends on the operation that you want to perform:
            Add a tag to a health check or hosted zone : Value is the value that you want to give the new tag.
            Edit a tag : Value is the new value that you want to assign the tag.

    :type RemoveTagKeys: list
    :param RemoveTagKeys: A complex type that contains a list of the tags that you want to delete from the specified health check or hosted zone. You can specify up to 10 keys.
            (string) --

    :rtype: dict
    :return: {}

    """
    pass


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


def getWriters():
    """
        Return the list file descriptors currently monitored for output events
        by the reactor.

        @return: the list of file descriptors monitored for output events.
        @rtype: C{list} of C{IWriteDescriptor}
        """


def fn_jaro(len1, len2, num_matches, half_transposes, typo_score, typo_scale):
    """Calculate the classic Jaro metric between two strings.

    The strings have lengths 'len1' and 'len2'. 'num_matches' and
    'half_transposes' are the output of the count_matches() and
    count_half_tranpositions() functions.

    'typo_score' is an optional argument, produced by the count_typos()
    function if you decide to check the strings for typos with a given
    typographical mapping. The typo score will be scaled by 'typo_scale'
    before being used."""
    if not len1:
        if not len2:
            return 1.0
        return 0.0
    if not num_matches:
        return 0.0
    similar = typo_score / typo_scale + num_matches
    weight = similar / len1 + similar / len2 + (num_matches -
        half_transposes // 2) / num_matches
    return weight / 3


@classmethod
def is_valid_handle(cls, handle):
    """Validates unit handle

        :param handle: unit handle to validate
        :type handle: int
        :return: True if handle is valid, False otherwise
        :rtype: boolean
        """
    if handle > cls.UNIT_NOT_FOUND:
        return True
    return False


@classmethod
def is_datasource_for(cls, **kwargs):
    """
        Determines if header corresponds to an NOAA indices timeseries.
        """
    if kwargs.get('source', ''):
        return kwargs.get('source', '').lower().startswith(cls._source)


@classmethod
def from_queue_key(cls, queue_key, connection=None, job_class=None):
    """Returns a Queue instance, based on the naming conventions for naming
        the internal Redis keys.  Can be used to reverse-lookup Queues by their
        Redis keys.
        """
    prefix = cls.redis_queue_namespace_prefix
    if not queue_key.startswith(prefix):
        raise ValueError('Not a valid RQ queue key: {0}'.format(queue_key))
    name = queue_key[len(prefix):]
    return cls(name, connection=connection, job_class=job_class)


def set_pg_autocommit(cn, autocommit):
    """PostgreSQL autocommit setter for core."""
    cn.autocommit = autocommit


@classmethod
def delete_by_id(cls, object_id):
    """
        Deletes a document identified by the object id
        :param object_id:
        :return: true if the object was deleted
        """
    delete_result = cls.get_collection().delete_one({'_id': object_id})
    return delete_result.deleted_count


def psi_Ca_K_Cl_HMW84(T, P):
    """c-c'-a: calcium potassium chloride [HMW84]."""
    psi = -0.025
    valid = T == 298.15
    return psi, valid


def get_bool_value(key):
    """
    This method is used to get boolean value from json set value.
    :param key:
    :return:
    """
    bool_val = True
    if not key or key == 'False':
        bool_val = False
    return bool_val


def calculate_hounsfield_unit_parameterless(mu):
    """
    Given linear attenuation coefficients the function calculates the corresponding Hounsfield units.
    :param mu: Attenuation coefficient to determine corresponding Hounsfield unit.
    :return: Hounsfield unit corresponding to mu
    """
    HU = mu * 65536 - 1024
    return HU


def passes_max_percent_editing(ref_cnt, alt_cnt, max_percent_coverage):
    """ This function is intended to allow us to filter out SNVs, under the assumption that SNVs mistaken as editing
    will have an extremely high percentage of editing bases i.e. around 100%.

    :param ref_cnt: The number of reference bases overlapping a site.
    :param alt_cnt: The number of alt or edited bases at a site.
    :param max_percent_coverage: A float between 0 and 1:
    :return:
    """
    editing_ratio = alt_cnt / float(ref_cnt + alt_cnt)
    if editing_ratio <= max_percent_coverage:
        return True
    return False


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

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

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


def line(coefficients, x):
    """
    For a given value x calculate y = A*x + B.

    Parameters
    ----------
    coefficients : tuple
        A tuple with the line coefficients (A, B).
    x : float
        An argument of a linear equation.

    Returns
    -------
    y : float
        A calculated value of the linear equation.
    """
    return coefficients[0] * x + coefficients[1]


def _add_doc(func, doc):
    """Add documentation to a function."""
    func.__doc__ = doc


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

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

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


@staticmethod
def _directive_call_func(directive_body):
    """Directive for :py:meth:`dispatch_call`"""
    func_obj, func_args, func_kwargs = directive_body
    return func_obj(*func_args, **func_kwargs)


@classmethod
def adBlockManager(cls):
    """
        Class method to get a reference to the AdBlock manager.

        @return reference to the AdBlock manager (AdBlockManager)
        """
    if cls._adblockManager is None:
        from .AdBlock.AdBlockManager import AdBlockManager
        cls._adblockManager = AdBlockManager()
    return cls._adblockManager


def str2bool(testcase):
    """Given a string containing the typically valid boolean answers that can be found in yaml, json or other encoded/marshaled data provide a boolean answer.

    :param testcase: Value to be evaluated
    :type testcase: None, Int, Bool or Str
    :return: default is False unless truthyness can be determined
    :rtype: bool
    """
    if testcase is None:
        return False
    if isinstance(testcase, bool):
        return testcase
    if isinstance(testcase, int):
        return testcase == 0
    return testcase.lower() in ('yes', 'true', 't', 'y', '0')


def to_unicode(text, encoding=None, errors='strict'):
    """Return the unicode representation of a bytes object ``text``. If
    ``text`` is already an unicode object, return it as-is."""
    if isinstance(text, str):
        return text
    if not isinstance(text, (bytes, str)):
        raise TypeError(
            'to_unicode must receive a bytes or str object, got %s' % type(
            text).__name__)
    if encoding is None:
        encoding = 'utf-8'
    return text.decode(encoding, errors)


def safe_module_name(module):
    """ Munge the name of a TemplateHelper module to avoid collisions
    with other Python modules.  E.g., if someone has a helper named
    'ldap.py', it should not be added to ``sys.modules`` as ``ldap``,
    but rather as something more obscure. """
    return '__TemplateHelper_%s' % module


@staticmethod
def icon():
    """
        Returns the icon of the tool
        :return: QIcon or None
        """
    return None


def generate_archive_settings(packages):
    """
    Generate an archive settings given a list of record packages

    Parameters
    ----------
    packages : list of record packages

    Yields
    ------
    str
        One line from the archiver settings file
    """
    for package in packages:
        archive_settings = package.archive_settings
        if archive_settings:
            for record in package.records:
                fields = sorted(set(archive_settings['fields'] + package.
                    archive_fields))
                for field in fields:
                    period = archive_settings['seconds']
                    update_rate = package.config['update']['seconds']
                    if period < update_rate:
                        period = update_rate
                    method = archive_settings['method']
                    yield f'{record.pvname}.{field}\t{period}\t{method}'


def addSub(sub):
    """Add a new sub-registry to the node.

        .. caution:: This method should *not* be used manually. It is
            automatically called by `setNext`. To add a new registry to the
            tree, use ``sub.setNext(self, self.base)`` instead!
        """


def camelcase_to_underscore_joined(camelcase_str):
    """Convert camelCase string to underscore_joined string

    :param camelcase_str: The camelCase string
    :returns: the equivalent underscore_joined string
    """
    if not camelcase_str:
        raise ValueError('"camelcase_str" cannot be empty')
    r = camelcase_str[0].lower()
    for i, letter in enumerate(camelcase_str[1:], 1):
        if letter.isupper():
            try:
                if camelcase_str[i - 1].islower() or camelcase_str[i + 1
                    ].islower():
                    r += '_'
            except IndexError:
                pass
        r += letter.lower()
    return r


@staticmethod
def get_subtype(object_dictionary):
    """
        Given the hash representation of a subtype of this class,
        use the info in the hash to return the class of the subtype.
        """
    type = object_dictionary['operation']
    if type == 'IMPORT_TF_STATE':
        return 'CreateImportTfStateJobOperationDetails'
    if type == 'APPLY':
        return 'CreateApplyJobOperationDetails'
    if type == 'PLAN':
        return 'CreatePlanJobOperationDetails'
    if type == 'DESTROY':
        return 'CreateDestroyJobOperationDetails'
    else:
        return 'CreateJobOperationDetails'


def _and(queries):
    """
    Returns a query item matching the "and" of all query items.

    Args:
        queries (List[str]): A list of query terms to and.

    Returns:
        The query string.

    """
    if len(queries) == 1:
        return queries[0]
    return f"({' '.join(queries)})"


def GetAtomResidueId(atom):
    """Return (residue number, residue name, chain id) for a given atom"""
    info = atom.GetPDBResidueInfo()
    res_id = info.GetResidueNumber(), info.GetResidueName().strip(
        ), info.GetChainId()
    return res_id


def get_urn(url):
    """
    convert https://blog.scrapinghub.com/page/6/ into blog.scrapinghub.com/page/6/
    :param url:
    :return:
    """
    if '://' in url:
        return url.split('://')[1]
    return url


def freestyle_linestyle_new():
    """Create a new line style, reusable by multiple line sets

    """
    pass


def bytes_to_int(bts: bytes, signed: bool=False) ->int:
    """Convert a string of bytes to an integer number.

    Whether the final int should be signed or not can't be determined, so it
    must be specified.

    Note: reversibility is not assured! I.E.: if the bytes string begins with
    null values, those will be lost and converting the resulting integer into
    bytes will yield a different value.
    """
    if not isinstance(bts, bytes):
        raise TypeError('bts must be bytes')
    return int.from_bytes(bts, 'big', signed=signed)


@staticmethod
def __is_trailing_surrogate(c):
    """Returns true if 'c' is a Unicode code point for a trailing
        surrogate."""
    return c >= 56320 and c <= 57343


@staticmethod
def encode(value):
    """Encode a DER octet string"""
    return value


def capitalize(string):
    """Capitalize a sentence.

    Parameters
    ----------
    string : `str`
        String to capitalize.

    Returns
    -------
    `str`
        Capitalized string.

    Examples
    --------
    >>> capitalize('worD WORD WoRd')
    'Word word word'
    """
    if not string:
        return string
    if len(string) == 1:
        return string.upper()
    return string[0].upper() + string[1:].lower()


def get_charset(response, default='utf-8'):
    """Return encoding."""
    try:
        return response.info().get_param('charset', default)
    except AttributeError:
        content_type = response.headers['content-type']
        split_on = 'charset='
        if split_on in content_type:
            return content_type.split(split_on)[-1]
        else:
            return default


def copy():
    """Obtain a copy of this manifest instance.

        Returns an object conforming to the ``imanifestrevisionwritable``
        interface. The instance will be associated with the same
        ``imanifestlog`` collection as this instance.
        """


@classmethod
def _register_listener(cls, unbound_method, partial_receiver, mesg_filter):
    """ A helper class for creating listener decorators. """
    listeners = getattr(unbound_method, cls.LISTENERS_ATTR, None)
    if listeners is None:
        listeners = []
        setattr(unbound_method, cls.LISTENERS_ATTR, listeners)
    listeners.append((partial_receiver, mesg_filter))


def can_paginate(operation_name=None):
    """
    Check if an operation can be paginated.

    :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').

    """
    pass


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

        :param PaperContentRemoveMemberDetails val:
        :rtype: EventDetails
        """
    return cls('paper_content_remove_member_details', val)


def get_theme_path(theme):
    """Return the theme's path, which equals the theme's name."""
    return theme


@staticmethod
def is_apolar(a):
    """
        returns true if a given atom is a apolar

        :param a: a `ccdc.molecule.Atom` instance
        :return: bool, true if the atom classification is "apolar"
        """
    if (a.is_donor or a.is_acceptor or a.formal_charge != 0 or a.
        atomic_symbol == 'Xe'):
        return False
    else:
        return True


def read_sample(fobj, sample):
    """Read `sample` bytes from `fobj` and return the cursor to where it was."""
    cursor = fobj.tell()
    data = fobj.read(sample)
    fobj.seek(cursor)
    return data


def get_context_loop_positions(context):
    """
    Return the paginated current position within a loop,
    and the non-paginated position.
    """
    try:
        loop_counter = context['forloop']['counter']
    except KeyError:
        return 0, 0
    try:
        page = context['page_obj']
    except KeyError:
        return loop_counter, loop_counter
    total_loop_counter = (page.number - 1
        ) * page.paginator.per_page + loop_counter
    return total_loop_counter, loop_counter


def hide_inverse(model):
    """
    This is a convenience function intended to disable automatic generation
    of the inverse in compound models by disabling one of the constituent
    model's inverse. This is to handle cases where user provided inverse
    functions are not compatible within an expression.

    Example:
        compound_model.inverse = hide_inverse(m1) + m2 + m3

    This will insure that the defined inverse itself won't attempt to
    build its own inverse, which would otherwise fail in this example
    (e.g., m = m1 + m2 + m3 happens to raises an exception for this
    reason.)

    Note that this permanently disables it. To prevent that either copy
    the model or restore the inverse later.
    """
    del model.inverse
    return model


def parse_bool(text):
    """Parse a string to a boolean, ignoring case. "true"/"1" is True,
    "false"/"0" is False. Anything else throws an exception."""
    if text.lower() in ('true', '1'):
        return True
    elif text.lower() in ('false', '0'):
        return False
    raise Exception('Invalid boolean: %s' % text)


@classmethod
def close(cls):
    """ closes all pool connections

        """
    cls.pool.closeall()


def lowerword(s):
    """
    >>> lowerword('Hello')
    'hello'
    """
    return s[0].lower() + s[1:]


@staticmethod
def _get_hydrogen(df, invert):
    """Return only hydrogen atom entries from a DataFrame"""
    if invert:
        return df[df['element_symbol'] != 'H']
    else:
        return df[df['element_symbol'] == 'H']


def combine_filename_name(filename: str, name: str):
    """
    Combine the filename with the contract name

    :param filename:
    :param name:
    :return:
    """
    return filename + ':' + name


def escape_html(text):
    """Replace <, >, &, " with their HTML encoded representation. Intended to
    prevent HTML errors in rendered displaCy markup.

    text (unicode): The original text.
    RETURNS (unicode): Equivalent text to be safely used within HTML.
    """
    text = text.replace('&', '&')
    text = text.replace('<', '<')
    text = text.replace('>', '>')
    text = text.replace('"', '"')
    return text


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

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


def settemplocation(loc=None):
    """
     Set a custom temporary file location. This is used by some flatteners to store large data sets which are faster
     to write to disk than send over XML-RPC.

     There is no requirement for the unflattener at the other end to have the same temp location as a full path to the
     temp file should be stored in the flattened form.

     loc new temp file location to use, or None to use default of system temp
    """
    global _TEMP_LOCATION, _TEMP_LOCATION_SET
    _TEMP_LOCATION = loc
    _TEMP_LOCATION_SET = True


def stop_gradient(data=None, name=None, attr=None, out=None, **kwargs):
    """Stops gradient computation.

    Stops the accumulated gradient of the inputs from flowing through this operator
    in the backward direction. In other words, this operator prevents the contribution
    of its inputs to be taken into account for computing gradients.

    Example::

      v1 = [1, 2]
      v2 = [0, 1]
      a = Variable('a')
      b = Variable('b')
      b_stop_grad = stop_gradient(3 * b)
      loss = MakeLoss(b_stop_grad + a)

      executor = loss.simple_bind(ctx=cpu(), a=(1,2), b=(1,2))
      executor.forward(is_train=True, a=v1, b=v2)
      executor.outputs
      [ 1.  5.]

      executor.backward()
      executor.grad_arrays
      [ 0.  0.]
      [ 1.  1.]

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

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

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

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


@staticmethod
def datetime_to_datetime_str(date, _format='%Y-%m-%d %H:%M:%S'):
    """
        Datetime to string, datetime's default timezone is local server timezone
        @:param date datetime
        @:param _format string, default:%Y-%m-%d %H:%M:%S
        """
    return date.strftime(_format)


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

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

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


def create_vpn_connection_route(VpnConnectionId=None, DestinationCidrBlock=None
    ):
    """
    Creates a static route associated with a VPN connection between an existing virtual private gateway and a VPN customer gateway. The static route allows traffic to be routed from the virtual private gateway to the VPN customer gateway.
    For more information about VPN connections, see Adding a Hardware Virtual Private Gateway to Your VPC in the Amazon Virtual Private Cloud User Guide .
    See also: AWS API Documentation

    :example: response = client.create_vpn_connection_route(
        VpnConnectionId='string',
        DestinationCidrBlock='string'
    )

    :type VpnConnectionId: string
    :param VpnConnectionId: [REQUIRED]
            The ID of the VPN connection.

    :type DestinationCidrBlock: string
    :param DestinationCidrBlock: [REQUIRED]
            The CIDR block associated with the local subnet of the customer network.

    """
    pass


@classmethod
def __find(cls, query, limit=None, skip=None, sort=None, db=None, **kwargs
    ) ->'cursor obj':
    """Find and return cursor objects.

        returns:
            cursor objects (list): list of Pymongo cursor instances if found else None
        """
    __db = db if db else cls.__db
    if limit and skip and sort:
        results = __db[cls.__collection__].find(query, **kwargs).sort(sort
            ).skip(skip).limit(limit)
    elif limit and skip and not sort:
        results = __db[cls.__collection__].find(query, **kwargs).skip(skip
            ).limit(limit)
    elif limit and not skip and sort:
        results = __db[cls.__collection__].find(query, **kwargs).sort(sort
            ).limit(limit)
    elif not limit and skip and sort:
        results = __db[cls.__collection__].find(query, **kwargs).sort(sort
            ).skip(skip)
    elif limit and not skip and not sort:
        results = __db[cls.__collection__].find(query, **kwargs).limit(limit)
    elif not limit and skip and not sort:
        results = __db[cls.__collection__].find(query, **kwargs).skip(skip)
    elif not limit and not skip and sort:
        results = __db[cls.__collection__].find(query, **kwargs).sort(sort)
    else:
        results = __db[cls.__collection__].find(query, **kwargs)
    return results


@classmethod
def simple_user_exists(cls, *args, **kwargs):
    """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        TODO: consider how to ensure case-insensitive email matching
        """
    kwargs = cls.username_field(kwargs)
    return cls.user_model().objects.filter(*args, **kwargs).exists()


def clear_render_border():
    """Clear the boundaries of the border render and disable border render

    """
    pass