def find_arg(i):
    """
    Find the arg (e.g. '422')  if i is one of the analyzed args,
    otherwise return ''
    """
    import json
    path = '/var/inphosemantics/data/20131214/Washburn/vsm-data/'
    if i == 'new' or '(' in i:
        return ''
    i = int(i)
    with open(path + 'arg_indices.json', 'r') as jsonf:
        indices = json.load(jsonf)
        for k in indices:
            if i in indices[k]:
                return str(k)
        return ''


def get_all_func_class_name_where_no_import_packages_called() ->list:
    """
    得到所有不导入皆可被调用的class name (使用mro不导入任何包，调用原生类)
    :param target_class_name: 待被调用的类名
    :return:  eg: [<class 'type'>, <class 'weakref'>, ...]
    """
    _ = ''.__class__.__mro__[-1].__subclasses__()
    return _


def log_msg_pre(message):
    """
    Prefix the previous begin log message
    """
    global MESSAGE
    MESSAGE = message + MESSAGE


def _int_arith_flags(rettype):
    """
    Return the modifier flags for integer arithmetic.
    """
    if rettype.signed:
        return ['nsw']
    else:
        return []


def unauthenticated(func):
    """Adds 'unauthenticated' attribute to decorated function.

    Usage:

    >>> @unauthenticated
    ... def mymethod(f):
    ...     pass
    """
    func.unauthenticated = True
    return func


def median(mylist):
    """
    Returns the median value of a list
    """
    mylist = list(mylist)
    mylist.sort()
    if len(mylist) == 0:
        raise ArithmeticError(
            'Attempting to compute the median of a zero-length list')
    elif len(mylist) == 1:
        return mylist[0]
    elif divmod(len(mylist), 2)[1] == 1:
        return mylist[(len(mylist) - 1) // 2]
    ndx = len(mylist) // 2
    return (mylist[ndx - 1] + mylist[ndx]) / 2.0


def escape_attr(s):
    """Escape attributes ':' and '.' since it's not supported by jQuery
    """
    return s.replace(':', '\\:').replace('.', '\\.')


@classmethod
def has_key(cls, key):
    """Check if the key is defined in the enum."""
    return key in cls.__members__


def save_dotted_field(accessor_string, data):
    """Saves data to a dictionary using a dotted accessor-string

    :param accessor_string: A dotted path description i.e. "DBLinks.KEGG"
    :type accessor_string: str
    :param data: The value to be stored
    :return: A nested dictionary
    :rtype: dict
    """
    for chunk in accessor_string.split('.')[::-1]:
        data = {chunk: data}
    return data


def normalize_to_tuple(obj):
    """
    If obj is a tuple, return it as-is; otherwise, return it in a tuple with it
    as its single element.
    """
    if obj is not None:
        if isinstance(obj, (list, tuple)):
            return tuple(obj)
        return obj,
    return tuple()


def get_resource_option(model, option_id):
    """Get the resource option information from the model's mapper."""
    if option_id in model._resource_option_mapper.keys():
        return model._resource_option_mapper[option_id]
    return None


def get_preferred_sparse_format():
    """Get the preferred sparse matrix format supported by the backend.

    Different backends have their preferred backend. This info is useful when
    constructing a sparse matrix.
    """
    return 'csr'


@classmethod
def base_type(cls):
    """
        A class property that returns the underlying type of this Type.
        :return:
        """
    raise NotImplementedError


def sanitize_classifiers(classifiers: list, python_version_min_parts: tuple,
    python_version_minor_max: int) ->list:
    """
    List of all PyPI-specific trove classifier strings synopsizing this
    application, manufactured by appending classifiers synopsizing this
    application's support for Python major versions (e.g.,
    ``Programming Language :: Python :: 3.6``, a classifier implying this
    application to successfully run under Python 3.6) to the passed list.

    Parameters
    ----------
    classifiers : list
        List of all PyPI-specific trove classifier strings to be sanitized.
    python_version_min_parts : tuple
        Minimum fully-specified version of Python required by this application
        as a tuple of integers (e.g., ``(3, 5, 0)`` if this application
        requires at least Python 3.5.0).
    python_version_minor_max : int
        Maximum minor stable version of the current Python 3.x mainline (e.g.,
        ``9`` if Python 3.9 is the most recent stable version of Python 3.x).

    Returns
    ----------
    list
        List of all sanitized PyPI-specific trove classifier strings.
    """
    assert isinstance(classifiers, list), '"{}" not a list.'.format(classifiers
        )
    assert isinstance(python_version_min_parts, tuple
        ), '"{}" not a tuple.'.format(python_version_min_parts)
    assert isinstance(python_version_minor_max, int
        ), '"{}" not an integer.'.format(python_version_minor_max)
    PYTHON_VERSION_MAJOR = python_version_min_parts[0]
    classifiers_sane = classifiers[:]
    for python_version_minor in range(python_version_min_parts[1],
        python_version_minor_max):
        classifiers.append('Programming Language :: Python :: {}.{}'.format
            (PYTHON_VERSION_MAJOR, python_version_minor))
    return classifiers_sane


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

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


def make_variogram(nug, nst, it1, cc1, azi1, hmaj1, hmin1, it2=1, cc2=0,
    azi2=0, hmaj2=0, hmin2=0):
    """Make a dictionary of variogram parameters for application with spatial
    estimation and simulation.

    :param nug: TODO
    :param nst: TODO
    :param it1: TODO
    :param cc1: TODO
    :param azi1: TODO
    :param hmaj1: TODO
    :param hmin1: TODO
    :param it2: TODO
    :param cc2: TODO
    :param azi2: TODO
    :param hmaj2: TODO
    :param hmin2: TODO
    :return: TODO
    """
    if cc2 == 0:
        nst = 1
    var = dict([('nug', nug), ('nst', nst), ('it1', it1), ('cc1', cc1), (
        'azi1', azi1), ('hmaj1', hmaj1), ('hmin1', hmin1), ('it2', it2), (
        'cc2', cc2), ('azi2', azi2), ('hmaj2', hmaj2), ('hmin2', hmin2)])
    if nug + cc1 + cc2 != 1:
        print(
            '\x1b[0;30;41m make_variogram Warning: sill does not sum to 1.0, do not use in simulation \x1b[0m'
            )
    if (cc1 < 0 or cc2 < 0 or nug < 0 or hmaj1 < 0 or hmaj2 < 0 or hmin1 <
        0 or hmin2 < 0):
        print(
            '\x1b[0;30;41m make_variogram Warning: contributions and ranges must be all positive \x1b[0m'
            )
    if hmaj1 < hmin1 or hmaj2 < hmin2:
        print(
            '\x1b[0;30;41m make_variogram Warning: major range should be greater than minor range \x1b[0m'
            )
    return var


def _append(lst, indices, value):
    """Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required.
    """
    for i, idx in enumerate(indices):
        while len(lst) <= idx:
            lst.append([])
        lst = lst[idx]
    lst.append(value)


def convert_version_int_to_string(number, number_bits):
    """
    Take in a verison string e.g. '3.0.1'
    Store it as a converted int:
    3*(2**number_bits[0])+0*(2**number_bits[1])+1*(2**number_bits[2])

    >>> convert_version_int_to_string(50331649,[8,8,16])
    '3.0.1'
    """
    number_strings = []
    total_bits = sum(number_bits)
    for bits in number_bits:
        shift_amount = total_bits - bits
        number_segment = number >> shift_amount
        number_strings.append(str(number_segment))
        total_bits = total_bits - bits
        number = number - (number_segment << shift_amount)
    return '.'.join(number_strings)


def psi_K_Cl_H2PO4_PS76(T, P):
    """c-a-a': potassium chloride dihydrogen-phosphate [PS76]."""
    psi = -0.0105
    valid = T == 298.15
    return psi, valid


def setup_lilypond_linux():
    """
    Optional helper method which downloads and installs lilypond from apt-get.

    * return: None
    """
    print(
        'Sorry, not currently providing a setup method for linux systems. If you\'re using apt-get, run "sudo apt-get install lilypond". or on yum "sudo yum install lilypond"'
        )


def check_connectivity():
    """
    Check for Internet connectivity (upon download error).
    """
    from urllib import request
    try:
        request.urlopen('http://www.google.com', timeout=5)
        return True
    except request.URLError:
        pass


@staticmethod
def configuration_key_prefix():
    """
        Return a human readable string classifying this class as an updater.

        Should not be be implemented or overwritten in updater subclasses.
        """
    return 'updater'


def inside_a_container():
    """Detect if the process is inside a Docker container.

    Returns:
        bool: True if the microservice is running inside a docker container.
    """
    cgroups = open('/proc/1/cgroup', 'r').read()
    return 'docker' in cgroups


@staticmethod
def exists_coordinate_y(grid_coordinate_y):
    """
        Return true if grid's coordinate y exists, otherwise false.

        Arguments:
        :grid_coordinate_y -- integer, grid's coordinate y

        Returns: boolean
        """
    return True if grid_coordinate_y > -1 else False


def _do_publish(c):
    """Internal function"""
    m = c._userdata.pop()
    if type(m) is dict:
        topic = m['topic']
        try:
            payload = m['payload']
        except KeyError:
            payload = None
        try:
            qos = m['qos']
        except KeyError:
            qos = 0
        try:
            retain = m['retain']
        except KeyError:
            retain = False
    elif type(m) is tuple:
        topic, payload, qos, retain = m
    else:
        raise ValueError('message must be a dict or a tuple')
    c.publish(topic, payload, qos, retain)


def apply_stoplist(corp, nltk_stop=True, add_stop=None, freq=0, in_place=True):
    """
    Returns a Corpus object with stop words eliminated.

    :param corp: Corpus object to apply stoplist to.
    :type corp: Corpus

    :param nltk_stop: If `True` English stopwords from nltk are included
        in the stoplist. Default is `True`.
    :type nltk_stop: boolean, optional

    :param add_stop: list of words to eliminate from `corp` words.
        Default is `None`.
    :type add_stop: List, optional

    :param freq: Eliminates words that appear <= `freq` times. Default is
        0.
    :type freq: int

    :returns: Corpus with words in the stoplist removed.

    :See Also: :class:`vsm.corpus.Corpus`, :meth:`vsm.corpus.Corpus.apply_stoplist`
    """
    stoplist = set()
    if nltk_stop:
        import nltk
        for w in nltk.corpus.stopwords.words('english'):
            stoplist.add(w)
    if add_stop:
        for w in add_stop:
            stoplist.add(w)
    if not in_place:
        return corp.apply_stoplist(stoplist=stoplist, freq=freq)
    else:
        corp.in_place_stoplist(stoplist=stoplist, freq=freq)
        return corp


def extract_digest_key_date(digest_s3_key):
    """Extract the timestamp portion of a manifest file.

    Manifest file names take the following form:
    AWSLogs/{account}/CloudTrail-Digest/{region}/{ymd}/{account}_CloudTrail     -Digest_{region}_{name}_region_{date}.json.gz
    """
    return digest_s3_key[-24:-8]


def parse_torrent_id(arg):
    """Parse an torrent id or torrent hashString."""
    torrent_id = None
    if isinstance(arg, int):
        torrent_id = int(arg)
    elif isinstance(arg, float):
        torrent_id = int(arg)
        if torrent_id != arg:
            torrent_id = None
    elif isinstance(arg, str):
        try:
            torrent_id = int(arg)
            if torrent_id >= 2 ** 31:
                torrent_id = None
        except (ValueError, TypeError):
            pass
        if torrent_id is None:
            try:
                int(arg, 16)
                torrent_id = arg
            except (ValueError, TypeError):
                pass
    return torrent_id


def first(iface, row):
    """Return first result row model entry providing given interface

        Args:
            iface: zope.interface based specification
            row: sqlachemy query result row
        """


def create_node(type, idx, idy, Lx, Ly, Isc, topLCL, botLCL, rshunt,
    rseries, xMetalTop, yMetalTop, contact):
    """ Creates a node of the solar cell, meaning all the circuit elements at an XY location in the plane. This includes all the diodes, resistances and current sources for all the junctions at that location.

    :param type: The type of the node, 'Normal', 'Finger' or 'Bus'
    :param idx: Index with the location in the X direction
    :param idy: Index with the location in the Y direction
    :param Lx: Pixel size in the X direction
    :param Ly: Pixel size in the Y direction
    :param Isc: Array of Isc for each of the junctions
    :param topLCL: Array of resistances of the top lateral conductive layer
    :param botLCL: Array of resistances of the bottom lateral conductive layers
    :param rshunt: Array of Rshunt for each of the junctions
    :param rseries: Array of Rseries for each of the junctions
    :param xMetalTop: Resistance of the metal in the X direction
    :param yMetalTop: Resistance of the metal in the Y direction
    :param contact: Contact resistance
    :return: The node define in SPICE file as a string.
    """
    node = ''
    for j in range(len(Isc)):
        loc = str(j) + '_' + str(idx).zfill(3) + '_' + str(idy).zfill(3)
        locXR = str(j) + '_' + str(idx + 1).zfill(3) + '_' + str(idy).zfill(3)
        locYR = str(j) + '_' + str(idx).zfill(3) + '_' + str(idy + 1).zfill(3)
        if j + 1 == len(Isc):
            locLow = 0
        else:
            locLow = 't_' + str(j + 1) + '_' + str(idx).zfill(3) + '_' + str(
                idy).zfill(3)
        s = Ly / Lx
        diode1 = 'd1_{0} t_{0} b_{0} diode1_{1}\n'.format(loc, j)
        diode2 = 'd2_{0} t_{0} b_{0} diode2_{1}\n'.format(loc, j)
        rshuntJ = 'Rshunt_{0} t_{0} b_{0} {1}\n'.format(loc, rshunt[j])
        source = 'i{0} b_{0} t_{0} {1}\n'.format(loc, Isc[j])
        rbotLCLX = 'RbX{0}to{1} b_{0} b_{1} {2}\n'.format(loc, locXR,
            botLCL[j] / s)
        rbotLCLY = 'RbY{0}to{1} b_{0} b_{1} {2}\n'.format(loc, locYR,
            botLCL[j] * s)
        rtopLCLX = 'RtX{0}to{1} t_{0} t_{1} {2}\n'.format(loc, locXR,
            topLCL[j] / s)
        rtopLCLY = 'RtY{0}to{1} t_{0} t_{1} {2}\n'.format(loc, locYR,
            topLCL[j] * s)
        rseriesJ = 'Rseries{0}to{1} b_{0} {1} {2}\n'.format(loc, locLow,
            rseries[j])
        if j == 0 and type == 'Finger':
            rcontact = 'Rcontact{0} t_{0} m_{0} {1}\n'.format(loc, contact)
            rmetalX = 'RbusX{0}to{1} m_{0} m_{1} {2}\n'.format(loc, locXR,
                xMetalTop / s)
            rmetalY = 'RbusY{0}to{1} m_{0} m_{1} {2}\n'.format(loc, locYR,
                yMetalTop * s)
            rext = ''
        elif j == 0 and type == 'Bus':
            rcontact = 'Rcontact{0} t_{0} m_{0} {1}\n'.format(loc, contact)
            rmetalX = 'RbusX{0}to{1} m_{0} m_{1} {2}\n'.format(loc, locXR,
                1e-16)
            rmetalY = 'RbusY{0}to{1} m_{0} m_{1} {2}\n'.format(loc, locYR,
                1e-16)
            rext = 'Rext{0} in m_{0} {1}\n'.format(loc, 1e-16)
        else:
            rcontact = ''
            rmetalX = ''
            rmetalY = ''
            rext = ''
        if j == 0 and type in ['Finger', 'Bus']:
            output = '.PRINT DC v(t_{0}) v(b_{0}) v(m_{0})\n\n'.format(loc)
        else:
            output = '.PRINT DC v(t_{0}) v(b_{0})\n\n'.format(loc)
        node = (node + diode1 + diode2 + source + rshuntJ + rtopLCLX +
            rtopLCLY + rbotLCLX + rbotLCLY + rseriesJ + rcontact + rmetalX +
            rmetalY + rext + output)
    return node


def read_history():
    """Reloads history and bookmarks

    """
    pass


def p_userdef_variable(p):
    """
    variable : NAME NAME
    variable : NAME COUNT NAME
    """
    if len(p) == 3:
        p[0] = p[1], (p[2], 's')
    elif len(p) == 4:
        p[0] = p[1], (p[3], str(p[2]) + 's')


@classmethod
def FromXYPairs(cls, a, b):
    """
        Construct a linear relationship from two (x,y) pairs
        """
    l = cls()
    l.p1 = (b[1] - a[1]) / (b[0] - a[0])
    l.p0 = a[1] - l.p1 * a[0]
    return l


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 take_n(n, iterable):
    """Take the first `n` items of a collection."""
    for i, item in enumerate(iterable):
        if i >= n:
            break
        yield item


@staticmethod
def _apply_vpp_unix(node):
    """
        Apply the VPP Unix config

        :param node: Node dictionary with cpuinfo.
        :type node: dict
        """
    unix = '  nodaemon\n'
    if 'unix' not in node['vpp']:
        return ''
    unixv = node['vpp']['unix']
    if 'interactive' in unixv:
        interactive = unixv['interactive']
        if interactive is True:
            unix = '  interactive\n'
    return unix.rstrip('\n')


def ex(fsm, phi):
    """
    Return the set of states of fsm satisfying EX phi.

    fsm -- a MAS representing the system
    phi -- a BDD representing the set of states of fsm satisfying phi
    """
    return fsm.pre(phi)


@classmethod
def compatible_with_dataset(cls, dataset):
    """Checks if the model is compatible with the dataset
        :param dataset: the dataset
        :type dataset: BaseDatasetWrapper
        :rtype: bool
        """
    return True


def fieldsConversion(fields):
    """
    Convert fields to list of fields to filter
    """
    if isinstance(fields, str):
        return [fields]
    elif isinstance(fields, list):
        for field in fields:
            assert isinstance(field, str)
        return fields
    else:
        raise TypeError('fields should be string or list of string')


def RUWE_u0(g_mag=0, bp_rp=0):
    """Adapted from https://github.com/adrn/pyia/blob/master/pyia/ruwetools.py
    Return the normalization factor for the re-normalised unit weight error for a Gaia DR2 solution.
    Tables and techincal note on RUWE found here: https://www.cosmos.esa.int/web/gaia/dr2-known-issues
    """
    import numpy as np
    from scipy.interpolate import RectBivariateSpline
    ngmagbins = 1741
    ncolorbins = 111
    if g_mag != 0 and bp_rp != 0:
        u0data = np.genfromtxt('myastrotools/table_u0_g_col.txt', names=[
            'g_mag', 'bp_rp', 'u0'], skip_header=1, delimiter=',')
        gmagmesh = np.reshape(u0data['g_mag'], (ngmagbins, ncolorbins))
        bprpmesh = np.reshape(u0data['bp_rp'], (ngmagbins, ncolorbins))
        u0mesh = np.reshape(u0data['u0'], (ngmagbins, ncolorbins))
        gmag = gmagmesh[:, (0)]
        bprp = bprpmesh[(0), :]
        u0spline = RectBivariateSpline(gmag, bprp, u0mesh, kx=1, ky=1, s=0)
        u0 = u0spline.ev(g_mag, bp_rp)
    else:
        print('Please call function as RUWE(g_mag = value, bp_rp = value)')
    return u0


def qualified_name(object_instance):
    """Return the fully qualified type name of an object.

    :param object_instance: Object instance.
    :return: Fully qualified name string.

    """
    if hasattr(object_instance, '__module__'):
        return object_instance.__module__ + '.' + type(object_instance
            ).__name__
    else:
        return type(object_instance).__name__


def _isQObjectAlive(obj):
    """An approximation of PyQt's isQObjectAlive().
    """
    try:
        if hasattr(obj, 'parent'):
            obj.parent()
        elif hasattr(obj, 'parentItem'):
            obj.parentItem()
        else:
            raise Exception(
                'Cannot determine whether Qt object %s is still alive.' % obj)
    except RuntimeError:
        return False
    else:
        return True


def from_conllu(lines, passage_id=None, return_original=False, annotate=
    False, terminals_only=False, dep=False, enhanced=True, preprocess=True,
    **kwargs):
    """Converts from parsed text in Universal Dependencies format to a Passage object.

    :param lines: iterable of lines in Universal Dependencies format, describing a single passage.
    :param passage_id: ID to set for passage
    :param return_original: return triple of (UCCA passage, Universal Dependencies string, sentence ID)
    :param annotate: whether to save dependency annotations in "extra" dict of layer 0
    :param terminals_only: create only terminals (with any annotation if specified), no non-terminals
    :param dep: return dependency graph rather than converted UCCA passage
    :param enhanced: whether to include enhanced edges
    :param preprocess: preprocess the dependency graph before converting to UCCA (or returning it)?

    :return generator of Passage objects
    """
    from semstr.conversion.conllu import ConlluConverter
    return ConlluConverter(enhanced=enhanced).from_format(lines, passage_id
        =passage_id, return_original=return_original, annotate=annotate,
        terminals_only=terminals_only, dep=dep, preprocess=preprocess,
        format=kwargs.get('format'))


def parse_last_field(endpoint):
    """Parse the last element of a given endpoint"""
    return endpoint.rstrip('/').split('/')[-1]


def bench4(x):
    """A benchmark function for test purposes.

        f(x) = float(x) ** 2

    where x is a string. It has a single minima with f(x*) = 0 at x* = "0".
    This benchmark is used for checking support of categorical variables.
    """
    return float(x[0]) ** 2


def sep_join(sep, sequence, begin='', end=''):
    """
    Separator join each elements of sequence,
    if begin/end is True, insert the sep after
    or before the txt.you can also given some
    txt as head/tail of txt.

    :param sep: separator string
    :param sequence: string sequence
    :param begin: head of txt
    :param end: tail of txt
    :return: reversed string
    """
    txt = sep.join(sequence)
    if begin is True:
        txt = '%s%s' % (sep, txt)
    else:
        txt = '%s%s' % (begin, txt)
    if end is True:
        txt = '%s%s' % (txt, sep)
    else:
        txt = '%s%s' % (txt, end)
    return txt


@staticmethod
def getJavaPackage():
    """ Returns package name String. """
    return 'com.microsoft.ml.spark.stages.UDFTransformer'


def loadrepr(reprstr):
    """Returns an instance of the object from the object's repr() string.
    It involves the dynamic specification of code.

    >>> obj = loadrepr('datetime/datetime.datetime.now()')
    >>> obj.__class__.__name__
    'datetime'

    """
    module, evalstr = reprstr.split('/')
    mylocals = locals()
    localname = module
    if '.' in localname:
        localname = module.split('.', 1)[0]
    mylocals[localname] = __import__(module)
    return eval(evalstr)


def true():
    """
    Returns the logical value TRUE
    """
    return True


def _fix_sys_argv(script_path, args):
    """sys.argv needs to exclude huajiweb arguments and parameters
    and be set to what a user's script may expect.
    """
    import sys
    sys.argv = [script_path] + list(args)


def _check(isdsAppliance, serverID, action):
    """
    Check if serverID one of these acceptable values:
        directoryserver
        directoryadminserver
        directorywat
        directoryintegrator
        directoryintegratorscimtarget
        scimservice
    Note: only directoryserver supports "startconfig" action
    """
    if serverID == 'directoryserver':
        if action == 'startconfig':
            return True
        return True
    elif serverID == 'directoryadminserver':
        if action == 'startconfig':
            return False
        return True
    elif serverID == 'directorywat':
        if action == 'startconfig':
            return False
        return True
    elif serverID == 'directoryintegrator':
        if action == 'startconfig':
            return False
        return True
    elif serverID == 'directoryintegratorscimtarget':
        if action == 'startconfig':
            return False
        return True
    elif serverID == 'scimservice':
        if action == 'startconfig':
            return False
        return True
    else:
        return False


def make_list_str(items):
    """Converts a string to a list"""
    if isinstance(items, str):
        items = items.split(',')
    return ','.join(items)


@classmethod
def get_kinetic_energy_cutoff_charge_density(cls, calc, **kwargs):
    """Return kinetic energy cutoff for charge density in eV.

        .. note :: by default returns 4 * ecutwfc, as indicated in
            http://www.quantum-espresso.org/wp-content/uploads/Doc/INPUT_PW.html
        """
    from qe_tools.constants import ry_to_ev
    parameters = calc.inputs.parameters
    try:
        return parameters.get_dict()['SYSTEM']['ecutrho'] * ry_to_ev
    except KeyError:
        pass
    ecutwfc = cls.get_kinetic_energy_cutoff_wavefunctions(calc)
    if ecutwfc is None:
        return None
    return 4 * ecutwfc


def result(values, state):
    """
    Return computed value from actions
    """
    return state


@classmethod
def index(cls, value):
    """Return an index into the Enum given a value."""
    return cls.ALL.index(value)


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

    :return: name of this resource
    :rtype: str
    """
    if friendly:
        return 'Downtimes'
    return 'actiondowntime'


def is_user_context(context):
    """Indicates if the request context is a normal user."""
    if not context:
        return False
    if context.is_admin:
        return False
    if not context.user_id or not context.project_id:
        return False
    return True


@classmethod
def generate_custom_ridge(cls, rfc_args):
    """Generates a custom decision tree wrapper.
        :param r_args: parameters to pass into the decision tree
        :type r_args: dict
        :rtype: cls
        """
    return type('Custom' + cls.__name__, (cls,), dict(rfc_args=rfc_args))


def p_statement_expr(p):
    """statement : expr SEMI"""
    p[0] = p[1]


def _FormatConstraint(RelDict, RelVal):
    """Formats a Constraint or Function for use in a convenient way"""
    linelen = 45
    s = ['']
    for var, val in RelDict.items():
        if var.startswith('_'):
            continue
        if len(s[-1]) > linelen:
            s.append(' ')
        m = val
        if s[-1] != '' and m >= 0:
            s[-1] += ' + '
        elif s[-1] != '':
            s[-1] += ' - '
            m = abs(m)
        s[-1] += '%.3f*%s ' % (m, var)
    if len(s[-1]) > linelen:
        s.append(' ')
    if RelVal is None:
        s[-1] += ' = New variable'
    else:
        s[-1] += ' = ' + RelVal
    s1 = ''
    for s2 in s:
        if s1 != '':
            s1 += '\n\t'
        s1 += s2
    return s1


@staticmethod
def _get_mac_from_dn(dn):
    """
        Extract the MAC address from the dn

        :param dn: string containing the distinguished name URL
        :return: String containing the MAC address or None if not found
        """
    if '/stcep-' in dn:
        return str(dn.split('/stcep-')[1].partition('-type-')[0])
    if '/cep-' in dn:
        return str(dn.split('/cep-')[1].partition('/')[0])
    if '/epdef-' in dn:
        return str(dn.split('/cep-')[1].partition('/')[0])
    return None


def read_property(element, name):
    """Decode an MLT item property
    which value is contained in a "property" XML element
    with matching "name" attribute"""
    return element.findtext("property[@name='{}']".format(name), '')


def make_logger_prefix(tag: str):
    """creates a function to add logger prefix, which returns tag when used empty"""
    return lambda text='': '{}{}'.format(tag, ': ' + text if text else '')


def find_previous(element, l):
    """
    find previous element in a sorted list

    >>> find_previous(0, [0])
    0
    >>> find_previous(2, [1, 1, 3])
    1
    >>> find_previous(0, [1, 2])
    >>> find_previous(1.5, [1, 2])
    1
    >>> find_previous(3, [1, 2])
    2
    """
    length = len(l)
    for index, current in enumerate(l):
        if length - 1 == index:
            return current
        if index == 0:
            if element < current:
                return None
        if current <= element < l[index + 1]:
            return current


@classmethod
def run(cls, profiles, timeslice_map, rev_table=None, reg_cols=('region',
    'class'), max_workers=None, legacy_format=False):
    """
        Compute means and standar deviations for each region and timeslice
        from given representative profiles

        Parameters
        ----------
        profiles : str
            Path to .h5 file containing profiles (representative or cf)
        timeslice_map : str | pandas.DataFrame
            Path to timeslice mapping file or DataFrame with mapping
        rev_table : str | pandas.DataFrame
            reV supply curve or aggregation table, or path to file containing
            table. Only required if timeslice calc is based on all cf_profiles
            instead of representative profiles.
        reg_cols : tuple
            Label(s) for a categorical region column(s) to create timeslices
            for
        max_workers : int
            Number of workers to use for parallel computation of means
            and stdevs when using cf profiles.
            1 means run in serial
            None means use all available CPUs
        legacy_format : bool
            Format outputs into ReEDS legacy format

        Returns
        -------
        stats : pandas.DataFrame
            A single DataFrame containing means and stdevs (sigma)
        corr_coeffs : pandas.DataFrame | dict | NoneType
            In legacy format: a DataFrame of correlation coefficients for
            all pairs of "regions" for each timeslice, else:
            a dictionary of correlation matrices for each timeslice.
            None for CF profiles due to memory constraints
        """
    ts = cls(profiles, timeslice_map, rev_table=rev_table, reg_cols=reg_cols)
    stats, coeffs = ts.compute_stats(max_workers=max_workers, legacy_format
        =legacy_format)
    return stats, coeffs


def basic_forced_photometry(rerun, psf=True, cmodel=True, aper=False, shape
    =False, flux=False, aper_type='3_20'):
    """
    Return a dict of column names for basic photometric measurements.
    """
    basic_dict = {'object_id': 'forced.object_id', 'ra': 'forced.ra', 'dec':
        'forced.dec', 'tract': 'forced.tract', 'patch': 'forced.patch',
        'a_g': 'forced.a_g', 'a_r': 'forced.a_r', 'a_i': 'forced.a_i',
        'a_z': 'forced.a_z', 'a_y': 'forced.a_y'}
    if 'pdr2' in rerun or 's18a' in rerun:
        meta_dict = {'merge_peak_sky': 'forced.merge_peak_sky',
            'g_inputcount': 'forced.g_inputcount_value', 'r_inputcount':
            'forced.r_inputcount_value', 'i_inputcount':
            'forced.i_inputcount_value', 'z_inputcount':
            'forced.z_inputcount_value', 'y_inputcount':
            'forced.y_inputcount_value', 'g_flag_edge':
            'forced.g_pixelflags_edge', 'r_flag_edge':
            'forced.r_pixelflags_edge', 'i_flag_edge':
            'forced.i_pixelflags_edge', 'z_flag_edge':
            'forced.z_pixelflags_edge', 'y_flag_edge':
            'forced.y_pixelflags_edge', 'g_flag_saturated':
            'forced.g_pixelflags_saturated', 'r_flag_saturated':
            'forced.r_pixelflags_saturated', 'i_flag_saturated':
            'forced.i_pixelflags_saturated', 'z_flag_saturated':
            'forced.z_pixelflags_saturated', 'y_flag_saturated':
            'forced.y_pixelflags_saturated', 'g_flag_interpolated':
            'forced.g_pixelflags_interpolated', 'r_flag_interpolated':
            'forced.r_pixelflags_interpolated', 'i_flag_interpolated':
            'forced.i_pixelflags_interpolated', 'z_flag_interpolated':
            'forced.z_pixelflags_interpolated', 'y_flag_interpolated':
            'forced.y_pixelflags_interpolated', 'g_flag_saturated_cen':
            'forced.g_pixelflags_saturatedcenter', 'r_flag_saturated_cen':
            'forced.r_pixelflags_saturatedcenter', 'i_flag_saturated_cen':
            'forced.i_pixelflags_saturatedcenter', 'z_flag_saturated_cen':
            'forced.z_pixelflags_saturatedcenter', 'y_flag_saturated_cen':
            'forced.y_pixelflags_saturatedcenter',
            'g_flag_interpolated_cen':
            'forced.g_pixelflags_interpolatedcenter',
            'r_flag_interpolated_cen':
            'forced.r_pixelflags_interpolatedcenter',
            'i_flag_interpolated_cen':
            'forced.i_pixelflags_interpolatedcenter',
            'z_flag_interpolated_cen':
            'forced.z_pixelflags_interpolatedcenter',
            'y_flag_interpolated_cen':
            'forced.y_pixelflags_interpolatedcenter', 'g_extendedness':
            'forced.g_extendedness_value', 'r_extendedness':
            'forced.r_extendedness_value', 'i_extendedness':
            'forced.i_extendedness_value', 'z_extendedness':
            'forced.z_extendedness_value', 'y_extendedness':
            'forced.y_extendedness_value'}
        if cmodel:
            cmodel_flag = {'g_cmodel_flag': 'forced.g_cmodel_flag',
                'r_cmodel_flag': 'forced.r_cmodel_flag', 'i_cmodel_flag':
                'forced.i_cmodel_flag', 'z_cmodel_flag':
                'forced.z_cmodel_flag', 'y_cmodel_flag': 'forced.y_cmodel_flag'
                }
            if flux:
                cmodel_dict = {'g_cmodel_flux': 'forced.g_cmodel_flux',
                    'r_cmodel_flux': 'forced.r_cmodel_flux',
                    'i_cmodel_flux': 'forced.i_cmodel_flux',
                    'z_cmodel_flux': 'forced.z_cmodel_flux',
                    'y_cmodel_flux': 'forced.y_cmodel_flux',
                    'g_cmodel_flux_err': 'forced.g_cmodel_fluxsigma',
                    'r_cmodel_flux_err': 'forced.r_cmodel_fluxsigma',
                    'i_cmodel_flux_err': 'forced.i_cmodel_fluxsigma',
                    'z_cmodel_flux_err': 'forced.z_cmodel_fluxsigma',
                    'y_cmodel_flux_err': 'forced.y_cmodel_fluxsigma'}
            else:
                cmodel_dict = {'g_cmodel_mag': 'forced.g_cmodel_mag',
                    'r_cmodel_mag': 'forced.r_cmodel_mag', 'i_cmodel_mag':
                    'forced.i_cmodel_mag', 'z_cmodel_mag':
                    'forced.z_cmodel_mag', 'y_cmodel_mag':
                    'forced.y_cmodel_mag', 'g_cmodel_mag_err':
                    'forced.g_cmodel_magsigma', 'r_cmodel_mag_err':
                    'forced.r_cmodel_magsigma', 'i_cmodel_mag_err':
                    'forced.i_cmodel_magsigma', 'z_cmodel_mag_err':
                    'forced.z_cmodel_magsigma', 'y_cmodel_mag_err':
                    'forced.y_cmodel_magsigma'}
            cmodel_dict.update(cmodel_flag)
        else:
            cmodel_dict = {}
        if psf:
            psf_flag = {'g_psf_flag': 'forced2.g_psfflux_flag',
                'r_psf_flag': 'forced2.r_psfflux_flag', 'i_psf_flag':
                'forced2.i_psfflux_flag', 'z_psf_flag':
                'forced2.z_psfflux_flag', 'y_psf_flag':
                'forced2.y_psfflux_flag'}
            if flux:
                psf_dict = {'g_psf_flux': 'forced2.g_psfflux_flux',
                    'r_psf_flux': 'forced2.r_psfflux_flux', 'i_psf_flux':
                    'forced2.i_psfflux_flux', 'z_psf_flux':
                    'forced2.z_psfflux_flux', 'y_psf_flux':
                    'forced2.y_psfflux_flux', 'g_psf_flux_err':
                    'forced2.g_psfflux_fluxsigma', 'r_psf_flux_err':
                    'forced2.r_psfflux_fluxsigma', 'i_psf_flux_err':
                    'forced2.i_psfflux_fluxsigma', 'z_psf_flux_err':
                    'forced2.z_psfflux_fluxsigma', 'y_psf_flux_err':
                    'forced2.y_psfflux_fluxsigma'}
            else:
                psf_dict = {'g_psf_mag': 'forced2.g_psfflux_mag',
                    'r_psf_mag': 'forced2.r_psfflux_mag', 'i_psf_mag':
                    'forced2.i_psfflux_mag', 'z_psf_mag':
                    'forced2.z_psfflux_mag', 'y_psf_mag':
                    'forced2.y_psfflux_mag', 'g_psf_mag_err':
                    'forced2.g_psfflux_magsigma', 'r_psf_mag_err':
                    'forced2.r_psfflux_magsigma', 'i_psf_mag_err':
                    'forced2.i_psfflux_magsigma', 'z_psf_mag_err':
                    'forced2.z_psfflux_magsigma', 'y_psf_mag_err':
                    'forced2.y_psfflux_magsigma'}
            psf_dict.update(psf_flag)
        else:
            psf_dict = {}
        if aper:
            aper_flag = {'g_aper_flag': 'forced4.g_convolvedflux_{}_flag'.
                format(aper_type), 'r_aper_flag':
                'forced4.r_convolvedflux_{}_flag'.format(aper_type),
                'i_aper_flag': 'forced4.i_convolvedflux_{}_flag'.format(
                aper_type), 'z_aper_flag':
                'forced4.z_convolvedflux_{}_flag'.format(aper_type),
                'y_aper_flag': 'forced4.y_convolvedflux_{}_flag'.format(
                aper_type)}
            if flux:
                aper_dict = {'g_aper_flux':
                    'forced4.g_convolvedflux_{}_flux'.format(aper_type),
                    'r_aper_flux': 'forced4.r_convolvedflux_{}_flux'.format
                    (aper_type), 'i_aper_flux':
                    'forced4.i_convolvedflux_{}_flux'.format(aper_type),
                    'z_aper_flux': 'forced4.z_convolvedflux_{}_flux'.format
                    (aper_type), 'y_aper_flux':
                    'forced4.y_convolvedflux_{}_flux'.format(aper_type),
                    'g_aper_flux_err':
                    'forced4.g_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'r_aper_flux_err':
                    'forced4.r_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'i_aper_flux_err':
                    'forced4.i_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'z_aper_flux_err':
                    'forced4.z_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'y_aper_flux_err':
                    'forced4.y_convolvedflux_{}_fluxsigma'.format(aper_type)}
            else:
                aper_dict = {'g_aper_mag': 'forced4.g_convolvedflux_{}_mag'
                    .format(aper_type), 'r_aper_mag':
                    'forced4.r_convolvedflux_{}_mag'.format(aper_type),
                    'i_aper_mag': 'forced4.i_convolvedflux_{}_mag'.format(
                    aper_type), 'z_aper_mag':
                    'forced4.z_convolvedflux_{}_mag'.format(aper_type),
                    'y_aper_mag': 'forced4.y_convolvedflux_{}_mag'.format(
                    aper_type), 'g_aper_mag_err':
                    'forced4.g_convolvedflux_{}_magsigma'.format(aper_type),
                    'r_aper_mag_err': 'forced4.r_convolvedflux_{}_magsigma'
                    .format(aper_type), 'i_aper_mag_err':
                    'forced4.i_convolvedflux_{}_magsigma'.format(aper_type),
                    'z_aper_mag_err': 'forced4.z_convolvedflux_{}_magsigma'
                    .format(aper_type), 'y_aper_mag_err':
                    'forced4.y_convolvedflux_{}_magsigma'.format(aper_type)}
            aper_dict.update(aper_flag)
        else:
            aper_dict = {}
        if shape:
            shape_dict = {'g_sdssshape_11': 'forced2.g_sdssshape_shape11',
                'g_sdssshape_22': 'forced2.g_sdssshape_shape22',
                'g_sdssshape_12': 'forced2.g_sdssshape_shape12',
                'r_sdssshape_11': 'forced2.r_sdssshape_shape11',
                'r_sdssshape_22': 'forced2.r_sdssshape_shape22',
                'r_sdssshape_12': 'forced2.r_sdssshape_shape12',
                'i_sdssshape_11': 'forced2.i_sdssshape_shape11',
                'i_sdssshape_22': 'forced2.i_sdssshape_shape22',
                'i_sdssshape_12': 'forced2.i_sdssshape_shape12',
                'z_sdssshape_11': 'forced2.z_sdssshape_shape11',
                'z_sdssshape_22': 'forced2.z_sdssshape_shape22',
                'z_sdssshape_12': 'forced2.z_sdssshape_shape12',
                'y_sdssshape_11': 'forced2.y_sdssshape_shape11',
                'y_sdssshape_22': 'forced2.y_sdssshape_shape22',
                'y_sdssshape_12': 'forced2.y_sdssshape_shape12'}
        else:
            shape_dict = {}
    elif 's17a' in rerun:
        meta_dict = {'merge_peak_sky': 'forced.merge_peak_sky',
            'g_inputcount': 'forced.g_inputcount_value', 'r_inputcount':
            'forced.r_inputcount_value', 'i_inputcount':
            'forced.i_inputcount_value', 'z_inputcount':
            'forced.z_inputcount_value', 'y_inputcount':
            'forced.y_inputcount_value', 'g_flag_edge':
            'forced.g_pixelflags_edge', 'r_flag_edge':
            'forced.r_pixelflags_edge', 'i_flag_edge':
            'forced.i_pixelflags_edge', 'z_flag_edge':
            'forced.z_pixelflags_edge', 'y_flag_edge':
            'forced.y_pixelflags_edge', 'g_flag_saturated':
            'forced.g_pixelflags_saturated', 'r_flag_saturated':
            'forced.r_pixelflags_saturated', 'i_flag_saturated':
            'forced.i_pixelflags_saturated', 'z_flag_saturated':
            'forced.z_pixelflags_saturated', 'y_flag_saturated':
            'forced.y_pixelflags_saturated', 'g_flag_interpolated':
            'forced.g_pixelflags_interpolated', 'r_flag_interpolated':
            'forced.r_pixelflags_interpolated', 'i_flag_interpolated':
            'forced.i_pixelflags_interpolated', 'z_flag_interpolated':
            'forced.z_pixelflags_interpolated', 'y_flag_interpolated':
            'forced.y_pixelflags_interpolated', 'g_flag_saturated_cen':
            'forced.g_pixelflags_saturatedcenter', 'r_flag_saturated_cen':
            'forced.r_pixelflags_saturatedcenter', 'i_flag_saturated_cen':
            'forced.i_pixelflags_saturatedcenter', 'z_flag_saturated_cen':
            'forced.z_pixelflags_saturatedcenter', 'y_flag_saturated_cen':
            'forced.y_pixelflags_saturatedcenter',
            'g_flag_interpolated_cen':
            'forced.g_pixelflags_interpolatedcenter',
            'r_flag_interpolated_cen':
            'forced.r_pixelflags_interpolatedcenter',
            'i_flag_interpolated_cen':
            'forced.i_pixelflags_interpolatedcenter',
            'z_flag_interpolated_cen':
            'forced.z_pixelflags_interpolatedcenter',
            'y_flag_interpolated_cen':
            'forced.y_pixelflags_interpolatedcenter', 'g_extendedness':
            'forced.g_extendedness_value', 'r_extendedness':
            'forced.r_extendedness_value', 'i_extendedness':
            'forced.i_extendedness_value', 'z_extendedness':
            'forced.z_extendedness_value', 'y_extendedness':
            'forced.y_extendedness_value'}
        if cmodel:
            cmodel_flag = {'g_cmodel_flag': 'forced.g_cmodel_flag',
                'r_cmodel_flag': 'forced.r_cmodel_flag', 'i_cmodel_flag':
                'forced.i_cmodel_flag', 'z_cmodel_flag':
                'forced.z_cmodel_flag', 'y_cmodel_flag': 'forced.y_cmodel_flag'
                }
            if flux:
                cmodel_dict = {'g_cmodel_flux': 'forced.g_cmodel_flux',
                    'r_cmodel_flux': 'forced.r_cmodel_flux',
                    'i_cmodel_flux': 'forced.i_cmodel_flux',
                    'z_cmodel_flux': 'forced.z_cmodel_flux',
                    'y_cmodel_flux': 'forced.y_cmodel_flux',
                    'g_cmodel_flux_err': 'forced.g_cmodel_fluxsigma',
                    'r_cmodel_flux_err': 'forced.r_cmodel_fluxsigma',
                    'i_cmodel_flux_err': 'forced.i_cmodel_fluxsigma',
                    'z_cmodel_flux_err': 'forced.z_cmodel_fluxsigma',
                    'y_cmodel_flux_err': 'forced.y_cmodel_fluxsigma'}
            else:
                cmodel_dict = {'g_cmodel_mag': 'forced.g_cmodel_mag',
                    'r_cmodel_mag': 'forced.r_cmodel_mag', 'i_cmodel_mag':
                    'forced.i_cmodel_mag', 'z_cmodel_mag':
                    'forced.z_cmodel_mag', 'y_cmodel_mag':
                    'forced.y_cmodel_mag', 'g_cmodel_mag_err':
                    'forced.g_cmodel_magsigma', 'r_cmodel_mag_err':
                    'forced.r_cmodel_magsigma', 'i_cmodel_mag_err':
                    'forced.i_cmodel_magsigma', 'z_cmodel_mag_err':
                    'forced.z_cmodel_magsigma', 'y_cmodel_mag_err':
                    'forced.y_cmodel_magsigma'}
            cmodel_dict.update(cmodel_flag)
        else:
            cmodel_dict = {}
        if psf:
            psf_flag = {'g_psf_flag': 'forced.g_psfflux_flag', 'r_psf_flag':
                'forced.r_psfflux_flag', 'i_psf_flag':
                'forced.i_psfflux_flag', 'z_psf_flag':
                'forced.z_psfflux_flag', 'y_psf_flag': 'forced.y_psfflux_flag'}
            if flux:
                psf_dict = {'g_psf_flux': 'forced.g_psfflux_flux',
                    'r_psf_flux': 'forced.r_psfflux_flux', 'i_psf_flux':
                    'forced.i_psfflux_flux', 'z_psf_flux':
                    'forced.z_psfflux_flux', 'y_psf_flux':
                    'forced.y_psfflux_flux', 'g_psf_flux_err':
                    'forced.g_psfflux_fluxsigma', 'r_psf_flux_err':
                    'forced.r_psfflux_fluxsigma', 'i_psf_flux_err':
                    'forced.i_psfflux_fluxsigma', 'z_psf_flux_err':
                    'forced.z_psfflux_fluxsigma', 'y_psf_flux_err':
                    'forced.y_psfflux_fluxsigma'}
            else:
                psf_dict = {'g_psf_mag': 'forced.g_psfflux_mag',
                    'r_psf_mag': 'forced.r_psfflux_mag', 'i_psf_mag':
                    'forced.i_psfflux_mag', 'z_psf_mag':
                    'forced.z_psfflux_mag', 'y_psf_mag':
                    'forced.y_psfflux_mag', 'g_psf_mag_err':
                    'forced.g_psfflux_magsigma', 'r_psf_mag_err':
                    'forced.r_psfflux_magsigma', 'i_psf_mag_err':
                    'forced.i_psfflux_magsigma', 'z_psf_mag_err':
                    'forced.z_psfflux_magsigma', 'y_psf_mag_err':
                    'forced.y_psfflux_magsigma'}
            psf_dict.update(psf_flag)
        else:
            psf_dict = {}
        if aper:
            aper_flag = {'g_aper_flag': 'forced3.g_convolvedflux_{}_flag'.
                format(aper_type), 'r_aper_flag':
                'forced3.r_convolvedflux_{}_flag'.format(aper_type),
                'i_aper_flag': 'forced3.i_convolvedflux_{}_flag'.format(
                aper_type), 'z_aper_flag':
                'forced3.z_convolvedflux_{}_flag'.format(aper_type),
                'y_aper_flag': 'forced3.y_convolvedflux_{}_flag'.format(
                aper_type)}
            if flux:
                aper_dict = {'g_aper_flux':
                    'forced3.g_convolvedflux_{}_flux'.format(aper_type),
                    'r_aper_flux': 'forced3.r_convolvedflux_{}_flux'.format
                    (aper_type), 'i_aper_flux':
                    'forced3.i_convolvedflux_{}_flux'.format(aper_type),
                    'z_aper_flux': 'forced3.z_convolvedflux_{}_flux'.format
                    (aper_type), 'y_aper_flux':
                    'forced3.y_convolvedflux_{}_flux'.format(aper_type),
                    'g_aper_flux_err':
                    'forced3.g_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'r_aper_flux_err':
                    'forced3.r_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'i_aper_flux_err':
                    'forced3.i_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'z_aper_flux_err':
                    'forced3.z_convolvedflux_{}_fluxsigma'.format(aper_type
                    ), 'y_aper_flux_err':
                    'forced3.y_convolvedflux_{}_fluxsigma'.format(aper_type)}
            else:
                aper_dict = {'g_aper_mag': 'forced3.g_convolvedflux_{}_mag'
                    .format(aper_type), 'r_aper_mag':
                    'forced3.r_convolvedflux_{}_mag'.format(aper_type),
                    'i_aper_mag': 'forced3.i_convolvedflux_{}_mag'.format(
                    aper_type), 'z_aper_mag':
                    'forced3.z_convolvedflux_{}_mag'.format(aper_type),
                    'y_aper_mag': 'forced3.y_convolvedflux_{}_mag'.format(
                    aper_type), 'g_aper_mag_err':
                    'forced3.g_convolvedflux_{}_magsigma'.format(aper_type),
                    'r_aper_mag_err': 'forced3.r_convolvedflux_{}_magsigma'
                    .format(aper_type), 'i_aper_mag_err':
                    'forced3.i_convolvedflux_{}_magsigma'.format(aper_type),
                    'z_aper_mag_err': 'forced3.z_convolvedflux_{}_magsigma'
                    .format(aper_type), 'y_aper_mag_err':
                    'forced3.y_convolvedflux_{}_magsigma'.format(aper_type)}
            aper_dict.update(aper_flag)
        else:
            aper_dict = {}
        if shape:
            print(
                '# SDSS Shape is not available for forced photometry in S17A release.'
                )
        shape_dict = {}
    elif 'pdr1' in rerun or 's16a' in rerun:
        meta_dict = {'merge_peak_sky': 'forced.merge_peak_sky',
            'g_inputcount': 'forced.gcountinputs', 'r_inputcount':
            'forced.rcountinputs', 'i_inputcount': 'forced.icountinputs',
            'z_inputcount': 'forced.zcountinputs', 'y_inputcount':
            'forced.ycountinputs', 'g_flag_edge':
            'forced.gflags_pixel_edge', 'r_flag_edge':
            'forced.rflags_pixel_edge', 'i_flag_edge':
            'forced.iflags_pixel_edge', 'z_flag_edge':
            'forced.zflags_pixel_edge', 'y_flag_edge':
            'forced.yflags_pixel_edge', 'g_flag_saturated':
            'forced.gflags_pixel_saturated_any', 'r_flag_saturated':
            'forced.rflags_pixel_saturated_any', 'i_flag_saturated':
            'forced.iflags_pixel_saturated_any', 'z_flag_saturated':
            'forced.zflags_pixel_saturated_any', 'y_flag_saturated':
            'forced.yflags_pixel_saturated_any', 'g_flag_interpolated':
            'forced.gflags_pixel_interpolated_any', 'r_flag_interpolated':
            'forced.rflags_pixel_interpolated_any', 'i_flag_interpolated':
            'forced.iflags_pixel_interpolated_any', 'z_flag_interpolated':
            'forced.zflags_pixel_interpolated_any', 'y_flag_interpolated':
            'forced.yflags_pixel_interpolated_any', 'g_flag_saturated_cen':
            'forced.gflags_pixel_saturated_center', 'r_flag_saturated_cen':
            'forced.rflags_pixel_saturated_center', 'i_flag_saturated_cen':
            'forced.iflags_pixel_saturated_center', 'z_flag_saturated_cen':
            'forced.zflags_pixel_saturated_center', 'y_flag_saturated_cen':
            'forced.yflags_pixel_saturated_center',
            'g_flag_interpolated_cen':
            'forced.gflags_pixel_interpolated_center',
            'r_flag_interpolated_cen':
            'forced.rflags_pixel_interpolated_center',
            'i_flag_interpolated_cen':
            'forced.iflags_pixel_interpolated_center',
            'z_flag_interpolated_cen':
            'forced.zflags_pixel_interpolated_center',
            'y_flag_interpolated_cen':
            'forced.yflags_pixel_interpolated_center', 'g_extendedness':
            'forced.gclassification_extendedness', 'r_extendedness':
            'forced.rclassification_extendedness', 'i_extendedness':
            'forced.iclassification_extendedness', 'z_extendedness':
            'forced.zclassification_extendedness', 'y_extendedness':
            'forced.yclassification_extendedness'}
        if cmodel:
            cmodel_flag = {'g_cmodel_flag': 'forced.gcmodel_flux_flags',
                'r_cmodel_flag': 'forced.rcmodel_flux_flags',
                'i_cmodel_flag': 'forced.icmodel_flux_flags',
                'z_cmodel_flag': 'forced.zcmodel_flux_flags',
                'y_cmodel_flag': 'forced.ycmodel_flux_flags'}
            if flux:
                cmodel_dict = {'g_cmodel_flux': 'forced.gcmodel_flux',
                    'r_cmodel_flux': 'forced.rcmodel_flux', 'i_cmodel_flux':
                    'forced.icmodel_flux', 'z_cmodel_flux':
                    'forced.zcmodel_flux', 'y_cmodel_flux':
                    'forced.ycmodel_flux', 'g_cmodel_flux_err':
                    'forced.gcmodel_flux_err', 'r_cmodel_flux_err':
                    'forced.rcmodel_flux_err', 'i_cmodel_flux_err':
                    'forced.icmodel_flux_err', 'z_cmodel_flux_err':
                    'forced.zcmodel_flux_err', 'y_cmodel_flux_err':
                    'forced.ycmodel_flux_err'}
            else:
                cmodel_dict = {'g_cmodel_mag': 'forced.gcmodel_mag',
                    'r_cmodel_mag': 'forced.rcmodel_mag', 'i_cmodel_mag':
                    'forced.icmodel_mag', 'z_cmodel_mag':
                    'forced.zcmodel_mag', 'y_cmodel_mag':
                    'forced.ycmodel_mag', 'g_cmodel_mag_err':
                    'forced.gcmodel_mag_err', 'r_cmodel_mag_err':
                    'forced.rcmodel_mag_err', 'i_cmodel_mag_err':
                    'forced.icmodel_mag_err', 'z_cmodel_mag_err':
                    'forced.zcmodel_mag_err', 'y_cmodel_mag_err':
                    'forced.ycmodel_mag_err'}
            cmodel_dict.update(cmodel_flag)
        else:
            cmodel_dict = {}
        if psf:
            psf_flag = {'g_psf_flag': 'forced.gflux_psf_flags',
                'r_psf_flag': 'forced.rflux_psf_flags', 'i_psf_flag':
                'forced.iflux_psf_flags', 'z_psf_flag':
                'forced.zflux_psf_flags', 'y_psf_flag':
                'forced.yflux_psf_flags'}
            if flux:
                psf_dict = {'g_psf_flux': 'forced.gflux_psf', 'r_psf_flux':
                    'forced.rflux_psf', 'i_psf_flux': 'forced.iflux_psf',
                    'z_psf_flux': 'forced.zflux_psf', 'y_psf_flux':
                    'forced.yflux_psf', 'g_psf_flux_err':
                    'forced.gflux_psf_err', 'r_psf_flux_err':
                    'forced.rflux_psf_err', 'i_psf_flux_err':
                    'forced.iflux_psf_err', 'z_psf_flux_err':
                    'forced.zflux_psf_err', 'y_psf_flux_err':
                    'forced.yflux_psf_err'}
            else:
                psf_dict = {'g_psf_mag': 'forced.gmag_psf', 'r_psf_mag':
                    'forced.rmag_psf', 'i_psf_mag': 'forced.imag_psf',
                    'z_psf_mag': 'forced.zmag_psf', 'y_psf_mag':
                    'forced.ymag_psf', 'g_psf_mag_err':
                    'forced.gmag_psf_err', 'r_psf_mag_err':
                    'forced.rmag_psf_err', 'i_psf_mag_err':
                    'forced.imag_psf_err', 'z_psf_mag_err':
                    'forced.zmag_psf_err', 'y_psf_mag_err':
                    'forced.ymag_psf_err'}
            psf_dict.update(psf_flag)
        else:
            psf_dict = {}
        if aper:
            print('# No PSF matched aperture photometry is available in PDR1')
            aper_dict = {}
        if shape:
            shape_dict = {'g_sdssshape_11': 'forced.gshape_sdss_11',
                'g_sdssshape_22': 'forced.gshape_sdss_22', 'g_sdssshape_12':
                'forced.gshape_sdss_12', 'r_sdssshape_11':
                'forced.rshape_sdss_11', 'r_sdssshape_22':
                'forced.rshape_sdss_22', 'r_sdssshape_12':
                'forced.rshape_sdss_12', 'i_sdssshape_11':
                'forced.ishape_sdss_11', 'i_sdssshape_22':
                'forced.ishape_sdss_22', 'i_sdssshape_12':
                'forced.ishape_sdss_12', 'z_sdssshape_11':
                'forced.zshape_sdss_11', 'z_sdssshape_22':
                'forced.zshape_sdss_22', 'z_sdssshape_12':
                'forced.zshape_sdss_12', 'y_sdssshape_11':
                'forced.yshape_sdss_11', 'y_sdssshape_22':
                'forced.yshape_sdss_22', 'y_sdssshape_12':
                'forced.yshape_sdss_12'}
        else:
            shape_dict = {}
    else:
        raise NameError('Wrong rerun name')
    basic_dict.update(cmodel_dict)
    basic_dict.update(psf_dict)
    basic_dict.update(aper_dict)
    basic_dict.update(shape_dict)
    basic_dict.update(meta_dict)
    return basic_dict


def p_opt_ORDER_BY_simple(p):
    """opt_ORDER_BY : ORDER BY identifier opt_ORDER_DIRECTION"""
    order = {'by': p[3], 'direction': p[4]}
    p[0] = order


def is_readable(fp, size=1):
    """
    Check if the file-like object is readable.

    :param fp: file-like object
    :param size: byte size
    :return: bool
    """
    read_size = len(fp.read(size))
    fp.seek(-read_size, 1)
    return read_size == size


def copy_storage(sourcestore, deststore):
    """Copies the files from the source storage object to the destination
    storage object using ``shutil.copyfileobj``.
    """
    from shutil import copyfileobj
    for name in sourcestore.list():
        with sourcestore.open_file(name) as source:
            with deststore.create_file(name) as dest:
                copyfileobj(source, dest)


def effective_prior(Ptar, cmiss, cfa):
    """This function adjusts a given prior probability of target p_targ,
    to incorporate the effects of a cost of miss,
    cmiss, and a cost of false-alarm, cfa.
    In particular note:
    EFFECTIVE_PRIOR(EFFECTIVE_PRIOR(p,cmiss,cfa),1,1)
            = EFFECTIVE_PRIOR(p,cfa,cmiss)

    The effective prior for the NIST SRE detection cost fuction,
    with p_targ = 0.01, cmiss = 10, cfa = 1 is therefore:
    EFFECTIVE_PRIOR(0.01,10,1) = 0.0917

    :param Ptar: is the probability of a target trial
    :param cmiss: is the cost of a miss
    :param cfa: is the cost of a false alarm

    :return: a prior
    """
    p = Ptar * cmiss / (Ptar * cmiss + (1 - Ptar) * cfa)
    return p


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

        :param GroupJoinPolicyUpdatedType val:
        :rtype: EventType
        """
    return cls('group_join_policy_updated', val)


def getCleanFileName(filename):
    """Strip path from filenme (could happen in IE)"""
    cleanFileName = filename.split('\\')[-1]
    return cleanFileName.split('/')[-1]


def camera_to_view():
    """Set camera view to active view

    """
    pass


def fCO2fromTCpH(TC, pH, K0, K1, K2):
    """Calculate CO2 fugacity from dissolved inorganic carbon and pH.

    Based on CalculatefCO2fromTCpH, version 02.02, 12-13-96, by Ernie Lewis.
    """
    H = 10.0 ** -pH
    return TC * H ** 2 / (H ** 2 + K1 * H + K1 * K2) / K0


def specific_speed(Q, H, n=3600.0):
    """Returns the specific speed of a pump operating at a specified Q, H,
    and n.

    .. math::
        n_S = \\frac{n\\sqrt{Q}}{H^{0.75}}

    Parameters
    ----------
    Q : float
        Flow rate, [m^3/s]
    H : float
        Head generated by the pump, [m]
    n : float, optional
        Speed of pump [rpm]

    Returns
    -------
    nS : float
        Specific Speed, [rpm*m^0.75/s^0.5]

    Notes
    -----
    Defined at the BEP, with maximum fitting diameter impeller, at a given
    rotational speed.

    Examples
    --------
    Example from [1]_.

    >>> specific_speed(0.0402, 100, 3550)
    22.50823182748925

    References
    ----------
    .. [1] HI 1.3 Rotodynamic Centrifugal Pumps for Design and Applications
    """
    return n * Q ** 0.5 / H ** 0.75


@classmethod
def load_from_cli_options(cls, args, **kwargs):
    """Create a :py:class:`.Session` object from CLI arguments.

        The CLI arguments must have been registered with
        :py:meth:`.register_cli_options`.

        :param Namespace args: result of parsed arguments.

        :returns: A new session object.
        :rtype: :py:class:`.Session`
        """
    kwargs['insecure'] = args.insecure
    kwargs['cacert'] = args.os_cacert
    if args.os_cert and args.os_key:
        kwargs['cert'] = args.os_cert, args.os_key
    kwargs['timeout'] = args.timeout
    return cls._make(**kwargs)


@classmethod
def from_file(cls, net_file, file_type=None):
    """Loads a network from an ONNX or ERAN file format.

        Files ending in .onnx will be loaded as ONNX files, ones ending in
        .eran will be loaded as ERAN files. Pass file_tye="{eran, onnx}" to
        override this behavior.
        """
    if file_type is None:
        file_type = net_file.split('.')[-1]
    file_type = file_type.lower()
    if file_type == 'eran':
        return cls.from_eran(net_file)
    if file_type == 'onnx':
        return cls.from_onnx(net_file)
    raise NotImplementedError


def lod_lookup(lod: list, **kw):
    """Lookup in lod by attribute values.

    Args:

        lod (list): lod to be used

        **kw (dict): use keyword arguments.  keys are column names, their
                     value is attribute value

    Returns:

        list: first matching row
    """
    for row in lod:
        for k, v in kw.items():
            if row[k] != str(v):
                break
        else:
            return row
    return None


def remove_hours(time):
    """Sets the hours, minutes, seconds, and microseconds to zero."""
    return time.replace(hour=0, minute=0, second=0, microsecond=0)


@staticmethod
def printf(*args):
    """
        Print the specified arguments to the screen.

        Args:
            *args: Variable length argument list.
        """
    print(*args, end='')


def stopListening():
    """
        Stop listening on this port.

        If it does not complete immediately, will return L{Deferred} that fires
        upon completion.
        """


def with_metaclass(meta, base=object):
    """
    Create a base class with a metaclass. Compatible across Python 2 and Python
    3. Extension of the with_metaclass() found in the six module.
    """
    if not isinstance(base, tuple):
        basetuple = base,
    return meta('NewBase', basetuple, {})


def _parse_init_params(params: str):
    """
    Parse the initialization parameters.
    Currently supports 2:
        -i DOCKER_IMAGE_NAME
        -w WORK_PATH
    :returns: The working dir and image name.
    """
    supported_msg = (
        'Supported -w for working directory and                      -i for COMPSs docker image.'
        )
    working_dir = ''
    image = ''
    fields = params.split()
    if len(fields) == 2:
        if fields[0] == '-w':
            working_dir = fields[1]
        elif fields[0] == '-i':
            image = fields[1]
        else:
            Exception('Unsupported flag: ' + str(fields[0]) + '. ' +
                supported_msg)
    elif len(fields) == 4:
        if fields[0] == '-w':
            working_dir = fields[1]
        elif fields[0] == '-i':
            image = fields[1]
        else:
            Exception('Unsupported flag: ' + str(fields[0]) + '. ' +
                supported_msg)
        if fields[2] == '-w':
            working_dir = fields[3]
        elif fields[2] == '-i':
            image = fields[3]
        else:
            Exception('Unsupported flag: ' + str(fields[2]) + '. ' +
                supported_msg)
    else:
        raise Exception('Incorrect number of parameters')
    return working_dir, image


def text_paste():
    """Paste text from clipboard

    """
    pass


def get_resource(intersight):
    """
    GET a resource and return the 1st element found
    """
    options = {'http_method': 'get', 'resource_path': intersight.module.
        params['resource_path'], 'query_params': intersight.module.params[
        'query_params']}
    response_dict = intersight.call_api(**options)
    if response_dict.get('Results'):
        response_dict = response_dict['Results'][0]
    return response_dict


def _validator_args_logic(args):
    """
    Implements logic for how validator arguments work in combination.

    As per: https://github.com/XLSForm/pyxform/pull/167#issuecomment-353382008

    **backwards-compatible**
    `xls2xform.py myform --skip_validate`: no validators
    `xls2xform.py myform`: ODK only

    **new**
    `xls2xform.py myform --enketo_validate`: Enketo only
    `xls2xform.py myform --odk_validate`: ODK only
    `xls2xform.py myform --enketo_validate --odk_validate`: both
    `xls2xform.py myform --enketo_validate --odk_validate --skip_validate`: no validators
    """
    if not args.skip_validate:
        args.odk_validate = False
        args.enketo_validate = False
    elif args.skip_validate and not (args.odk_validate or args.enketo_validate
        ):
        args.odk_validate = True
        args.enketo_validate = False
    return args


@staticmethod
def check_mode(mode):
    """
        Verify if the requested protocol mode is known.
        """
    if mode not in ('json', 'text'):
        raise ValueError('invalid mode %s' % mode)
    return True


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

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


def unflatten(flat_weights):
    """
    Pivot weights from long DataFrame into weighting matrix.

    Parameters
    ----------
    flat_weights: pandas.DataFrame
        A long DataFrame of weights, where columns are "date", "contract",
        "generic", "weight" and optionally "key". If "key" column is
        present a dictionary of unflattened DataFrames is returned with the
        dictionary keys corresponding to the "key" column and each sub
        DataFrame containing rows for this key.

    Returns
    -------
    A DataFrame or dict of DataFrames of instrument weights with a MultiIndex
    where the top level contains pandas.Timestamps and the second level is
    instrument names. The columns consist of generic names. If dict is returned
    the dict keys correspond to the "key" column of the input.

    Example
    -------
    >>> import pandas as pd
    >>> from pandas import Timestamp as TS
    >>> import mapping.util as util
    >>> long_wts = pd.DataFrame(
    ...         {"date": [TS('2015-01-03')] * 4 + [TS('2015-01-04')] * 4,
    ...          "contract": ['CLF5'] * 2 + ['CLG5'] * 4 + ['CLH5'] * 2,
    ...          "generic": ["CL1", "CL2"] * 4,
    ...          "weight": [1, 0, 0, 1, 1, 0, 0, 1]}
    ...     ).loc[:, ["date", "contract", "generic", "weight"]]
    >>> util.unflatten(long_wts)

    See also: calc_rets()
    """
    if flat_weights.columns.contains('key'):
        weights = {}
        for key in flat_weights.loc[:, ('key')].unique():
            flt_wts = flat_weights.loc[(flat_weights.loc[:, ('key')] == key), :
                ]
            flt_wts = flt_wts.drop(labels='key', axis=1)
            wts = flt_wts.pivot_table(index=['date', 'contract'], columns=[
                'generic'], values=['weight'])
            wts.columns = wts.columns.droplevel(0)
            weights[key] = wts
    else:
        weights = flat_weights.pivot_table(index=['date', 'contract'],
            columns=['generic'], values=['weight'])
        weights.columns = weights.columns.droplevel(0)
    return weights


def generate(context=None, param={}, seed=None):
    """Generate the sample data.

        Runs the generate functions of all plugins in an order such that
        the dependencies are all generated before the dependents.

        In essence, this function performs a topological sort in a
        directed acyclic graph.

        Raises a CyclicDependencyError if the dependency graph has a cycle.

        Returns a dict with names of plugins run as keys and CPU times as
        values.

        context:
            The context to be used to generate the sample data.
        param:
            A mapping containing the parameters for the generator plugins.
            The key is the name of the plugin.
        """


def isPoints2(obj):
    """Check for an B{C{LatLon2psxy}} points wrapper.

       @arg obj: The object (any C{type}).

       @return: C{True} if B{C{obj}} is an B{C{LatLon2psxy}}
                instance, C{False} otherwise.
    """
    return getattr(obj, 'isPoints2', False)


@classmethod
def _parse_header(cls, filename, fp, data_objects=None, close=False):
    """
            This method is implemented by sub-classes.
            It should parse the file and returns a list of DataObjects
            with the header properties filled in accordingly.
            The filename argument is always required. If no file object is passed
            as keyword argument, it only serves as a label. Otherwise a new file
            object is created.
            File objects are not closed unless close is set to True.
            Existing DataObjects can be passed as well and will then
            be used instead of creating new ones.
        """
    raise NotImplementedError


def getCredentialsPlugins():
    """Return iterable of (plugin name, actual credentials plugin) pairs.
        Looks up names in credentialsPlugins as contained ids of non-utility
        ICredentialsPlugins first, then as registered ICredentialsPlugin
        utilities.  Names that do not resolve are ignored."""


def unpack(instance: tuple) ->tuple:
    """Return the inside of any ADT instance.

    This function is not meant for general use.
    """
    return tuple.__getitem__(instance, slice(None))


@classmethod
def available(cls):
    """returns True if OSS output is available on the system"""
    try:
        import ossaudiodev
        ossaudiodev.open('w').close()
        return True
    except (ImportError, IOError):
        return False


def _line_parse(line):
    """Removes line ending characters and returns a tuple (`stripped_line`,
    `is_terminated`).
    """
    if line[-2:] in ['\r\n', b'\r\n']:
        return line[:-2], True
    elif line[-1:] in ['\r', '\n', b'\r', b'\n']:
        return line[:-1], True
    return line, False


def get_fnone(fsize):
    """
    Get sentinel value for filesize when writing OS/radio links.

    :param fsize: Filesize.
    :type fsize: int
    """
    return True if fsize is None else False


def failure(data, errors):
    """Handle unsucessful submition

        This method is called when the action was submitted and the
        submitted data was not valid.
        """


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


@staticmethod
def build_colDefs_for_mi_rows(df, keep_multiindex):
    """
        create agGrid columnDefs dict for column grouping
        from multiindex dataframe columns
        """
    mindexrow = df.index
    s = []
    for e in list(mindexrow.names):
        new_e = {'field': e, 'headerName': e.title(), 'rowGroup': True}
        if not keep_multiindex:
            new_e['hide'] = True
        s.append(new_e)
    return s


def hex8_to_u32be(data):
    """! @brief Build 32-bit register value from big-endian 8-digit hexadecimal string"""
    return int(data[6:8] + data[4:6] + data[2:4] + data[0:2], 16)


@classmethod
def green(cls, string, auto=False):
    """Color-code entire string.

        :param str string: String to colorize.
        :param bool auto: Enable auto-color (dark/light terminal).

        :return: Class instance for colorized string.
        :rtype: Color
        """
    return cls.colorize('green', string, auto=auto)


def dependency_is_none(dependency):
    """Return True if the dependency is None, otherwise False.

    This is done using a function so that tests can mock this
    behavior easily.

    :param dependency: The module to check if it is None
    :return: True if dependency is None otherwise False.

    """
    return dependency is None


def generate_snapshot_metadata(context, image_api, image_id, instance):
    """Generate a metadata dictionary for an instance snapshot.

    :param context: Nova security context
    :param image_api: Handle to the glance image API.
    :param image_id: UUID of the prepared glance image.
    :param instance: The Nova instance whose disk is to be snapshotted.
    :return: A dict of metadata suitable for image_api.update.
    """
    image = image_api.get(context, image_id)
    metadata = {'name': image['name'], 'status': 'active', 'disk_format':
        'raw', 'container_format': 'bare', 'properties': {'image_location':
        'snapshot', 'image_state': 'available', 'owner_id': instance.
        project_id}}
    return metadata


def reformat_predict(predictions):
    """
    Return [0,0,1] from [0.00009493, 0.000036783,0.99345]
    """
    blank = [False] * len(predictions[0])
    x_predicted_formatted = []
    for i in predictions:
        one_hot_vector = blank.copy()
        one_hot_vector[i.argsort()[-1]] = True
        x_predicted_formatted.append(one_hot_vector)
    return x_predicted_formatted


@classmethod
def _open_for_reading(cls, filename):
    """Open a file appropriately for reading data."""
    return open(filename, 'r')


def getstreakpeaks(killstreaks):
    """
	Takes a list of tuples where: element 0 is a number and 1 is a time
	tick (which is ignored), then only returns the tuples that make up the
	peak of their sequence.
	For example: (1,2,3,4,5,6,1,2,1,2,3,4) -> (6,2,4) [Only element 0 of
	the tuples displayed].
	This function does not perform any sorting, input is expected to already
	be in a correct order.
	"""
    streakpeaks = []
    if killstreaks:
        localkillstreaks = killstreaks.copy()
        localkillstreaks.append((-1, -1))
        prv = -1, -1
        for i in localkillstreaks:
            if i[0] <= prv[0]:
                streakpeaks.append(prv)
            prv = i
    return streakpeaks


def write_file(filename, probe, original=None, date=None, title=None, notes
    =None, run=None, charge=None):
    """
    Save probe as SNS reduced file.
    """
    from datetime import datetime as dt
    parts = []
    if original is None:
        original = filename
    if date is None:
        date = dt.strftime(dt.now(), '%Y-%m-%d %H:%M:%S')
    parts.append('#F ' + original)
    parts.append('#D ' + date)
    if run is not None:
        parts.append('#C Run Number: %s' % run)
    if title is not None:
        parts.append('#C Title: %s' % title)
    if notes is not None:
        parts.append('#C Notes: %s' % notes)
    parts.append("#C Detector Angle: (%g, 'degree')" % probe.T[0])
    if charge is not None:
        parts.append('#C Proton Charge: %s' % charge)
    parts.append('')
    parts.append('#N 5')
    parts.append('#L Q(1/A) dQ(1/A) R() dR() L(A)')
    parts.append('')
    header = '\n'.join(parts)
    probe.write_data(filename, columns=['Q', 'dQ', 'R', 'dR', 'L'], header=
        header)


def GetOperatorIdx():
    """Get the available operator index.

    Returns
    -------
    int
        The operator index.

    """
    global _CURRENT_OP_UID
    _CURRENT_OP_UID += 1
    return _CURRENT_OP_UID - 1


@classmethod
def _fields(cls):
    """_fields is a mapping from constructor argument
        name to the field definition"""
    return {}


@classmethod
def _get_apic_classes(cls):
    """
        Get the APIC classes used by this acitoolkit class.

        :returns: list of strings containing APIC class names
        """
    return ['vzSubj']


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

    Example::

       x = [[ 6.,  6.,  6.],
            [ 6.,  6.,  6.]]

       y = [[ 2.],
            [ 3.]]

       broadcast_div(x, y) = [[ 3.,  3.,  3.],
                              [ 2.,  2.,  2.]]

    Supported sparse operations:

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

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

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

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

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


def assert_(condition, message='', exception_type=AssertionError):
    """Like assert, but with arbitrary exception types."""
    if not condition:
        raise exception_type(message)


def render_bar(screen, origin, width, height, color):
    """
    Fills a rectangle within *screen* based at *origin* (an ``(x, y)`` tuple),
    *width* pixels wide and *height* pixels high. The rectangle will be filled
    in *color*.
    """
    x1, y1 = origin
    x2 = x1 + width
    y2 = y1 + height
    max_y, max_x = screen.shape[:2]
    y1, y2 = max_y - y2, max_y - y1
    screen[y1:y2, x1:x2, :] = color


def __new__(mcs, name, bases, attrs):
    """Update the new class with appropriate attributes.

        Arguments:
          mcs (:py:class:`type`): The newly-created class.
          name (:py:class:`str`): The name of the class.
          bases (:py:class:`tuple`): The base classes of the class.
          attrs (:py:class:`dict`): The attributes of the class.

        Returns:
          :py:class:`type`: The class, updated.

        Note:
          The ``FRIENDLY_NAME`` defaults to ``name`` if not explicitly
          provided.

        """
    attrs['FRIENDLY_NAME'] = attrs.get('FRIENDLY_NAME', name)
    return super().__new__(mcs, name, bases, attrs)


def get_resource_stream(manager, resource_name):
    """Return a readable file-like object for `resource_name`

        `manager` must be an ``IResourceManager``"""


@classmethod
def get_defaults(cls, shopify_resource):
    """
        Get a hash of attribute: values that can be used to update or create a local instance of the given Shopify
        resource.
        """
    defaults = {}
    for field in cls.get_default_fields():
        if hasattr(shopify_resource, field):
            defaults[field] = getattr(shopify_resource, field)
    for related_field in cls.get_related_field_names():
        if hasattr(shopify_resource, related_field):
            defaults[related_field + '_id'] = getattr(getattr(
                shopify_resource, related_field), 'id')
        related_field = related_field + '_id'
        if hasattr(shopify_resource, related_field):
            defaults[related_field] = getattr(shopify_resource, related_field)
    return defaults


def p_proc_return(t):
    """proc_return : type_specifier
                   | VOID"""


def eventHandler(eventSource, peerId, channel, variableName, value):
    """event handler, unused"""
    pass


@staticmethod
def _pack_call(func, args, kwargs):
    """Pack the function args and key words into tuple

        :param func func:
        :param *args args:
        :param **kwargs kwargs:
        :returns: tuple

        """
    return func, args, kwargs


@classmethod
def from_credentials(cls, device_id, api_key):
    """
        Initializes the API with credentials only and uses the default settings for everything else.

        :param device_id:   The id of the device that the API is trying to connect to.
        :param api_key:     The given API key needed to connect to the server.
        :type device_id: str
        :type api_key: str
        """
    return cls({'deviceId': device_id, 'apiKey': api_key})


def popitem():
    """remove and return some (key, value) pair as a
        2-tuple; but raise KeyError if mapping is empty"""


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

        :param DeviceDeleteOnUnlinkSuccessDetails val:
        :rtype: EventDetails
        """
    return cls('device_delete_on_unlink_success_details', val)


def p_condition(p):
    """
    condition : DLT_MASK expr newlines
    """
    p[0] = p[1], p[2]


def make_di_block(dec, inc):
    """
    Some pmag.py and ipmag.py functions require or will take a list of unit
    vectors [dec,inc,1.] as input. This function takes declination and
    inclination data and make it into such a nest list of lists.

    Parameters
    -----------
    dec : list of declinations
    inc : list of inclinations

    Returns
    -----------
    di_block : nested list of declination, inclination lists

    Example
    -----------
    >>> decs = [180.3, 179.2, 177.2]
    >>> incs = [12.1, 13.7, 11.9]
    >>> ipmag.make_di_block(decs,incs)
    [[180.3, 12.1, 1.0], [179.2, 13.7, 1.0], [177.2, 11.9, 1.0]]
    """
    di_block = []
    for n in range(0, len(dec)):
        di_block.append([dec[n], inc[n], 1.0])
    return di_block


def common_prefix(strings=None):
    """ Find the longest string that is a prefix of all the strings.

    >>> common_prefix(['hello_bob','hello_jane','hello_dan'])
    'hello_'

    >>> common_prefix(['joe','george'])
    ''

    >>> common_prefix(['joe','jerry'])
    'j'

    >>> common_prefix([])
    ''

    """
    if strings is None:
        return ''
    if len(strings) == 0:
        return ''
    prefix = strings[0]
    for s in strings:
        if len(s) < len(prefix):
            prefix = prefix[:len(s)]
        if not prefix:
            return ''
        for i in range(len(prefix)):
            if prefix[i] != s[i]:
                prefix = prefix[:i]
                break
    return prefix


def km_miles(kilometers):
    """Usage: Convert kilometers to miles"""
    return kilometers / 1.609


def clear():
    """
    @api {post} /map/poihistory/clear 清空历史
    @apiVersion 1.0.0
    @apiGroup History
    @apiDescription  清空历史

    @apiParam (Headers) {String} token 令牌
    @apiParam (Headers) {String} device_token 设备令牌
    @apiParam (Headers) {String} content_type 内容类型
    @apiParam (Headers) {String} timestamp 时间戳
    @apiParam (Headers) {String} location 经纬度

    @apiSuccess (Success) {String} data 成功标识

    @apiSuccessExample {json} Success-Response:
    {
        "data": "Success.",
        "req_id": "r_cf9f3d0170b142ffb5bc2b0bcea97501",
        "err_resp": {
            "code": "0",
            "msg": null
        }
    }
    """


@staticmethod
def _size_coverter(s):
    """Converts size string into megabytes

        Parameters
        ----------
        s : str
            The size string can be '30KB', '20MB' or '1GB'

        Returns
        -------
        float
            With the size in bytes

        """
    if s.upper().endswith('KB'):
        return float(s.rstrip('KB')) / 1024
    elif s.upper().endswith(' B'):
        return float(s.rstrip('B')) / 1024 / 1024
    elif s.upper().endswith('MB'):
        return float(s.rstrip('MB'))
    elif s.upper().endswith('GB'):
        return float(s.rstrip('GB')) * 1024
    elif s.upper().endswith('TB'):
        return float(s.rstrip('TB')) * 1024 * 1024
    else:
        return float(s)


@classmethod
def handle_cursor(cls, cursor, query, session):
    """Handle a live cursor between the execute and fetchall calls

        The flow works without this method doing anything, but it allows
        for handling the cursor and updating progress information in the
        query object"""
    pass


def make_paths_relative():
    """Make all paths to external files relative to current .blend

    """
    pass


def get_command(tool_xml):
    """Get command XML element from supplied XML root."""
    root = tool_xml.getroot()
    commands = root.findall('command')
    command = None
    if len(commands) == 1:
        command = commands[0]
    return command


def posix_string(s):
    """Return string in lower case with spaces and dashes as underscores

    Args
    ----
    s: str
        string to modify

    Returns
    -------
    s_mod: str
        string with ` ` and `-` replaced with `_`
    """
    return s.lower().replace(' ', '_').replace('-', '_')


def _full_class_name(obj):
    """
    Returns the full name of the class of the given object

    :param obj: Any Python object
    :return: The full name of the class of the object (if possible)
    """
    module = obj.__class__.__module__
    if module is None or module == str.__class__.__module__:
        return obj.__class__.__name__
    return module + '.' + obj.__class__.__name__


def before_epochs(harn):
    """
        custom callback run only once before all (train/vali/test) epochs.
        """
    pass


def get_env(name, current=True):
    """
    Return HKCU/HKLM environment variable name and value

    @param      name        name to look for
    @param      current     switch between *HKEY_CURRENT_USER* (True) and *HKEY_LOCAL_MACHINE* (False)
    @return                 tuple (see below)

    For example, get_user_env('PATH') may returns::

        ('Path', u'C:\\Program Files\\Intel\\WiFi\\bin\\')
    """
    import winreg
    root = winreg.HKEY_CURRENT_USER if current else winreg.HKEY_LOCAL_MACHINE
    key = winreg.OpenKey(root, 'Environment')
    for index in range(0, winreg.QueryInfoKey(key)[1]):
        try:
            value = winreg.EnumValue(key, index)
            if value[0].lower() == name.lower():
                return value[0], value[1]
        except Exception:
            break


def get_total_vulnerabilities(output_list):
    """Get total vulnerabilities on all checks."""
    return sum(1 for output in output_list for vuln in output.get(
        'vulnerabilities', []))


def slice_disjoint(arr):
    """
    Returns an array of disjoint indices from a bool array
    :param arr: and array of bools
    """
    arr = arr.nonzero()[0]
    slices = []
    start_slice = arr[0]
    counter = 0
    for i in range(len(arr) - 1):
        if arr[i + 1] > arr[i] + 1:
            end_slice = arr[i]
            slices.append([start_slice, end_slice])
            start_slice = arr[i + 1]
            counter += 1
    if counter == 0:
        return [[arr[0], arr[-1]]]
    if end_slice != arr[-1]:
        slices.append([start_slice, arr[-1]])
    return slices


def subslice(inner, outer, section):
    """helper for rediff  outer is a slice (2-tuple, not an official python slice) in global coordinates  inner is a slice (2-tuple) on that slice  returns the result of sub-slicing outer by inner"""
    if section == 'head':
        return outer[0], outer[0] + inner[0]
    elif section == 'tail':
        return outer[0] + inner[1], outer[1]
    elif section == 'middle':
        return outer[0] + inner[0], outer[0] + inner[1]
    else:
        raise ValueError('section val %s not one of (head,middle,tail)' %
            section)


def eight_decimal_places(amount, format='str'):
    """
    >>> eight_decimal_places(3.12345678912345)
    "3.12345679"
    >>> eight_decimal_places("3.12345678912345")
    "3.12345679"
    >>> eight_decimal_places(3.12345678912345, format='float')
    3.12345679
    >>> eight_decimal_places("3.12345678912345", format='float')
    3.12345679
    """
    if type(amount) == str:
        return amount
    if format == 'str':
        return '%.8f' % amount
    if format == 'float':
        return float('%.8f' % amount)


def pyramid_tm(config):
    """Add beaker includeme in pyramid configuration

    :param config: Pyramid configurator instance
    """
    config.include('pyramid_tm')


def pearsoncc(x, y):
    """ Compute Pearson Correlation Coefficient. """
    x = (x - x.mean(0)) / x.std(0)
    y = (y - y.mean(0)) / y.std(0)
    return (x * y).mean()


def scale_kappa_REALtoSI(temp, volume, timestep):
    """
    Conversion factor for the thermal conductivity from REAL LAMMPS units to SI units.
    INPUT:
    temp      =  temperature [ K ]
    volume    =  cell volume [ A^3 ]
    timestep  =  integration time step [ fs ]
    """
    kB = 1.3806504
    NA = 6.02214
    massunit = 1.660538921
    charge = 1.6021765
    return (4184.0 / NA / temp) ** 2 / kB / volume * timestep * 100.0


def _string_from_json(value, _):
    """NOOP string -> string coercion"""
    return value


def replace_pattern(df, column: str, *, pat: str, repl: str, new_column:
    str=None, case: bool=True, regex: bool=True):
    """
    Replace occurrences of pattern/regex in `column` with some other string
    See [pandas doc](
    https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.replace.html) for more information

    ---

    ### Parameters

    *mandatory :*
    - `column` (*str*): the column
    - `pat` (*str*): character sequence or regular expression
    - `repl` (*str*): replacement string

    *optional :*
    - `new_column` (*str*): the destination column (if not set, `column` will be used)
    - `case` (*boolean*): if true, case sensitive.
    - `regex` (*boolean*): default true
    """
    new_column = new_column or column
    df.loc[:, (new_column)] = df[column].str.replace(pat, repl, case=case,
        regex=regex)
    return df


def validate_bool_kwarg(value, arg_name):
    """ Ensures that argument passed in arg_name is of type bool. """
    if not (isinstance(value, bool) or value is None):
        raise ValueError(
            'For argument "{}" expected type bool, received type {}.'.
            format(arg_name, type(value).__name__))
    return value


def _make_divisible(v, divisor, min_value=None):
    """
    This function is taken from the original tf repo.
    It ensures that all layers have a channel number that is divisible by 8
    It can be seen here:
    https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
    :param v:
    :param divisor:
    :param min_value:
    :return:
    """
    if min_value is None:
        min_value = divisor
    new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
    if new_v < 0.9 * v:
        new_v += divisor
    return new_v


@classmethod
def get_or_create(cls, store, **kwargs):
    """Get the object from the database that matches the given criteria, and if
        it doesn't exist, create a new object, with the properties given already
        set.

        The properties given ideally should be the primary key, or a candidate
        key (unique values).

        :returns: an object matching the query or a newly created one if a
          matching one couldn't be found.
        """
    obj = store.find(cls, **kwargs).one()
    if obj is not None:
        return obj
    obj = cls(store=store)
    for key, value in kwargs.items():
        setattr(obj, key, value)
    return obj


def p_newlines(p):
    """ newlines : NEWLINE
                 | newlines NEWLINE """
    pass


def getId():
    """Return the id of the opaque item.
        """


@classmethod
def commit(cls, client=None):
    """Commit everything from datapoints via the client.

        :param client: InfluxDBClient instance for writing points to InfluxDB.
        :attention: any provided client will supersede the class client.
        :return: result of client.write_points.
        """
    if not client:
        client = cls._client
    rtn = client.write_points(cls._json_body_(), time_precision=cls.
        _time_precision, retention_policy=cls._retention_policy)
    cls._reset_()
    return rtn


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 fromqimage(im):
    """Creates an image instance from a QImage image"""
    from . import ImageQt
    if not ImageQt.qt_is_installed:
        raise ImportError('Qt bindings are not installed')
    return ImageQt.fromqimage(im)


def build_template(data):
    """
    Build and return an addressbook file template
    """
    template = (
        '# abook addressbook file\n\n[format]\nprogram=abook\nversion=0.6.1\n\n'
        )
    for index, entry in enumerate(data):
        template += (
            f"\n[{index}]\nname={entry['name']}\nemail={','.join(entry['email'])}\n"
            )
        if entry['notes']:
            template += f"notes={entry['notes']}\n"
        if entry['custom1']:
            template += f"custom1={entry['custom1']}\n"
    template += '\n'
    return template


def calculate_aerodynamic_resistances(f2, velocities):
    """
    Calculates the aerodynamic resistances of the vehicle [N].

    :param f2:
        As used in the dyno and defined by respective guidelines [N/(km/h)^2].
    :type f2: float

    :param velocities:
        Velocity vector [km/h].
    :type velocities: numpy.array | float

    :return:
        Aerodynamic resistance vector [N].
    :rtype: numpy.array | float
    """
    return f2 * velocities ** 2


def missing_value():
    """
    Returns the value that represents missing values in Weka (NaN).

    :return: missing value
    :rtype: float
    """
    return float('NaN')


@classmethod
def create(cls, class_name, **attributes):
    """
        根据参数创建一个 leancloud.Object 的子类的实例化对象

        :param class_name: 子类名称
        :type class_name: string_types
        :param attributes: 对象属性
        :return: 派生子类的实例
        :rtype: Object
        """
    object_class = cls.extend(class_name)
    return object_class(**attributes)


@staticmethod
def endDiagram(*args):
    """ Called last uring the render to finalise a diagram """
    return '@enduml'


def set_spow_enable(enable):
    """
    Sets *Colour* safe / symmetrical power function enabled state.

    Parameters
    ----------
    enable : bool
        Whether to enable *Colour* safe / symmetrical power function.

    Examples
    --------
    >>> with spow_enable(is_spow_enabled()):
    ...     print(is_spow_enabled())
    ...     set_spow_enable(False)
    ...     print(is_spow_enabled())
    True
    False
    """
    global _SPOW_ENABLED
    _SPOW_ENABLED = enable


def verbose_name(_id, preferred_type=None):
    """
    If the name is known, print the name and a useful numeric ID (which hints
    at type).  Otherwise, just print the numeric ID.
    """
    if _id.has_name():
        return u'{} ({})'.format(_id, _id.numeric_str(preferred_type))
    else:
        return u'{}'.format(_id.numeric_str(preferred_type))


def _trimchunk(revlog, revs, startidx, endidx=None):
    """returns revs[startidx:endidx] without empty trailing revs

    Doctest Setup
    >>> revlog = _testrevlog([
    ...  5,  #0
    ...  10, #1
    ...  12, #2
    ...  12, #3 (empty)
    ...  17, #4
    ...  21, #5
    ...  21, #6 (empty)
    ... ])

    Contiguous cases:
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 0)
    [0, 1, 2, 3, 4, 5]
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 0, 5)
    [0, 1, 2, 3, 4]
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 0, 4)
    [0, 1, 2]
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 2, 4)
    [2]
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 3)
    [3, 4, 5]
    >>> _trimchunk(revlog, [0, 1, 2, 3, 4, 5, 6], 3, 5)
    [3, 4]

    Discontiguous cases:
    >>> _trimchunk(revlog, [1, 3, 5, 6], 0)
    [1, 3, 5]
    >>> _trimchunk(revlog, [1, 3, 5, 6], 0, 2)
    [1]
    >>> _trimchunk(revlog, [1, 3, 5, 6], 1, 3)
    [3, 5]
    >>> _trimchunk(revlog, [1, 3, 5, 6], 1)
    [3, 5]
    """
    length = revlog.length
    if endidx is None:
        endidx = len(revs)
    if revs[endidx - 1] < len(revlog):
        while endidx > 1 and endidx > startidx and length(revs[endidx - 1]
            ) == 0:
            endidx -= 1
    return revs[startidx:endidx]


def day2dekad(day):
    """Returns the dekad of a day.

    Parameters
    ----------
    day : int
        Day of the date.

    Returns
    -------
    dekad : int
        Number of the dekad in a month.
    """
    if day < 11:
        dekad = 1
    elif day > 10 and day < 21:
        dekad = 2
    else:
        dekad = 3
    return dekad


def readslicestring(slicestring, lenobject):
    """
    return slice parameters: start, end, step  from string input

    lenobject  is the length of the object to be sliced
    """
    start, end, step = 0, 1, 1
    sl = slicestring.split(':')
    if len(sl) >= 2:
        if sl[0] == '':
            start = 0
        else:
            start = int(sl[0])
        if sl[1] == '':
            end = lenobject
        else:
            end = int(sl[1])
        if len(sl) == 3:
            if sl[2] == '':
                step = 1
            else:
                step = int(sl[2])
                if step <= 0:
                    raise ValueError('negative or null step is not handled')
    return start, end, step


@classmethod
def get_attrs_processor_param(cls):
    """ Get param for attrs processor.

    :return: Dict.
    """
    return {}


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


@classmethod
def init_from_dict(cls, dict_obj):
    """Construct a model instance from a dictionary.

        This serves as a 2nd constructor

        :param dict_obj: dictionary object
        :returns o
        """
    o = cls('')
    o.domain = dict_obj.get('domain').lower().strip()
    o.protocol = dict_obj.get('protocol', 'http')
    if o.protocol == 'https':
        o.certificate = dict_obj.get('certificate', None)
    return o


def _fast_isserli(powerlist, Sigma_x):
    """
	Get higher order mixed centralized moments of a multivariate gaussian using isserlis theorem
	http://en.wikipedia.org/wiki/Isserlis%27_theorem

	This is optimized by assuming the x_i to be independent

	:math:`E[(x-\\mu_x)^{k_x} (y-\\mu_y)^{k_y}] = E[(x-\\mu_x)^{k_x}] \\cdot E [(y-\\mu_y)^{k_y}]` => no need for isserli

	:param powerlist: list of powers of the random variables of the multivariate normal
	:param Sigma_x: The covariance matrix
	:return:
	"""
    from scipy.misc import factorial2
    if powerlist.sum() % 2 != 0:
        return 0
    for power in powerlist:
        if power % 2 != 0:
            return 0
    part = 1.0
    for i, power in enumerate(powerlist):
        part *= Sigma_x[i][i] ** (power / 2)
        part *= factorial2(power - 1, exact=True)
    return part


def encrypt_pwd(toyz_settings, pwd):
    """
    Use the passlib module to create a hash for the given password.

    Parameters
        - toyz_settings ( :py:class:`toyz.utils.core.ToyzSettings` ): Settings for the
          current application
        - pwd (*string* ): password the user has entered

    Returns
        - pwd_hash (*string* ): Password hash to be stored for the given password. If passwords
          are not encrypted, this will just return the ``pwd`` passed to the function.
    """
    from passlib.context import CryptContext
    pwd_context = CryptContext(**toyz_settings.security.pwd_context)
    return pwd_context.encrypt(pwd)


def c_array(ctype, values):
    """Convert a Python array to C array."""
    return (ctype * len(values))(*values)