def registerRefID(refid, obj):
    """Register the relationship between 'refid' (a number taken from
        the cumulative count of OPEN tokens sent over our connection: 0 is
        the object described by the very first OPEN sent over the wire) and
        the object. If the object is sent a second time, a Reference may be
        used in its place.

        Slicers usually delgate this function upwards to the RootSlicer, but
        it can be handled at any level to allow local scoping of references
        (they might only be valid within a single RPC invocation, for
        example).

        This method is *not* allowed to raise a Violation, as that will mess
        up the transmit logic. If it raises any other exception, the
        connection will be dropped."""


def add_nodes(g, nodes):
    """Add nodes to the graph in place."""
    nodes.apply(lambda n: g.add_node(n['name'], label=n['label'],
        node_class=n['node_class']), axis=1)


def redirect_url():
    """ Returns empty string or the url to be redirected, depending on
            the configuration of the feed folder.

            Returns an empty string if redirect is not enabled or if
            you have modify permissions
        """


@classmethod
def base_queryset(cls):
    """
        Returns a queryset of objects of this type to use as a base
        for calling get_or_create() on.

        You can use the `select_related` attribute on your class to
        specify a list of foreign key field names, which the method
        will attempt to select additional related-object data for
        when the query is executed.

        If your needs are more complex than this, you can override
        this method on your custom class.
        """
    queryset = cls.objects.all()
    if cls.select_related is not None:
        queryset = queryset.select_related(*cls.select_related)
    return queryset


def _setup_smoothing_sigmas(scale: int=1):
    """Setup the smoothing sigmas array for registration"""
    smoothing_sigmas = [0]
    if scale > 1:
        for idx in range(1, scale, 1):
            smoothing_sigmas.insert(0, 2 ** (idx - 1))
        print('No smoothing sigmas given, setting to {}'.format(
            smoothing_sigmas))
    return smoothing_sigmas


def _margeff_cov_params_count(model, cov_margins, params, exog, count_ind,
    method, J):
    """
    Returns the Jacobian for discrete regressors for use in margeff_cov_params.

    For discrete regressors the marginal effect is

    \\Delta F = F(XB) | d += 1 - F(XB) | d -= 1

    The row of the Jacobian for this variable is given by

    (f(XB)*X | d += 1 - f(XB)*X | d -= 1) / 2

    where F is the default prediction for the model.
    """
    for i in count_ind:
        exog0 = exog.copy()
        exog0[:, (i)] -= 1
        dfdb0 = model._derivative_predict(params, exog0, method)
        exog0[:, (i)] += 2
        dfdb1 = model._derivative_predict(params, exog0, method)
        dfdb = dfdb1 - dfdb0
        if dfdb.ndim >= 2:
            dfdb = dfdb.mean(0) / 2
        if J > 1:
            K = dfdb.shape[1] / (J - 1)
            cov_margins[i::K, :] = dfdb
        else:
            cov_margins[(i), :len(dfdb)] = dfdb
    return cov_margins


def dpad_right_unheading(controller):
    """
    Callback function that is triggered, when the direction right was released

    :param controller:              the controller that triggered the action
    :type controller:               steuer.Controller
    """
    print('DIRECTION:' + str(controller.number) + ':' + controller.name +
        ':DPAD Right unheading')


@classmethod
def remove_activity(cls, activity, **kwargs):
    """
        Removes an activity from the activity storage

        :param activity: the activity class or an activity id
        """
    activity_storage = cls.get_activity_storage()
    activity_storage.remove(activity)


def configure(conf):
    """
	Configuration methods to call for detecting msvc
	"""
    conf.autodetect(True)
    conf.find_msvc()
    conf.msvc_common_flags()
    conf.cc_load_tools()
    conf.cxx_load_tools()
    conf.cc_add_flags()
    conf.cxx_add_flags()
    conf.link_add_flags()
    conf.visual_studio_add_flags()


def get_domains(boundary_list):
    """
        returns for each boundary a chrom, start,end position
        corresponding to each TAD
        :param boundary_position: list of boundary chromosomal positions
        :return: list of (chrom, start, end, value) tuples.
        """
    prev_start = None
    prev_chrom = boundary_list[0][0]
    domain_list = []
    for chrom, start, value in boundary_list:
        if start is None:
            prev_start = start
            prev_chrom = chrom
            continue
        if prev_chrom != chrom:
            prev_chrom = chrom
            prev_start = None
            continue
        domain_list.append((chrom, prev_start, start, value))
        prev_start = start
        prev_chrom = chrom
    return domain_list


def javascript():
    """
        content to be included in javascript area of template
        """


def list(session, attributes='Name'):
    """
    Description: return list of all products installed on windows machine

    :param session: instance of Windows, which hold session to win machine
    :type session: winremote.Windows
    :param attributes: comma delimited name of attributes to be returned
    :type attributes: str
    :returns: list of installed products
    :rtype: list of str
    """
    return session._wmi.query('select %s from win32_product' % attributes)


def find_stab(state, xs, zs):
    """
    Find a stabilizer in the stabilizer group.

    Args:
        state:
        logical_circuit:
        delogical_circuit:

    Returns:

    """
    stabs = state.stabs
    destabs = state.destabs
    possible_antidestabs = set([])
    for q in xs:
        possible_antidestabs.update(destabs.col_z[q])
    for q in zs:
        possible_antidestabs.update(destabs.col_x[q])
    antidestabs = set([])
    for d in possible_antidestabs:
        if (len(xs & destabs.row_z[d]) + len(zs & destabs.row_x[d])) % 2 == 1:
            antidestabs.add(d)
    confirm_xs = set([])
    confirm_zs = set([])
    for d in antidestabs:
        confirm_xs ^= stabs.row_x[d]
        confirm_zs ^= stabs.row_z[d]
    found = confirm_xs == xs and confirm_zs == zs
    return found, antidestabs


def reset():
    """Reset UV projection

    """
    pass


@classmethod
def with_teardown(cls, *teardown_phases):
    """Create PhaseGroup creator function with predefined teardown phases."""
    return cls.with_context([], teardown_phases)


def Nu_vertical_helical_coil_Prabhanjan_Rennie_Raghavan(Pr, Gr):
    """Calculates Nusselt number for natural convection around a vertical
    helical coil inside a tank or other vessel according to the Prabhanjan,
    Rennie, and Raghavan [1]_ correlation.

    .. math::
        Nu_H = 0.0749\\text{Ra}_H^{0.3421}

    The range of Rayleigh numbers is as follows:

    .. math::
        9 \\times 10^{9} < \\text{Ra} < 4 \\times 10^{11}

    Parameters
    ----------
    Pr : float
        Prandtl number calculated with the film temperature -
        wall and temperature very far from the coil average, [-]
    Gr : float
        Grashof number calculated with the film temperature -
        wall and temperature very far from the coil average,
        and using the total height of the coil [-]

    Returns
    -------
    Nu : float
        Nusselt number using the total height of the coil
        and the film temperature, [-]

    Notes
    -----
    [1]_ also has several other equations using different characteristic
    lengths.

    Examples
    --------
    >>> Nu_vertical_helical_coil_Prabhanjan_Rennie_Raghavan(4.4, 1E11)
    720.6211067718227

    References
    ----------
    .. [1] Prabhanjan, Devanahalli G., Timothy J. Rennie, and G. S. Vijaya
       Raghavan. "Natural Convection Heat Transfer from Helical Coiled Tubes."
       International Journal of Thermal Sciences 43, no. 4 (April 1, 2004):
       359-65.
    """
    Ra = Pr * Gr
    return 0.0749 * Ra ** 0.3421


@classmethod
def get_tx(cls, txid):
    """Gets tx dict by txid.

        :param txid: The transaction id in question.
        :type txid: ``str``
        :raises ConnectionError: If all API services fail.
        :rtype: ``dict``
        """
    for api_call in cls.GET_TX_MAIN:
        try:
            return api_call(txid)
        except cls.IGNORED_ERRORS:
            pass
    raise ConnectionError('All APIs are unreachable.')


def find_node(prev: bool=False):
    """Search for named node and allow to select and activate it

    :param prev: Previous
    :type prev: bool
    """
    pass


def get_default_opts(cyclic=False):
    """Get the default advanced settings for DMRG.

    Returns
    -------
    default_sweep_sequence : str
        How to sweep. Will be repeated, e.g. "RRL" -> RRLRRLRRL..., default: R.
    bond_compress_method : {'svd', 'eig', ...}
        Method used to compress sites after update.
    bond_compress_cutoff_mode : {'sum2', 'abs', 'rel'}
        How to perform compression truncation.
    bond_expand_rand_strength : float
        In DMRG1, strength of randomness to expand bonds with. Needed to avoid
        singular matrices after expansion.
    local_eig_tol : float
        Relative tolerance to solve inner eigenproblem to, larger = quicker but
        more unstable, default: 1e-3. Note this can be much looser than the
        overall tolerance, the starting point for each local solve is the
        previous state, and the overall accuracy comes from multiple sweeps.
    local_eig_ncv : int
        Number of inner eigenproblem lanczos vectors. Smaller can mean quicker.
    local_eig_backend : {None, 'AUTO', 'SCIPY', 'SLEPC'}
        Which to backend to use for the inner eigenproblem. None or 'AUTO' to
        choose best. Generally ``'SLEPC'`` best if available for large
        problems, but it can't currently handle ``LinearOperator`` Neff as well
        as ``'lobpcg'``.
    local_eig_maxiter : int
        Maximum number of inner eigenproblem iterations.
    local_eig_ham_dense : bool
        Force dense representation of the effective hamiltonian.
    local_eig_EPSType : {'krylovschur', 'gd', 'jd', ...}
        Eigensovler tpye if ``local_eig_backend='slepc'``.
    local_eig_norm_dense : bool
        Force dense representation of the effective norm.
    periodic_segment_size : float or int
        How large (as a proportion if float) to make the 'segments' in periodic
        DMRG. During a sweep everything outside this (the 'long way round') is
        compressed so the effective energy and norm can be efficiently formed.
        Tradeoff: longer segments means having to compress less, but also
        having a shorter 'long way round', meaning that it needs a larger bond
        to represent it and can be 'pseudo-orthogonalized' less effectively.
        0.5 is the largest fraction that makes sense. Set to >= 1.0 to not
        use segmentation at all, which is better for small systems.
    periodic_compress_method : {'isvd', 'svds'}
        Which method to perform the transfer matrix compression with.
    periodic_compress_norm_eps : float
        Precision to compress the norm transfer matrix in periodic systems.
    periodic_compress_ham_eps : float
        Precision to compress the energy transfer matrix in periodic systems.
    periodic_compress_max_bond : int
        The maximum bond to use when compressing transfer matrices.
    periodic_nullspace_fudge_factor : float
        Factor to add to ``Heff`` and ``Neff`` to remove nullspace.
    periodic_canonize_inv_tol : float
        When psuedo-orthogonalizing, an inverse gauge is generated that can be
        very ill-conditioned. This factor controls cutting off the small
        singular values of the gauge to stop this.
    periodic_orthog_tol : float
        When psuedo-orthogonalizing, if the local norm is within this
        distance to 1 (pseudo-orthogonoalized), then the generalized eigen
        decomposition is *not* used, which is much more efficient. If set too
        large the total normalization can become unstable.
    """
    return {'default_sweep_sequence': 'R', 'bond_compress_method': 'svd',
        'bond_compress_cutoff_mode': 'rel' if cyclic else 'sum2',
        'bond_expand_rand_strength': 1e-06, 'local_eig_tol': 0.001,
        'local_eig_ncv': 4, 'local_eig_backend': None, 'local_eig_maxiter':
        None, 'local_eig_EPSType': None, 'local_eig_ham_dense': None,
        'local_eig_norm_dense': None, 'periodic_segment_size': 1 / 2,
        'periodic_compress_method': 'isvd', 'periodic_compress_norm_eps':
        1e-06, 'periodic_compress_ham_eps': 1e-06,
        'periodic_compress_max_bond': -1, 'periodic_nullspace_fudge_factor':
        1e-12, 'periodic_canonize_inv_tol': 1e-10, 'periodic_orthog_tol': 1e-06
        }


@staticmethod
def bacc(pos_acc, neg_acc):
    """compute balanced accuracy"""
    return float(pos_acc + neg_acc) / 2


def _applySpecial_SceneOpts_movieSyncRefresh(args, overlayList, displayCtx,
    target):
    """Applies the ``SceneOpts.movieSyncRefresh`` option. """
    if args.movieSync:
        target.movieSyncRefresh = not target.defaultMovieSyncRefresh


def int_to_bytes(value):
    """Converts an integer to a big-endian sequence of bytes"""
    return value.to_bytes((value.bit_length() + 7) // 8, 'big')


def calc_generation(I_0, alpha):
    """
   Does nothing so far.
   """
    return None


def delete(item):
    """This method is called to remove item from its container"""


@staticmethod
def _get_value(obj, ds_key, transformer):
    """
        Get value from source object, transforming if specified

        :param obj: the input object we are translating to STIX
        :param ds_key: the property from the input object
        :param transformer: the transform to apply to the property value (can be None)
        :return: the resulting STIX value
        """
    if ds_key not in obj:
        print('{} not found in object'.format(ds_key))
        return None
    ret_val = obj[ds_key]
    if ret_val and transformer is not None:
        return transformer.transform(ret_val)
    return ret_val


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 vector_to_diagonal(v):
    """Converts a vector to a diagonal matrix with vector elements
    as the diagonal elements of the matrix"""
    diag_matrix = [[(0) for i in range(len(v))] for j in range(len(v))]
    for i in range(len(v)):
        diag_matrix[i][i] = v[i]
    return diag_matrix


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


@staticmethod
def __get_preset_dictionary_v1(root):
    """
        Get the presets and returns a dictionary with all the key-value pairs.

        Example output: {'away': 17.0, 'home': 20.0, 'vacation': 15.0,
        'no_frost': 10.0, 'asleep': 15.0}.
        """
    preset_dictionary = {}
    directives = root.findall('rule/directives/when/then')
    for directive in directives:
        if directive is not None and 'icon' in directive.keys():
            preset_dictionary[directive.attrib['icon']] = float(directive.
                attrib['temperature'])
    return preset_dictionary


@classmethod
def load_xml(cls, filehandle, **kwargs):
    """
        Load a DMRS from a file
        NB: read file as bytes!
        """
    return cls.loads_xml(filehandle.read(), **kwargs)


def tags2set(tags):
    """Parse a ``tags`` argument into a set - leave if already one.
    """
    if isinstance(tags, set):
        return tags
    elif tags is None:
        return set()
    elif isinstance(tags, str):
        return {tags}
    else:
        return set(tags)


def handle_leap_year(t):
    """given a time struct, give the number of days in February for that year"""
    return 29 if t.tm_year % 4 == 0 else 28


def set_item_in_dict(dictionary, item, value):
    """
    Set dictionary item from a dotted-word.

    >>> d = {"x": 1}
    >>> get_item_in_dict(d, "x")
    1
    >>> set_item_in_dict(d, "x", 2)
    >>> get_item_in_dict(d, "x")
    2
    >>> d2 = {"x": {"y": 42}}
    >>> get_item_in_dict(d2, "x.y")
    42
    >>> set_item_in_dict(d2, "x.y", 43)
    >>> get_item_in_dict(d2, "x.y")
    43
    """
    current = dictionary
    words = item.split('.')
    for word in words[:-1]:
        current = current[word]
    current[words[-1]] = value


def upload_layer_part(registryId=None, repositoryName=None, uploadId=None,
    partFirstByte=None, partLastByte=None, layerPartBlob=None):
    """
    Uploads an image layer part to Amazon ECR.
    See also: AWS API Documentation

    :example: response = client.upload_layer_part(
        registryId='string',
        repositoryName='string',
        uploadId='string',
        partFirstByte=123,
        partLastByte=123,
        layerPartBlob=b'bytes'
    )

    :type registryId: string
    :param registryId: The AWS account ID associated with the registry that you are uploading layer parts to. If you do not specify a registry, the default registry is assumed.

    :type repositoryName: string
    :param repositoryName: [REQUIRED]
            The name of the repository that you are uploading layer parts to.

    :type uploadId: string
    :param uploadId: [REQUIRED]
            The upload ID from a previous InitiateLayerUpload operation to associate with the layer part upload.

    :type partFirstByte: integer
    :param partFirstByte: [REQUIRED]
            The integer value of the first byte of the layer part.

    :type partLastByte: integer
    :param partLastByte: [REQUIRED]
            The integer value of the last byte of the layer part.

    :type layerPartBlob: bytes
    :param layerPartBlob: [REQUIRED]
            The base64-encoded layer part payload.

    :rtype: dict
    :return: {
        'registryId': 'string',
        'repositoryName': 'string',
        'uploadId': 'string',
        'lastByteReceived': 123
    }

    """
    pass


def ParseBool(text):
    """Parse a boolean value.

  Args:
    text: Text to parse.

  Returns:
    Boolean values parsed

  Raises:
    ValueError: If text is not a valid boolean.
  """
    if text in ('true', 't', '1'):
        return True
    elif text in ('false', 'f', '0'):
        return False
    else:
        raise ValueError('Expected "true" or "false".')


def get_page_limit(request, default):
    """Return page and limit as integers."""
    try:
        limit = int(request.GET.get('limit', default))
    except ValueError:
        limit = default
    limit = min(max(10, limit), 2000)
    try:
        page = int(request.GET.get('page', 1))
    except ValueError:
        page = 1
    page = max(1, page)
    return page, limit


def Trim(t, p=0.01):
    """Trims the largest and smallest elements of t.

    Args:
        t: sequence of numbers
        p: fraction of values to trim off each end

    Returns:
        sequence of values
    """
    n = int(p * len(t))
    t = sorted(t)[n:-n]
    return t


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

        :param SharedContentRemoveMemberDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_remove_member_details', val)


def label_to_name(class_dict, label):
    """ Map label to name.
        """
    name = class_dict[label]
    return name


def index_resolver(index, strict=False):
    """Returns a function that accepts a value and returns index[value]."""
    if strict:
        return lambda id_: index[id_]
    else:
        return index.get


def unique(seq):
    """ Remove duplicates from the supplied sequence """
    dictionary = {}
    for i in seq:
        dictionary[i] = 1
    return list(dictionary.keys())


def format_trace_id(trace_id):
    """Format the trace id according to b3 specification."""
    return format(trace_id, '016x')[-16:]


def array_offsets_xy(test_geo, offsets):
    """Return centroid x/y for an array and offsets

    Parameters
    ----------
    test_geo (): Geotransform from which the x/y are to be calculated
    offsets (): number of cells to offset in the x, y direction. Input
        as a list or tuple

    Returns
    -------
    x: x coordinate of centroid
    y: y coordinate of centroid

    """
    xi, yi = offsets
    x = test_geo[0] + (xi + 0.5) * test_geo[1]
    y = test_geo[3] + (yi + 0.5) * test_geo[5]
    return x, y


def maybe(obj, attribute):
    """Return object attribute or None if it does not exist"""
    try:
        return getattr(obj, attribute)
    except AttributeError:
        return None


def get_list(dct, item, default=()):
    """
    Get an item from a dictionary, like `dict.get`.

    This method will transform all scalar values into lists of lenght 1
    """
    value = dct.get(item, default)
    if not isinstance(value, (list, tuple)):
        value = [value]
    return list(value)


def extract_generics(error_lines):
    """
    Parse the errors output from ghdl to determine what generics
    are required by the generators.
    """
    ds = []
    for line in error_lines:
        d = {}
        pieces = line.split('Generator')
        if len(pieces) == 2:
            params = pieces[1].split()
            for param in params:
                key, value = param.split('=')
                assert key not in d
                d[key] = value
                ds.append(d)
    return ds


def cli(hub):
    """
    Execute a single idem run from the cli
    """
    hub.pop.config.load(['idem', 'takara'], cli='idem')
    hub.pop.loop.start(hub.idem.init.cli_apply())


def oif_axis_size(oifsettings):
    """Return dict of axes sizes from OIF main settings."""
    scale = {'nm': 1000.0, 'ms': 1000.0}
    result = {}
    i = 0
    while True:
        try:
            axis = oifsettings[f'Axis {i} Parameters Common']
        except KeyError:
            break
        size = abs(axis['EndPosition'] - axis['StartPosition'])
        size /= scale.get(axis['UnitName'], 1.0)
        result[axis['AxisCode']] = size
        i += 1
    return result


@classmethod
def assert_zcorn(cls, nx, ny, nz, zcorn, twisted_check=True):
    """

        Raises an AssertionError if the zcorn is not as expected. In
        patricular, it is verified that:

            - zcorn has the approperiate length (8*nx*ny*nz) and
            - that no cell is twisted.

        """
    if len(zcorn) != 8 * nx * ny * nz:
        raise AssertionError('Expected len(zcorn) to be %d, was %d' % (8 *
            nx * ny * nz, len(zcorn)))
    plane_size = 4 * nx * ny
    for p in range(8 * nx * ny * nz - plane_size):
        if zcorn[p] > zcorn[p + plane_size] and twisted_check:
            raise AssertionError('Twisted cell was created. ' +
                'Decrease offset or increase dz to avoid this!')


def return_one(result):
    """return one statement"""
    return '            return ' + result


def longest_common_substring(s1, s2):
    """
    From https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Longest_common_substring#Python
    @param s1: string 1
    @param s2: string 2
    @return: string: the longest common string!
    """
    m = [([0] * (1 + len(s2))) for i in range(1 + len(s1))]
    longest, x_longest = 0, 0
    for x in range(1, 1 + len(s1)):
        for y in range(1, 1 + len(s2)):
            if s1[x - 1] == s2[y - 1]:
                m[x][y] = m[x - 1][y - 1] + 1
                if m[x][y] > longest:
                    longest = m[x][y]
                    x_longest = x
            else:
                m[x][y] = 0
    return s1[x_longest - longest:x_longest]


def Iy(x, y, z, Hx, Hy, Hz, G):
    """Calculates the y-component of current at a grid position.

    Args:
        x, y, z (float): Coordinates of position in grid.
        Hx, Hy, Hz (memory view): numpy array of magnetic field values.
        G (class): Grid class instance - holds essential parameters describing the model.
    """
    if x == 0 or z == 0:
        Iy = 0
    else:
        Iy = G.dx * (Hx[x, y, z] - Hx[x, y, z - 1]) + G.dz * (Hz[x - 1, y,
            z] - Hz[x, y, z])
    return Iy


def postgres_migration_prep(apps, schema_editor):
    """
    Set null text fields to empty string to workaround incompatibility with migration 0003 on postgres
    See https://github.com/dj-stripe/dj-stripe/issues/850
    """
    Account = apps.get_model('djstripe', 'Account')
    BankAccount = apps.get_model('djstripe', 'BankAccount')
    Card = apps.get_model('djstripe', 'Card')
    Charge = apps.get_model('djstripe', 'Charge')
    Customer = apps.get_model('djstripe', 'Customer')
    Event = apps.get_model('djstripe', 'Event')
    Invoice = apps.get_model('djstripe', 'Invoice')
    Payout = apps.get_model('djstripe', 'Payout')
    Plan = apps.get_model('djstripe', 'Plan')
    Product = apps.get_model('djstripe', 'Product')
    Refund = apps.get_model('djstripe', 'Refund')
    Source = apps.get_model('djstripe', 'Source')
    Transfer = apps.get_model('djstripe', 'Transfer')
    model_fields = [(Account, ('business_name', 'business_primary_color',
        'business_url', 'payout_statement_descriptor',
        'product_description', 'support_url')), (BankAccount, (
        'account_holder_name',)), (Card, ('address_city', 'address_country',
        'address_line1', 'address_line1_check', 'address_line2',
        'address_state', 'address_zip', 'address_zip_check', 'country',
        'cvc_check', 'dynamic_last4', 'fingerprint', 'name',
        'tokenization_method')), (Charge, ('failure_code',
        'failure_message', 'receipt_email', 'receipt_number',
        'statement_descriptor', 'transfer_group')), (Customer, (
        'business_vat_id', 'currency', 'email')), (Event, (
        'idempotency_key', 'request_id')), (Invoice, ('hosted_invoice_url',
        'invoice_pdf', 'number', 'statement_descriptor')), (Payout, (
        'failure_code', 'failure_message', 'statement_descriptor')), (Plan,
        ('aggregate_usage', 'billing_scheme', 'nickname')), (Product, (
        'caption', 'statement_descriptor', 'unit_label')), (Refund, (
        'failure_reason', 'reason', 'receipt_number')), (Source, (
        'currency', 'statement_descriptor')), (Transfer, ('transfer_group',))]
    for model, fields in model_fields:
        for field in fields:
            filter_param = {'{}__isnull'.format(field): True}
            update_param = {field: ''}
            model.objects.filter(**filter_param).update(**update_param)


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 load_idna(finder, module):
    """the idna module implicitly loads data; make sure this happens."""
    finder.IncludeModule('idna.idnadata')


def getattrrec(object, name, *default):
    """Extract the underlying data from an onion of wrapper objects.

    ``r = object.name``, and then get ``r.name`` recursively, as long as
    it exists. Return the final result.

    The ``default`` parameter acts as in ``getattr``.

    See also ``setattrrec``.
    """
    o = getattr(object, name, *default)
    while hasattr(o, name):
        o = getattr(o, name, *default)
    return o


def to_float(val):
    """Convert val to float (or raise Exception)

    :param val: value to convert
    :type val:
    :return: float(val)
    :rtype: float
    """
    return float(val)


def scroll(driver, scroll_element=None):
    """Scrolls the current page or the Selenium WebElement if one is provided

    Args:
        driver (selenium.webdriver.): Selenium webdriver to use.
        scroll_element (selenium.webdriver.remote.webelement.WebElement): Selenium webelement to scroll.

    Examples:
        ::

            from selenium import webdriver
            from selenium_extensions.core import scroll

            driver = webdriver.Chrome()
            scroll(driver)

        ::

            from selenium import webdriver
            from selenium_extensions.core import scroll

            driver = webdriver.Chrome()
            ...
            pop_up = driver.find_element_by_class_name('ff_pop_up')
            scroll(driver, pop_up)
    """
    if scroll_element:
        driver.execute_script(
            'arguments[0].scrollTop = arguments[0].scrollHeight;',
            scroll_element)
    else:
        driver.execute_script(
            'document.body.scrollTop = document.body.scrollHeight;')


def _to_year(parsed):
    """
    Transforms the parsed two digits integer into a valid year value.

    :param parsed: the parsed value
    """
    return 2000 + parsed[0]


def needRecatalog():
    """Does this thing now need recataloging?"""


def pep8_module_name(name):
    """Convert a module name to a PEP8 compliant module name.

    * lowercase
    * whitespace -> underscore
    * dash -> underscore
    """
    if name[0].isnumeric():
        name = '_' + name
    valid_module_name = name.lower().replace('-', '_').replace(' ', '_')
    return valid_module_name


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

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


def _to_iloc(data):
    """Indexible attribute of array."""
    return getattr(data, 'iloc', data)


def chunks(l, n):
    """
	Yield successive n-sized chunks from l.

	:param l:
	:param n:
	:return:
	"""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def _isalnumMUTF8(c):
    """Return True if the given UTF-8 encoded character is alphanumeric
    or multibyte.

    Input is not checked!
    """
    return c.isalnum() or len(c.encode('utf-8')) > 1


def get_document_version(DocumentId=None, VersionId=None, Fields=None):
    """
    Retrieves version metadata for the specified document.
    See also: AWS API Documentation

    :example: response = client.get_document_version(
        DocumentId='string',
        VersionId='string',
        Fields='string'
    )

    :type DocumentId: string
    :param DocumentId: [REQUIRED]
            The ID of the document.

    :type VersionId: string
    :param VersionId: [REQUIRED]
            The version ID of the document.

    :type Fields: string
    :param Fields: A comma-separated list of values. Specify 'SOURCE' to include a URL for the source document.

    :rtype: dict
    :return: {
        'Metadata': {
            'Id': 'string',
            'Name': 'string',
            'ContentType': 'string',
            'Size': 123,
            'Signature': 'string',
            'Status': 'INITIALIZED'|'ACTIVE',
            'CreatedTimestamp': datetime(2015, 1, 1),
            'ModifiedTimestamp': datetime(2015, 1, 1),
            'ContentCreatedTimestamp': datetime(2015, 1, 1),
            'ContentModifiedTimestamp': datetime(2015, 1, 1),
            'CreatorId': 'string',
            'Thumbnail': {
                'string': 'string'
            },
            'Source': {
                'string': 'string'
            }
        }
    }

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

    """
    pass


def __call__(cls, *args, **kwargs):
    """Do not allow the class to be instantiated."""
    raise TypeError('Type {} cannot be instantiated.'.format(cls.__name__))


def is_above_min_depth(record):
    """
    Check if the record is above the min depth threshold.

    Parameters:
    -----------
    record: obj
        a record from the vcf library

    Returns:
    --------
    above: boolean
        True if record is above min depth
    """
    above = True
    for f in record.FILTER:
        if 'min_depth' in f:
            above = False
            break
    return above


def normalize(scraped):
    """ Turns the return format from do_scrape into the schema type """
    normal = []
    for dat in scraped:
        url = dat['url']
        res = dat['res']
        spec, sess = url.split('.')[0].split('_')
        normal.append({'specialisation': spec, 'session': sess,
            'last_updated': res['last_updated'], 'courses': res['courses']})
    return normal


def _get_data_var_message(obj):
    """
    Get message for named data variables.
    """
    try:
        return f' Data variable: {obj.name}' if obj.name else ''
    except AttributeError:
        return ''


def check_duplicate_slugs(contents):
    """
	check for duplicate slugs
	"""
    slugs = []
    for post in contents:
        slug = ''
        if post.path.startswith('pages/'):
            slug = post.path.split('pages/')[1]
        elif post.path.startswith('posts/'):
            slug = post.path.split('posts/')[1]
        if slug and slug in slugs:
            raise ValueError('Duplicate slug : {}'.format())


def _only_var_left_in_poly(poly, extension_vars):
    """
    Checks whether that there is only one other variable besides
    the variables in extension_vars.
    In other words, if the variables in extension_vars are bound,
    checks that the polynomial has only one free variable and returns
    its name.
    """
    vars_left = set(poly.variables()) - set(extension_vars)
    no_vars_left = len(vars_left)
    assert no_vars_left > 0
    if no_vars_left > 1:
        return None
    return list(vars_left)[0]


def _BorderEdges(facelist):
    """Return a set of (u,v) where u and v are successive vertex indices
    in some face in the list in facelist."""
    ans = set()
    for i in range(0, len(facelist)):
        f = facelist[i]
        for j in range(1, len(f)):
            ans.add((f[j - 1], f[j]))
        ans.add((f[-1], f[0]))
    return ans


def del_secret_token(node):
    """Deletes the IPA agent secret token.

    Removes the agent token secret from the driver_internal_info field
    from the Node object.

    :param node: Node object
    """
    i_info = node.driver_internal_info
    i_info.pop('agent_secret_token', None)
    node.driver_internal_info = i_info


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 _test3():
    """
    >>> vtor.check('string(default="")', '', missing=True)
    ''
    >>> vtor.check('string(default="\\n")', '', missing=True)
    '\\n'
    >>> print(vtor.check('string(default="\\n")', '', missing=True))
    <BLANKLINE>
    <BLANKLINE>
    >>> vtor.check('string()', '\\n')
    '\\n'
    >>> vtor.check('string(default="\\n\\n\\n")', '', missing=True)
    '\\n\\n\\n'
    >>> vtor.check('string()', 'random \\n text goes here\\n\\n')
    'random \\n text goes here\\n\\n'
    >>> vtor.check('string(default=" \\nrandom text\\ngoes \\n here\\n\\n ")',
    ... '', missing=True)
    ' \\nrandom text\\ngoes \\n here\\n\\n '
    >>> vtor.check("string(default='\\n\\n\\n')", '', missing=True)
    '\\n\\n\\n'
    >>> vtor.check("option('\\n','a','b',default='\\n')", '', missing=True)
    '\\n'
    >>> vtor.check("string_list()", ['foo', '\\n', 'bar'])
    ['foo', '\\n', 'bar']
    >>> vtor.check("string_list(default=list('\\n'))", '', missing=True)
    ['\\n']
    """


def _get_column_letter(col_idx):
    """Convert a column number into a column letter (3 -> 'C')

    Right shift the column col_idx by 26 to find column letters in reverse
    order.  These numbers are 1-based, and can be converted to ASCII
    ordinals by adding 64.

    Credits: openpyxl library
    """
    if not 1 <= col_idx <= 18278:
        raise ValueError('Invalid column index {0}'.format(col_idx))
    letters = []
    while col_idx > 0:
        col_idx, remainder = divmod(col_idx, 26)
        if remainder == 0:
            remainder = 26
            col_idx -= 1
        letters.append(chr(remainder + 64))
    return ''.join(reversed(letters))


def dynamic_load(name):
    """Equivalent of "from X import Y" statement using dot notation to specify
    what to import and return.  For example, foo.bar.thing returns the item
    "thing" in the module "foo.bar" """
    pieces = name.split('.')
    item = pieces[-1]
    mod_name = '.'.join(pieces[:-1])
    mod = __import__(mod_name, globals(), locals(), [item])
    return getattr(mod, item)


def SwapIndx(Axis, H):
    """needs doc string"""
    if Axis in [1, -1]:
        return H
    elif Axis in [2, -3]:
        return [H[1], H[2], H[0]]
    else:
        return [H[2], H[0], H[1]]


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


@staticmethod
def compute_filling_factor(surface_potential, lagrangian_points):
    """
        Compute filling factor of given BinaryStar system.
        Filling factor is computed as::

            (Omega_{inner} - Omega) / (Omega_{inner} - Omega_{outter}),

        where Omega_X denote potential value and `Omega` is potential of given Star.
        Inner and outter are critical inner and outter potentials for given binary star system.

        :param surface_potential: float;
        :param lagrangian_points: List; lagrangian points in `order` (in order to ensure that L2)
        :return: float;
        """
    return (lagrangian_points[1] - surface_potential) / (lagrangian_points[
        1] - lagrangian_points[2])


def object_as_category(df_data):
    """
    dataframe object to category
    :param df_data:
    :return:
    """
    for col in df_data.columns:
        if df_data[col].dtype != 'object':
            continue
        num_unique_values = len(df_data[col].unique())
        num_total_values = len(df_data[col])
        if not num_total_values:
            return df_data
        if num_unique_values / num_total_values < 0.5:
            df_data.loc[:, (col)] = df_data[col].astype('category')
    return df_data


def __len__():
    """number of incoming things"""


@staticmethod
def _vlan_tag_check(literal):
    """
        Check if the VLAN tag literal is a range or not and returns start and end tag number.

        :param literal: (str) VLAN tag literal
        :return: start_vlan (str), end_vlan (str)
        """
    if '-' in literal:
        vlans = literal.strip('-')
        return vlans[0], vlans[1]
    else:
        return literal, literal


def hook_add_newob():
    """Hook selected vertices to a newly created object

    """
    pass


def is_session_dir(path):
    """Return whether a path is a session directory.

    Example of a session dir: `/path/to/root/mainenlab/Subjects/ZM_1150/2019-05-07/001/`

    """
    return path.is_dir() and path.parent.parent.parent.name == 'Subjects'


def split(path):
    """
    splits path into parent, child
    """
    if path == '/':
        return '/', None
    parent, child = path.rsplit('/', 1)
    if parent == '':
        parent = '/'
    return parent, child


def invalid_json_schema():
    """
    Verified 2015-06-16 for creating a LB, changing a node, adding nodes:

    - when providing invalid fields in the JSON request
    - when providing invalid JSON
    - this schema validation happens even before checking whether a LB and/or
      node exists

    :return: a `tuple` of (dict body message, 400 http status code)
    """
    return {'message': ['JSON does not match the expected schema']}, 400


@classmethod
def forProtocol(cls, protocol, *args, **kwargs):
    """
        Create a factory for the given protocol.

        It sets the C{protocol} attribute and returns the constructed factory
        instance.

        @param protocol: A L{Protocol} subclass

        @param args: Positional arguments for the factory.

        @param kwargs: Keyword arguments for the factory.

        @return: A L{Factory} instance wired up to C{protocol}.
        """
    factory = cls(*args, **kwargs)
    factory.protocol = protocol
    return factory


def protocol_from_http(protocol_str):
    """Return a protocol tuple from the given 'HTTP/x.y' string."""
    return int(protocol_str[5]), int(protocol_str[7])


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

    The ".dev0" means dirty.

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


def qmult(q1, q2):
    """ Multiply two quaternions

    Parameters
    ----------
    q1 : 4 element sequence
    q2 : 4 element sequence

    Returns
    -------
    q12 : shape (4,) array

    Notes
    -----
    See : http://en.wikipedia.org/wiki/Quaternions#Hamilton_product
    """
    w1, x1, y1, z1 = q1
    w2, x2, y2, z2 = q2
    w = w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2
    x = w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2
    y = w1 * y2 + y1 * w2 + z1 * x2 - x1 * z2
    z = w1 * z2 + z1 * w2 + x1 * y2 - y1 * x2
    return w, x, y, z


def numeric_parse_text(conn, table, word_embeddings_file, word_delimiter=
    '\t', parse_column='first_objects'):
    """
    Parses text data into numeric data using a word-embeddings file

    Parameters
    ----------
    conn : CAS
        Specifies the CAS connection object.
    table: CASTable
        Specifies table containing data to be parsed
    word_embeddings_file : string
        Specifies path to file containing word embeddings
    word_delimiter : string, optional
        Specifies delimiter used in word embeddings file
        Default : '	'
    parse_column : string, optional
        Specifies name of column containing text data to be parsed
        Default : 'first_objects'
    Returns
    -------
    :class:`CASTable`

    """
    conn.upload_file(data=word_embeddings_file, casout=dict(name=
        'word_embeddings', replace=True), importOptions=dict(fileType=
        'delimited', delimiter=word_delimiter, getNames=True, guessRows=2,
        varChars=True))
    conn.tpParse(table=table, docId='_id_', entities='NONE', text=
        parse_column, nounGroups=False, offset=dict(name='pos_output',
        replace=True))
    conn.applyWordVector(casout=dict(name='objects_all_numeric', replace=
        True), modelTable=dict(name='word_embeddings'), table=dict(name=
        'pos_output'))
    conn.altertable('objects_all_numeric', columns=[dict(name='_Document_',
        rename='_id_')])
    objects_numeric = conn.CASTable('objects_all_numeric')
    return objects_numeric


def layers_ui(layers, layout):
    """ Turn a list of booleans + a list of names into a layer UI.
    """
    code = """
class RigLayers(bpy.types.Panel):
    bl_space_type = 'VIEW_3D'
    bl_region_type = 'UI'
    bl_label = "Rig Layers"
    bl_idname = rig_id + "_PT_rig_layers"

    @classmethod
    def poll(self, context):
        try:
            return (context.active_object.data.get("rig_id") == rig_id)
        except (AttributeError, KeyError, TypeError):
            return False

    def draw(self, context):
        layout = self.layout
        col = layout.column()
"""
    rows = {}
    for i in range(28):
        if layers[i]:
            if layout[i][1] not in rows:
                rows[layout[i][1]] = []
            rows[layout[i][1]] += [(layout[i][0], i)]
    keys = list(rows.keys())
    keys.sort()
    for key in keys:
        code += """
        row = col.row()
"""
        i = 0
        for l in rows[key]:
            if i > 3:
                code += '\n        row = col.row()\n'
                i = 0
            code += (
                """        row.prop(context.active_object.data, 'layers', index=%s, toggle=True, text='%s')
"""
                 % (str(l[1]), l[0]))
            i += 1
    code += """
        row = col.row()"""
    code += """
        row.separator()"""
    code += """
        row = col.row()"""
    code += """
        row.separator()
"""
    code += """
        row = col.row()
"""
    code += """        row.prop(context.active_object.data, 'layers', index=28, toggle=True, text='Root')
"""
    return code


def spooler_jobs():
    """Returns a list of spooler jobs (filenames in spooler directory).

    :rtype: list[str]
    """
    return []


@classmethod
def SerialMatcher(cls, serial):
    """Returns a device matcher for the given serial."""
    return lambda device: device.serial_number == serial


def test_teardown(test):
    """Called after every test has run.

    Add an implementation of this to your own lifecycle module.

    :param unittest_jasmine.unittest.Test test: The test that has completed.
    """
    pass


def validate_boolean(setting, value, option_parser, config_parser=None,
    config_section=None):
    """Check/normalize boolean settings:
         True:  '1', 'on', 'yes', 'true'
         False: '0', 'off', 'no','false', ''
    """
    if isinstance(value, bool):
        return value
    try:
        return option_parser.booleans[value.strip().lower()]
    except KeyError:
        raise LookupError('unknown boolean value: "%s"' % value)


def _display_interval(i):
    """Convert a time interval into a human-readable string.

    :param i: The interval to convert, in seconds.
    """
    sigils = ['d', 'h', 'm', 's']
    factors = [24 * 60 * 60, 60 * 60, 60, 1]
    remain = int(i)
    result = ''
    for fac, sig in zip(factors, sigils):
        if remain < fac:
            continue
        result += '{}{}'.format(remain // fac, sig)
        remain = remain % fac
    return result


def assemble_warnings(w):
    """pretty-format all warnings for logs"""
    wlog = []
    for wi in w:
        wlog.append('{}'.format(wi.category.__name__))
        wlog.append(' in {} line {}:'.format(wi.category.__module__, wi.lineno)
            )
        words = str(wi.message).split(' ')
        wline = '  '
        for ii in range(len(words)):
            wline += ' ' + words[ii]
            if ii == len(words) - 1:
                wlog.append(wline)
            elif len(wline + words[ii + 1]) + 1 >= 100:
                wlog.append(wline)
                wline = '  '
    return wlog


def notwanted(obj, notwant):
    """ determine whether this object in not wanted in a query. """
    if not notwant:
        return False
    for key in notwant:
        try:
            value = obj[key]
            return True
        except:
            pass
    return False


def wraptext(line, indent=None):
    """
    Wrap line of text at eighty characters while allowing ability to indent.

    @param line: Text to wrap at 80 characters.
    @type line: basestring
    @param indent: Indent line of text number of characters. Default 'None'.
    @type indent: int
    @return: List of wrapped lines
    @rtype: list

    @requires: textwrap
    """
    import textwrap
    indent = ' ' * indent if indent else ''
    wrapline = textwrap.TextWrapper(width=80, initial_indent=indent,
        subsequent_indent=indent)
    return wrapline.wrap(line)


def future_add_done_callback(future, callback):
    """Arrange to call ``callback`` when ``future`` is complete.

    ``callback`` is invoked with one argument, the ``future``.

    If ``future`` is already done, ``callback`` is invoked immediately.
    This may differ from the behavior of ``Future.add_done_callback``,
    which makes no such guarantee.

    .. versionadded:: 5.0
    """
    if future.done():
        callback(future)
    else:
        future.add_done_callback(callback)


def generator_sum(a, b):
    """
	Generate the sum of settings.
	"""
    return a + b


def parse_track(trackelement):
    """Extract info from every track entry and output to list.

    :param trackelement: json element representing a track
    :return: List containing the date, title, artist and albumname corresponding to the track
    """
    artistname = trackelement['artist']['#text']
    albumname = trackelement['album']['#text']
    trackname = trackelement['name']
    date = trackelement['date']['uts']
    output = [date, trackname, artistname, albumname]
    for i, v in enumerate(output):
        if v is None:
            output[i] = ''
    return output


def text2html_table(items):
    """Put the texts in `items` in an HTML table."""
    html_code = f'
\n'
    html_code += f"""

"""
    for i in items[0]:
        html_code += f'      {i}	\n'
    html_code += f'
\n
\n
\n'
    for line in items[1:]:
        html_code += '
\n'
        for i in line:
            html_code += f'      {i}	\n'
        html_code += '
\n'
    html_code += '
\n

'
    return html_code


def get_models_names():
    """Return a list with the models names."""
    return ['foo', 'bar', 'baz']


def _combine_dicts(list_of_dicts, combine_function):
    """
    >>> d = _combine_dicts(
    ...      [ {'key1': 1, 'key2': 2},
    ...        {'key1': 1} ],
    ...      combine_function = operator.add)
    >>> d['key1']
    2
    >>> d['key2']
    2
    """
    result = {}
    for a_dict in list_of_dicts:
        for k, v in list(a_dict.items()):
            if k in result:
                result[k] = combine_function(result[k], v)
            else:
                result[k] = v
    return result


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 summarize(logger):
    """
    Creates a short summary on the actions that were logged by the given
    Logger.

    :type  logger: Logger
    :param logger: The logger that recorded what happened in the queue.
    :rtype:  string
    :return: A string summarizing the status of every performed task.
    """
    summary = []
    for log in logger.get_logs():
        thestatus = log.has_error() and log.get_error(False) or 'ok'
        name = log.get_name()
        summary.append(name + ': ' + thestatus)
    return '\n'.join(summary)


def get_mode_parameter(mode):
    """
    Map the mode parameter to the server parameter
    """
    if mode == 'job':
        return 'cli'
    elif mode == 'serve':
        return 'serve'
    else:
        return mode


def bC_H_OH_HMW84(T, P):
    """c-a: hydrogen hydroxide [HMW84]."""
    b0 = 0.0
    b1 = 0.0
    b2 = 0.0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


@classmethod
def topic(cls, **kwargs) ->str:
    """Get MQTT topic for this message type."""
    return 'hermes/dialogueManager/intentNotRecognized'


def leftmost(root):
    """
    Returns the leftmost leaf in this tree.

    :param root: The root node of the tree.
    :type root: d20.ast.ChildMixin
    :rtype: d20.ast.ChildMixin
    """
    left = root
    while left.children:
        left = left.children[0]
    return left


def validate_digest_nonce(params, request, nonce_manager):
    """Validate that the digest parameters contain a fresh nonce.

    This is a helper function to check that the provided digest-auth
    credentials contain a valid, up-to-date nonce.  It calls various
    methods on the provided NonceManager object in order to query and
    update the state of the nonce database.

    Returns True if the nonce is valid, False otherwise.
    """
    nonce = params['nonce']
    if not nonce_manager.is_valid_nonce(nonce, request):
        return False
    nc_new = params.get('nc', None)
    if nc_new is not None:
        try:
            nc_new = int(nc_new[:8], 16)
        except ValueError:
            return False
    nc_old = nonce_manager.get_nonce_count(nonce)
    if nc_old is not None:
        if nc_new is None or nc_new <= nc_old:
            return False
    if nc_new is not None:
        nonce_manager.set_nonce_count(nonce, nc_new)
    return True


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

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


def fileExt(filename):
    """Returns file extension of inputed filename. One paramater is required: filename"""
    import os
    return os.path.splitext(filename)[1]


def generate_presigned_url(ClientMethod=None, Params=None, ExpiresIn=None,
    HttpMethod=None):
    """
    Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
            ClientMethod.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
            default, the http method is whatever is used in the method's model.

    """
    pass


def p_sat(T=293.15):
    """
    Water vapor saturation pressure [Pa]

    input : temperature T [K]
    """
    T_celsius = T - 273.15
    log_p_sat = 2.7858 + 7.5 * T_celsius / (237.3 + T_celsius)
    return 10 ** log_p_sat


@staticmethod
def RK4(x_initial, p_initial, timestep, H_p, H_x):
    """Non-symplectic one-dimensional Runge Kutta 4 O(T^5) Algorithm."""
    x_a = timestep * H_p(p_initial)
    p_a = -timestep * H_x(x_initial)
    x_b = timestep * H_p(p_initial + 0.5 * p_a)
    p_b = -timestep * H_x(x_initial + 0.5 * x_a)
    x_c = timestep * H_p(p_initial + 0.5 * p_b)
    p_c = -timestep * H_x(x_initial + 0.5 * x_b)
    x_d = timestep * H_p(p_initial + p_c)
    p_d = -timestep * H_x(x_initial + x_c)
    x_final = x_initial + x_a / 6.0 + x_b / 3.0 + x_c / 3.0 + x_d / 6.0
    p_final = p_initial + p_a / 6.0 + p_b / 3.0 + p_c / 3.0 + p_d / 6.0
    return x_final, p_final


def ni(i, minutes='minutes'):
    """
    Utility to normalize the the interval parameter.
    :params i:
    """
    if not isinstance(i, int):
        raise ValueError('For ib.ni minutes must be an int')
    durdict = {(1): '1 min', (2): '2 mins', (3): '3 mins', (5): '5 mins', (
        10): '10 mins', (15): '15 mins', (20): '20 mins', (30): '30 mins',
        (60): '1 hour'}
    resamp = False
    if i in durdict.keys():
        return resamp, (durdict[i], i, i)
    resamp = True
    if isinstance(i, int):
        return resamp, ('1 min', 1, i)
    return False, ('', 0, 0)


def getConstructor():
    """Return the __init__ method, or None if there isn't one."""


def UdJH_to_F0F2F4(Ud, JH):
    """
    Given :math:`U_d` and :math:`J_H`, return :math:`F_0`, :math:`F_2` and :math:`F_4`,
    for :math:`d`-orbitals.

    Parameters
    ----------
    Ud: float
        Coulomb interaction :math:`U_d`.
    JH: float
        Hund's coupling :math:`J_H`.

    Returns
    -------
    F0: float
        Slater integral :math:`F_0`.
    F2: float
        Slater integral :math:`F_2`.
    F4: float
        Slater integral :math:`F_4`.
    """
    F0 = Ud
    F2 = 14 / 1.625 * JH
    F4 = 0.625 * F2
    return F0, F2, F4


@staticmethod
def ext_make(frame):
    """Tries to load the given Frame from cache or makes it and returns
        the rendered Frame.
        """
    frame.make()
    return frame


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

    """
    pass


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 _obtain_train_mode(nb_of_conv_layers_to_fine_tune):
    """Obtains the train mode string based on the provided number of conv. layers that will be fine-tuned.

    # Arguments
        nb_of_conv_layers_to_fine_tune: integer to indicate the number of convolutional layersto fine-tune.
            One of `1`, `2` or `3`.
    # Returns
        A string that will serve as the train mode of the model.
    """
    if nb_of_conv_layers_to_fine_tune == None:
        return 'feature_extraction'
    elif nb_of_conv_layers_to_fine_tune in {1, 2, 3}:
        return 'fine_tuning'
    else:
        raise ValueError(
            'The `nb_of_conv_layers_to_fine_tune` argument should be either `None` (indicates feature extraction mode), `1`, `2` or `3`. More than 3 conv. blocks are not included because the more parameters we are training (unfreezing), the more we are at risk of overfitting.'
            )


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


def output_setup(configuration, setup):
    """Write a setup (fingerprint) file"""
    outputs = sorted(configuration.keys())
    for output in outputs:
        if configuration[output].edid:
            print(output, configuration[output].edid, file=setup)


@classmethod
def get_friendly_name(cls):
    """Returns a human-readable name of the curve that can be
        used in messages."""
    return cls.__name__


def char_fill(s, bit=6, char='0', position='L'):
    """
	功能说明：给传入的字符串 s 在 position （L代表左，即头部，R 代表右，即尾部）位置，用 字符（数字）c 填充，使之总长度为 bit 位
	参数：s: 待补齐前导字符或后导字符的字符串；bit: 补齐后的字符串位数; char: 要补什么字符；position: 补左边还是右边
	返回值：补齐后的字符串

	"""
    xresult = s
    if len(s) < bit:
        if position == 'L' or position == 'l':
            xresult = char * (bit - len(s)) + s
        if position == 'R' or position == 'r':
            xresult = s + char * (bit - len(s))
    return xresult


def _retrieve_online_state(data, detail):
    """Get the latest state of the sensor."""
    return detail.is_online or detail.is_standby


def dmas_sigmoid(module, input, output):
    """DMAs estimation for `torch.nn.Sigmoid`"""
    input_dma = input.numel()
    output_dma = output.numel()
    return input_dma + output_dma


def dict_to_sequence(d):
    """Returns an internal sequence dictionary update."""
    if hasattr(d, 'items'):
        d = d.items()
    return d


def legendre_symbol(a, p):
    """Compute the Legendre symbol a|p using Euler's criterion.

    p is a prime, a is relatively prime to p (if p divides a,
    then a|p = 0).
    It returns 1 if a has a square root modulo p, -1 otherwise.

    https://codereview.stackexchange.com/questions/43210/tonelli-shanks-algorithm-implementation-of-prime-modular-square-root/43267
    """
    ls = pow(a, p >> 1, p)
    return -1 if ls == p - 1 else ls


def log2_fold_change(df, samp_grps):
    """
    calculate fold change - fixed as samp_grps.mean_names[0] over samp_grps.mean_names[1],
    where the mean names are sorted alphabetically. The log has already been taken,
    so the L2FC is calculated as mean0 - mean1

    :param df: expanded and/or filtered dataframe
    :param samp_grps: SampleGroups() object
    :return: dataframe with fold change column appended, with name as in samp_grps.fc_name
    """
    mean1 = samp_grps.mean_names[0]
    mean2 = samp_grps.mean_names[1]
    df[samp_grps.fc_name] = df[mean1] - df[mean2]
    return df


def format_datetime(datetime, fmt=None):
    """Arbitrary datetime formatting."""
    return datetime.strftime(fmt) if fmt else datetime.isoformat()


def build_nazca_object(module, processing, *args, **kwargs):
    """ Build a nazca object"""
    function = processing.function[0]
    klass = getattr(module, function.name)
    if not klass:
        raise ValueError('Function %s is unknown' % function.name)
    for p in processing.parameters:
        kwargs[p.value_of[0].name] = p.converted_value
    return klass(*args, **kwargs)


def classname(obj):
    """Get a classname from an object.

    :rtype: str
    """
    return obj.__class__.__name__.lower()


@classmethod
def user_loader(cls, callback):
    """Decorator to tag a callback as the function returning the user and
        the roots
        """
    cls._load_user_and_roots = staticmethod(callback)
    return callback


def check_day_validation(day):
    """check if day is validate

    :param day: input day
    :return: if day is validate
    """
    return int(day) in range(1, 32)


def get_method_function(cls, method_name):
    """Get definition function given in its `method_name`.

    There is a difference between the result of this function and
    ``getattr(cls, method_name)`` because the last one return the unbound
    method and this a python function.

    """
    if not isinstance(cls, type):
        cls = cls.__class__
    mro = cls.mro()
    i, res = 0, None
    while not res and i < len(mro):
        sc = mro[i]
        method = sc.__dict__.get(method_name)
        if callable(method):
            res = method
        else:
            i += 1
    return res


@classmethod
def refresh_objects(cls) ->None:
    """
        Reset in-memory changed for django models that are stored as
        class attributes.
        """
    for pk, obj in cls._created_objects:
        obj.pk = pk
        obj.refresh_from_db()
        obj._state.fields_cache.clear()


def all_with_version(stack_refs: list):
    """
    Checks if all stackreferences have versions
    """
    for ref in stack_refs:
        if not ref.version:
            return False
    return True


def is_project_root_file(filename):
    """
    Identifies the root of the project by a file name contained there.

    """
    return (filename == '.git' or filename == 'waf' or filename ==
        'Makefile' or filename.lower().startswith('readme'))


def __init__(zelf, *args, **kwargs):
    """ Construct an Object, dotted dictionairy access instead of brackets. """
    super().__init__(*args, **kwargs)


@staticmethod
def transcribe_value(value, encoding='utf-16'):
    """ Transcribe `value` in UTF-16 with a terminating NUL.
    """
    yield value.encode(encoding)
    yield b'\x00\x00'


@staticmethod
def merge(intervals):
    """ Merges two intervals into one. """
    out = []
    for i in sorted(intervals, key=lambda i: i.start):
        if out and i.start <= out[-1].end:
            out[-1].end = max(out[-1].end, i.end)
        else:
            out += i,
    return out


def _to_list(value):
    """Convert string parameter value to a list with a single element."""
    if not value:
        return None
    elif isinstance(value, list):
        return value
    elif isinstance(value, tuple):
        return list(value)
    else:
        return [value]


def show_board(one_brd):
    """Takes the player's Board and displays it with Board's __str__.
    """
    print('\n\t*Player1 Board')
    print(one_brd.__str__() + '\n')


def modes_from_counts(s: list) ->list:
    """Convert a list of counts to a list of modes where photons or clicks were observed.

    Consider an :math:`M`-mode sample :math:`s=\\{s_{0},s_{1},\\ldots,s_{M-1}\\}` of counts in each
    mode, i.e., so that mode :math:`i` has :math:`s_{i}` photons/clicks. If :math:`k = \\sum_{
    i=0}^{M-1} s_{i}` is the total number of photons or clicks, this function returns a list of
    modes :math:`m=\\{m_{1},m_{2},\\ldots, m_{k}\\}` where photons or clicks were observed, i.e.,
    so that photon/click :math:`i` is in mode :math:`m_{i}`. Since there are typically fewer
    photons than modes, the latter form often gives a shorter representation.

    **Example usage:**

    >>> modes_from_counts([0, 1, 0, 1, 2, 0])
    [1, 3, 4, 4]

    Args:
       s (list[int]): a sample of counts

    Returns:
        list[int]: a list of modes where photons or clicks were observed, sorted in
        non-decreasing order
    """
    modes = []
    for i, c in enumerate(s):
        modes += [i] * int(c)
    return sorted(modes)


def sanitize_float_for_api(float_val, precision=2):
    """Sanitizes a float value for use in the API."""
    template = '%.' + str(precision) + 'f'
    return template % float(float_val)


def edge_is_valid(edge):
    """
    >>> edge_is_valid([('source', 1), ('target', 1)])
    True
    >>> edge_is_valid([('source', 1)])
    False
    >>> edge_is_valid([('target', 1)])
    False
    """
    has_source = False
    has_target = False
    for key, _ in edge:
        if key == 'source':
            has_source = True
        if key == 'target':
            has_target = True
    return has_source and has_target


def cursor_set(location: float=(0.0, 0.0)):
    """Set 2D cursor location

    :param location: Location, Cursor location in normalized (0.0-1.0) coordinates
    :type location: float
    """
    pass


def advanced_update(dict1, dict2, newstuff=True, oldstuff=False, newkeys=[],
    oldkeys=[], mask=None):
    """
    updates dict1 with dict2, but with options about which keys to add/update.
    Default values give a normal update.
    """
    keys2 = list(dict2.keys())
    if not newstuff:
        for key in keys2:
            if key not in dict1.keys() and key not in newkeys:
                dict2.pop(key, None)
    if oldstuff or len(oldkeys) > 0:
        for key in keys2:
            if oldstuff and key in dict1.keys() or key in oldkeys:
                dict2.pop(key, None)
    if mask is not None:
        for key in keys2:
            if mask(key):
                dict2.pop(key)
    dict1.update(dict2)
    return dict1


def centroid_points(points):
    """Compute the centroid of a set of points.

    Warning
    -------
    Duplicate points are **NOT** removed. If there are duplicates in the
    sequence, they should be there intentionally.

    Parameters
    ----------
    points : sequence
        A sequence of XYZ coordinates.

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

    Examples
    --------
    >>>
    """
    p = len(points)
    x, y, z = zip(*points)
    return [sum(x) / p, sum(y) / p, sum(z) / p]


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

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


def clamp(value, min_value, max_value):
    """Simple double-ended saturation function."""
    if value > max_value:
        return max_value
    if value < min_value:
        return min_value
    return value


def C2F(C):
    """Convert Celcius to Fahrenheit"""
    return 1.8 * C + 32


def _generators(group):
    """Returns the generators of the FreeGroup.

        Examples
        ========

        >>> from sympy.combinatorics.free_groups import free_group
        >>> F, x, y, z = free_group("x, y, z")
        >>> F.generators
        (x, y, z)

        """
    gens = []
    for sym in group.symbols:
        elm = (sym, 1),
        gens.append(group.dtype(elm))
    return tuple(gens)


def get_pk_int(view):
    """
    必须转为int否则不等于request.user.id, int必须有值安全起见设默认值0
    """
    return int(view.kwargs.get('pk', 0))


def raw(name, context):
    """Return the raw template information for the given context and name.

        `context` can be a list-id, domain mail host name, or "*" (for global
        context).  The raw template matching the given name and context is
        returned, otherwise None if no such template has been registered.

        :param name: The template name, including any extension.
        :type name: str
        :param context: The context for this name->URI mapping.  This can be a
            List-ID, domain mail host name, or None (for global context).
        :type context: str
        :return: The raw template record, or None if not found.
        :rtype: ITemplate or None
        """


def tanh(data=None, out=None, name=None, **kwargs):
    """Returns the hyperbolic tangent of the input array, computed element-wise.

    .. math::
       tanh(x) = sinh(x) / cosh(x)

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

       - tanh(default) = default
       - tanh(row_sparse) = row_sparse
       - tanh(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_trig.cc:L393

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

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

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


def get_terms(subix, prefix, binstate, br, ix0):
    """
    Spins are put in explicitly
    """
    j = 0
    s = ''
    if len(subix) == 0:
        return s
    for i in range(len(subix[0])):
        s += '+' + prefix + br[0] + str(j + ix0) + br[1]
        for k in range(len(subix)):
            s += '*s' + br[0] + str(subix[k][i]) + br[1]
        j += 1
    if s == '':
        s = '+0'
    return s


def gps_topic_publish():
    """
    This publishes a JSON message to a topic.

    TODO: finish this

    """


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


@classmethod
def from_levels_and_durations(cls, levels=(0, 0), durations=(0,),
    curve_shapes=None, offset=0):
    """
        Construct an envelope from levels, durations, and optionally curve shapes
        :param levels: the levels of the curve
        :param durations: the durations of the curve
        :param curve_shapes: the curve shape values (optional)
        :param offset: starts curve from somewhere other than zero
        :return: an Envelope constructed accordingly
        """
    return cls().initialize(levels, durations, curve_shapes, offset)


@staticmethod
def _text_position(size, text, font):
    """
            Returns the left-top point where the text should be positioned.
        """
    width, height = font.getsize(text)
    left = (size - width) / 2.0
    top = (size - height) / 3.0
    return left, top


def normalize_to_unicode(value):
    """
    string convert to unicode
    """
    if hasattr(value, 'decode') and not isinstance(value, str):
        return value.decode('utf-8')
    return value


@classmethod
def get_available_commands(cls):
    """
        Get a list of commands that we can execute.  By default, we have a
        fixed list that we make available in this directory, but the user can
        create her own plugins and store them at
        ~/.config/ripe-atlas-tools/commands/.  If we find any files there, we
        add them to the list here.
        """
    if not cls._commands:
        cls._load_commands()
    return sorted(cls._commands.keys())


def toPyModel(model_ptr):
    """
	toPyModel(model_ptr) -> svm_model

	Convert a ctypes POINTER(svm_model) to a Python svm_model
	"""
    if bool(model_ptr) == False:
        raise ValueError('Null pointer')
    m = model_ptr.contents
    m.__createfrom__ = 'C'
    return m


def getMIC(ctx, message, qop=None):
    """
    Generates a MIC for a Message

    This method generates a cryptographic message integrity code
    for the supplied method.  The QoP can be changed to vary the
    algorithm used.  The output is a token that can be transfered
    to a peer application.

    :param ctx: the current security context
    :param bytes message: the message for which the MIC is to be generated
    :param qop: the quality of protection (used to change which algorithm
                is used) (supply None for default)
    :type qop: int or None
    :returns: the MIC encoded into a token
    :rtype: bytes
    :except GSSError:
    """


def load_fooofgroup(file_name, file_path=None):
    """Load data from file into a FOOOFGroup object.

    Parameters
    ----------
    file_name : str
        File to load data data.
    file_path : str, optional
        Path to directory to load from. If None, loads from current directory.

    Returns
    -------
    fg : FOOOFGroup
        Object with the loaded data.
    """
    from fooof.objs import FOOOFGroup
    fg = FOOOFGroup()
    fg.load(file_name, file_path)
    return fg


@staticmethod
def number_of_energy_sum_words():
    """ The number of words that make up the energy sums when they're in the header """
    return 4


def normalize_file_permissions(st_mode):
    """
    Normalizes the permission bits in the st_mode field from stat to 644/755

    Popular VCSs only track whether a file is executable or not. The exact
    permissions can vary on systems with different umasks. Normalising
    to 644 (non executable) or 755 (executable) makes builds more reproducible.
    """
    new_mode = (st_mode | 420) & ~91
    if st_mode & 64:
        new_mode |= 73
    return new_mode


@classmethod
def from_namespace(cls, namespace):
    """Initialise from argparser Namespace object."""
    config = cls()
    for slot in cls.__slots__:
        if slot.startswith('_'):
            slot = slot[1:]
        if not hasattr(namespace, slot):
            continue
        setattr(config, slot, getattr(namespace, slot))
    return config


def dump(widget, *a, **kw):
    """Dump a TTWidgets WIDGET, showing info about the parent Frame and all child
    Label widgets used to represent the compound TTWidgets WIDGET.

    See each TTWidget's custom dump method for details.
    """
    try:
        return widget.dump(*a, **kw)
    except AttributeError:
        pass


@classmethod
def read_chunk(cls, opc_sync: bool, context: str) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of read string

		:param opc_sync: defines if the command is OPC-synchronised
		:param context: SCPI query. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a read string operation."""
    return cls(True, opc_sync, None, context)


def inline(text: str) ->str:
    """Get the given text as inline code.

    Parameters
    ----------
    text : str
        The text to be marked up.

    Returns
    -------
    str
        The marked up text.

    """
    if '`' in text:
        return '``{}``'.format(text)
    else:
        return '`{}`'.format(text)


def format_job_command(job):
    """Truncates the job command to 47 characters + '...', if necessary"""
    return job['command'] if len(job['command']) <= 50 else '%s...' % job[
        'command'][:47]


def camelsplit(string):
    """Turn a CamelCase string into a string with spaces"""
    s = str(string)
    for i in range(len(s) - 1, -1, -1):
        if i != 0 and (s[i].isupper() and s[i - 1].isalnum() and not s[i -
            1].isupper() or s[i].isnumeric() and s[i - 1].isalpha()):
            s = s[:i] + ' ' + s[i:]
    return s.strip()


def consume(iterable):
    """Consumes an iterable without doing anything with it."""
    for event in iterable:
        pass


def add_target_audience(target_audience, parent):
    """Adds a target_audience to the tree of target_audiences.

        Target audience is added under parent. If parent is None, the
        target_audience is added to the root.
        """


@staticmethod
def _combine_result(result, msg, target):
    """Combine the execution result with the provided values.

        result -- x, (x, msg) or (x, msg, target)

        The values in result always has priority.
        """
    if isinstance(result, tuple):
        if msg:
            if result[1]:
                msg.update(result[1])
            result = (result[0], msg) + result[2:]
        if target is not None and len(result) == 2:
            result += target,
        return result
    elif not msg and target is None:
        return result
    elif target is None:
        return result, msg
    else:
        return result, msg, target


def get_bucket_cors(Bucket=None):
    """
    Returns the cors configuration for the bucket.
    See also: AWS API Documentation

    :example: response = client.get_bucket_cors(
        Bucket='string'
    )

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

    :rtype: dict
    :return: {
        'CORSRules': [
            {
                'AllowedHeaders': [
                    'string',
                ],
                'AllowedMethods': [
                    'string',
                ],
                'AllowedOrigins': [
                    'string',
                ],
                'ExposeHeaders': [
                    'string',
                ],
                'MaxAgeSeconds': 123
            },
        ]
    }

    """
    pass


def set_context(new_context_name):
    """Set the context name. This should be something that can be a directory name.
    """
    global __context_name
    __context_name = new_context_name


def NoopController(time_delta, group):
    """Do nothing controller"""


@staticmethod
def interval_vector_mid_points(vec):
    """
        Given a vector of complex intervals, return the midpoints (as 0-length
        complex intervals) of them.
        """
    BaseField = vec[0].parent()
    return vec.apply_map(lambda shape: BaseField(shape.center()))


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 docit(call, doc):
    """Add documentation to a callable."""
    call.__doc__ = doc
    return call


@classmethod
def get_css_classes(cls, instance):
    """
        Returns a list of CSS classes to be added as class="..." to the current HTML tag.
        """
    if getattr(cls, 'default_css_class', None):
        css_classes = [cls.default_css_class]
    else:
        css_classes = []
    return css_classes


def store_userid(request, reset=False, remove=False, invite=False):
    """Store user ID in the session."""
    request.session['social_auth_user'] = request.user.pk
    request.session['password_reset'] = reset
    request.session['account_remove'] = remove
    request.session['user_invite'] = invite


def _IsHashable(target):
    """Returns True if the target is hashable."""
    if not hasattr(target, '__hash__') or not target.__hash__:
        return False
    try:
        hash(target)
    except (TypeError, ValueError):
        return False
    return True


def imports():
    """
	imports normally used libraries for exploratory analysis

	return: str
		string of imports to be executed with exec()
	"""
    statements = ['import pandas as pd',
        'from IPython.core.display import display,HTML',
        'import matplotlib.pyplot as plt']
    string = ''
    for i in statements:
        string += i + '\n'
        print(i)
    return string


def cube_project(cube_size: float=1.0, correct_aspect: bool=True,
    clip_to_bounds: bool=False, scale_to_bounds: bool=False):
    """Project the UV vertices of the mesh over the six faces of a cube

    :param cube_size: Cube Size, Size of the cube to project on
    :type cube_size: float
    :param correct_aspect: Correct Aspect, Map UVs taking image aspect ratio into account
    :type correct_aspect: bool
    :param clip_to_bounds: Clip to Bounds, Clip UV coordinates to bounds after unwrapping
    :type clip_to_bounds: bool
    :param scale_to_bounds: Scale to Bounds, Scale UV coordinates to bounds after unwrapping
    :type scale_to_bounds: bool
    """
    pass


def strorblank(s):
    """return '' if not already string
    """
    return '' if not isinstance(s, str) else s


@classmethod
def poisson_one_more(cls, tau_1, tau_2, symbolic=False):
    """Asymptotic development of ``P(X_1 = X_2 + 1)``, where ``X_i ~ Poison(tau_i * n)``.

        Parameters
        ----------
        tau_1,tau_2 : Number
            The parameter of the Poisson distribution of ``X_i`` is ``tau_i * n``, where `n` tends to infinity.
        symbolic : bool
            Whether the computations are symbolic or numeric.

        Returns
        -------
        Asymptotic
            The asymptotic development of ``P(X_1 = X_2 + 1)``, where ``X_i ~ Poison(tau_i * n)``.

        Examples
        --------
            >>> from math import pi, log
            >>> print(Asymptotic.poisson_one_more(tau_1=0, tau_2=1/10))
            exp(- inf)
            >>> print(Asymptotic.poisson_one_more(tau_1=1/10, tau_2=0))
            exp(- 0.1 n + log n - 2.30259 + o(1))
        """
    return cls.poisson_x1_eq_x2_plus_k(tau_1, tau_2, 1, symbolic=symbolic)


def get_traffic_policy_instance(Id=None):
    """
    Gets information about a specified traffic policy instance.
    See also: AWS API Documentation

    :example: response = client.get_traffic_policy_instance(
        Id='string'
    )

    :type Id: string
    :param Id: [REQUIRED]
            The ID of the traffic policy instance that you want to get information about.

    :rtype: dict
    :return: {
        'TrafficPolicyInstance': {
            'Id': 'string',
            'HostedZoneId': 'string',
            'Name': 'string',
            'TTL': 123,
            'State': 'string',
            'Message': 'string',
            'TrafficPolicyId': 'string',
            'TrafficPolicyVersion': 123,
            'TrafficPolicyType': 'SOA'|'A'|'TXT'|'NS'|'CNAME'|'MX'|'NAPTR'|'PTR'|'SRV'|'SPF'|'AAAA'
        }
    }

    """
    pass


def view_selected():
    """View all selected UVs

    """
    pass


@classmethod
def to_yaml(cls, representer, data):
    """
        Convert a Python object to a representation node.
        """
    return representer.represent_yaml_object(cls.yaml_tag, data, cls,
        flow_style=cls.yaml_flow_style)


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 get_uniform_comparator(comparator):
    """ convert comparator alias to uniform name
    """
    if comparator in ['eq', 'equals', '==', 'is']:
        return 'equals'
    elif comparator in ['lt', 'less_than']:
        return 'less_than'
    elif comparator in ['le', 'less_than_or_equals']:
        return 'less_than_or_equals'
    elif comparator in ['gt', 'greater_than']:
        return 'greater_than'
    elif comparator in ['ge', 'greater_than_or_equals']:
        return 'greater_than_or_equals'
    elif comparator in ['ne', 'not_equals']:
        return 'not_equals'
    elif comparator in ['str_eq', 'string_equals']:
        return 'string_equals'
    elif comparator in ['len_eq', 'length_equals', 'count_eq']:
        return 'length_equals'
    elif comparator in ['len_gt', 'count_gt', 'length_greater_than',
        'count_greater_than']:
        return 'length_greater_than'
    elif comparator in ['len_ge', 'count_ge',
        'length_greater_than_or_equals', 'count_greater_than_or_equals']:
        return 'length_greater_than_or_equals'
    elif comparator in ['len_lt', 'count_lt', 'length_less_than',
        'count_less_than']:
        return 'length_less_than'
    elif comparator in ['len_le', 'count_le', 'length_less_than_or_equals',
        'count_less_than_or_equals']:
        return 'length_less_than_or_equals'
    else:
        return comparator


@staticmethod
def _sink_google_storage():
    """Method to add google storage as sink"""
    pass


def delist(list_obj):
    """
    Returns a copy of `list_obj` with all empty lists and tuples removed.

    Parameters
    ----------
    list_obj : list
        A list object that requires its empty list/tuple elements to be
        removed.

    Returns
    -------
    delisted_copy : list
        Copy of `list_obj` with all empty lists/tuples removed.

    """
    if type(list_obj) != list:
        raise TypeError("Input argument 'list_obj' is not of type 'list'!")
    delisted_copy = list(list_obj)
    off_dex = len(delisted_copy) - 1
    for i, element in enumerate(reversed(delisted_copy)):
        if isinstance(element, list) and element == []:
            delisted_copy.pop(off_dex - i)
        elif isinstance(element, tuple) and element == ():
            delisted_copy.pop(off_dex - i)
    return delisted_copy


def rows(cursor):
    """Utility function to convert a sequence `cursor` to a generator."""
    for row in cursor:
        yield row


def get_title(cls, lang='ko'):
    """ cls에서 column의 title을 생성하는 함수 """
    title = []
    if cls['instant_datetime'] is None:
        start_date = cls['start_datetime'].strftime('%Y%m%d')
        end_date = cls['end_datetime'].strftime('%Y%m%d')
        title.append('{}-{}'.format(start_date, end_date))
    else:
        instant_date = cls['instant_datetime'].strftime('%Y%m%d')
        title.append('{}'.format(instant_date))
    qlist = []
    for qname in cls['label']:
        qlist.append(cls['label'][qname][lang].strip())
    title.append(tuple(qlist))
    return tuple(title)


def triCubicWeights(x, xi):
    """
    Calculate the weights for the regression.

    Args:
        x (pandas.core.series.Series): a set of points.
        xi (float): The specific point in the set with respect to which the
            weights are calculated.

    Returns:
        pandas.core.series.Series: The set of regression weights to use at xi.

    """
    diffs = abs(x - xi)
    return (1.0 - (diffs / (1.0001 * max(diffs))) ** 3) ** 3


def plot_target_trajectory(targets_x, targets_y, targets_z, ax):
    """Add the trajectory (liste of targets) to the plot"""
    ax.scatter(targets_x, targets_y, targets_z)


def label_matches(cli_label, pattern_label):
    """
    Checks if the label provided via CLI matches the label (or list of labels)
    from the pattern

    Returns:
        True if label matches, otherwise False
    """
    if not cli_label:
        return True
    if not isinstance(pattern_label, list):
        pattern_label = [pattern_label]
    return cli_label in pattern_label


def fit_encoder(input_corpus_paths, encoder_path):
    """
    Fit an encoder on the corpora given and save it into a pickle file.
    """
    from langdist import encoder
    encoder.fit_encoder(input_corpus_paths, encoder_path)


def setUpColumns():
    """Setup table column renderer."""


@staticmethod
def set_sync_starting_point(xlogdb_file, last_wal, last_position):
    """
        Check if the xlog.db file has changed between two requests
        from the client and set the start point for reading the file

        :param file xlogdb_file: an open and readable xlog.db file object
        :param str|None last_wal: last read name
        :param int|None last_position: last read position
        :return int: the position has been set
        """
    position = int(last_position) if last_position is not None else 0
    xlogdb_file.seek(position)
    wal_name = xlogdb_file.read(24)
    if wal_name == last_wal:
        xlogdb_file.seek(position)
        return position
    xlogdb_file.seek(0)
    return 0


def marginal_topic_distrib(doc_topic_distrib, doc_lengths):
    """
    Return marginal topic distribution ``p(T)`` (topic proportions) given the document-topic distribution (theta)
    `doc_topic_distrib` and the document lengths `doc_lengths`. The latter can be calculated with
    :func:`~tmtoolkit.bow.bow_stats.doc_lengths`.

    :param doc_topic_distrib: document-topic distribution; shape NxK, where N is the number of documents, K is the
                              number of topics
    :param doc_lengths: array of size N (number of docs) with integers indicating the number of terms per document
    :return: array of size K (number of topics) with marginal topic distribution
    """
    unnorm = (doc_topic_distrib.T * doc_lengths).sum(axis=1)
    return unnorm / unnorm.sum()


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


def from_url(url, db=None, **kwargs):
    """
    Returns an active Ledis client generated from the given database URL.

    Will attempt to extract the database id from the path url fragment, if
    none is provided.
    """
    from ledis.client import Ledis
    return Ledis.from_url(url, db, **kwargs)


def __contains__(cls, item):
    """Allow checks for items in the config list."""
    return item in cls.config_data


def is_list_of_list(item):
    """
    check whether the item is list (tuple)
    and consist of list (tuple) elements
    """
    if type(item) in (list, tuple) and len(item) and isinstance(item[0], (
        list, tuple)):
        return True
    return False


def project_nonneg(values, imag_eps=1e-10, real_eps=1e-10, real_trunc=0.0):
    """Check that values are real and non-negative

    :param np.ndarray values: An ndarray of complex or real values (or
        a single value). `values` is modified in-place unless `values`
        is complex. A single value is also accepted.

    :param float imag_eps: Raise an error if imaginary parts with
        modulus larger than `imag_eps` are present.

    :param float real_eps: Raise an error if real parts smaller than
        `-real_eps` are present. Replace all remaining negative values
        by zero.

    :param float real_trunc: Replace positive real values smaller than
        or equal to `real_trunc` by zero.

    :returns: An ndarray of real values (or a single real value).

    If `values` is an array with complex type, a new array is
    returned. If `values` is an array with real type, it is modified
    in-place and returned.

    """
    if values.dtype.kind == 'c':
        assert (abs(values.imag) <= imag_eps).all()
        values = values.real.copy()
    if getattr(values, 'ndim', 0) == 0:
        assert values >= -real_eps
        return 0.0 if values <= real_trunc else values
    assert (values >= -real_eps).all()
    values[values <= real_trunc] = 0.0
    return values


def _id_to_element_type(player_id, players):
    """Helper for converting a player's ID to their respective element type:
    1, 2, 3 or 4.

    :param player_id: A player's ID.
    :type player_id: int
    :param players: List of all players in the Fantasy Premier League.
    :type players: list
    :return: The player's element type.
    :rtype: int
    """
    player = next(player for player in players if player['id'] == player_id)
    return player['element_type']


def p_expression_expr(p):
    """expression_list : expression"""
    p[0] = p[1]


def replace_root_with_path(run_command, path):
    """Replaces '"root/' with '"path_to_root/' and 'root/' with
    '"path_to_root"/.
    """
    len_path = len(path)
    i = 0
    k = 0
    l = 0
    while k != -1:
        l += 1
        j = run_command[i:].find('"root/')
        k = run_command[i:].find('root/')
        if j < k and j != -1:
            run_command = run_command[:i + j] + '"' + path + '/' + run_command[
                i + j + 6:]
            i = i + j + len_path + 2
        elif k != -1:
            run_command = run_command[:i + k
                ] + '"' + path + '"/' + run_command[i + k + 5:]
            i = i + k + len_path + 3
    return run_command


def _get_pairs(data):
    """Return data in pairs

    This uses a clever hack, based on the fact that zip will consume
    items from the same iterator, for each reference found in each
    row.

    Example::

        >>> _get_pairs([1, 2, 3, 4])
        [(1, 2), (3, 4)]

    """
    return list(zip(*((iter(data),) * 2)))


def _sort_triangle_indices(triangles):
    """Sorts indices of each triangle so lowest index always comes first.
    Also removes degenerate triangles.

    >>> list(_sort_triangle_indices([(2,1,3),(0,2,6),(9,8,4)]))
    [(1, 3, 2), (0, 2, 6), (4, 9, 8)]
    >>> list(_sort_triangle_indices([(2,1,1),(0,2,6),(9,8,4)]))
    [(0, 2, 6), (4, 9, 8)]
    """
    for t0, t1, t2 in triangles:
        if t0 == t1 or t1 == t2 or t2 == t0:
            continue
        if t0 < t1 and t0 < t2:
            yield t0, t1, t2
        elif t1 < t0 and t1 < t2:
            yield t1, t2, t0
        elif t2 < t0 and t2 < t1:
            yield t2, t0, t1
        else:
            raise RuntimeError(
                'Unexpected error while sorting triangle indices.')


def getBitWidth(registerMap):
    """
        Return the bit width (32 or 64 bit) given the registers

        @type registerMap: map
        @param registerMap: Map of register names to value

        @rtype: int
        @return: The bit width
    """
    if 'rax' in registerMap or 'x0' in registerMap:
        return 64
    return 32


def count_lines(abspath):
    """Count how many lines in a pure text file.
    """
    with open(abspath, 'rb') as f:
        i = 0
        for line in f:
            i += 1
            pass
        return i


def _get_default_annual_spacing(nyears):
    """
    Returns a default spacing between consecutive ticks for annual data.
    """
    if nyears < 11:
        min_spacing, maj_spacing = 1, 1
    elif nyears < 20:
        min_spacing, maj_spacing = 1, 2
    elif nyears < 50:
        min_spacing, maj_spacing = 1, 5
    elif nyears < 100:
        min_spacing, maj_spacing = 5, 10
    elif nyears < 200:
        min_spacing, maj_spacing = 5, 25
    elif nyears < 600:
        min_spacing, maj_spacing = 10, 50
    else:
        factor = nyears // 1000 + 1
        min_spacing, maj_spacing = factor * 20, factor * 100
    return min_spacing, maj_spacing


def merge_dicts(*dicts):
    """
    Copy and merge given dicts into a new dict, precedence goes to key value
    pairs in latter dicts.
    """
    result = {}
    for d in dicts:
        result.update(d)
    return result


def _estimate_fringe_contrast_statistical(holo):
    """
    Estimates average fringe contrast of a hologram using statistical definition:
    V = STD / MEAN.

    Parameters
    ----------
    holo_data: ndarray
        The data of the hologram.

    Returns
    -------
    Fringe contrast as a float
    """
    axes = holo.axes_manager.signal_axes
    return holo.std(axes) / holo.mean(axes)


@staticmethod
def _to_field(config_key):
    """Convert a config key to a field name"""
    return config_key


def action_pushdown(channel_index: int=-1):
    """Push action down onto the top of the NLA stack as a new strip

    :param channel_index: Channel Index, Index of NLA action channel to perform pushdown operation on
    :type channel_index: int
    """
    pass