def showOperandLines(rh):
    """
    Produce help output related to operands.

    Input:
       Request Handle
    """
    if rh.function == 'HELP':
        rh.printLn('N', '  For the ChangeVM function:')
    else:
        rh.printLn('N', 'Sub-Functions(s):')
    rh.printLn('N', '      add3390       - Add a 3390 (ECKD) disk ' +
        "to a virtual machine's directory")
    rh.printLn('N', '                      entry.')
    rh.printLn('N', '      add9336       - Add a 9336 (FBA) disk ' +
        "to virtual machine's directory")
    rh.printLn('N', '                      entry.')
    rh.printLn('N', '      aemod         - Sends an activation ' +
        'engine script to the managed virtual')
    rh.printLn('N', '                      machine.')
    rh.printLn('N', '      help          - Displays this help ' +
        'information.')
    rh.printLn('N', '      ipl           - Sets the IPL statement in ' +
        "the virtual machine's")
    rh.printLn('N', '                      directory entry.')
    rh.printLn('N', '      loaddev       - Sets the LOADDEV statement ' +
        "in the virtual machine's")
    rh.printLn('N', '                      directory entry.')
    rh.printLn('N', '      punchfile     - Punch a file to a virtual ' +
        'reader of the specified')
    rh.printLn('N', '                      virtual machine.')
    rh.printLn('N', '      purgerdr      - Purges the reader ' +
        'belonging to the virtual machine.')
    rh.printLn('N', '      removedisk    - ' +
        'Remove an mdisk from a virtual machine.')
    rh.printLn('N', '      removeIPL     - ' +
        "Remove an IPL from a virtual machine's directory entry.")
    rh.printLn('N', '      version       - ' +
        'show the version of the power function')
    if rh.subfunction != '':
        rh.printLn('N', 'Operand(s):')
        rh.printLn('N', '      -addr <addr>          - ' +
            'Specifies the logical block address of the')
        rh.printLn('N', '                              ' + 'boot record.')
        rh.printLn('N', '      <addrOrNSS>           - ' +
            'Specifies the virtual address or NSS name')
        rh.printLn('N', '                              to IPL.')
        rh.printLn('N', '      <aeScript>            - ' +
            'aeScript is the fully qualified file')
        rh.printLn('N', '                              ' +
            'specification of the script to be sent')
        rh.printLn('N', '      --boot <boot>         - ' +
            'Boot program number')
        rh.printLn('N', '      --class <class>       - ' +
            'The class is optional and specifies the spool')
        rh.printLn('N', '                              ' +
            'class for the reader file.')
        rh.printLn('N', '      <diskPool>            - ' +
            'Specifies the directory manager disk pool to')
        rh.printLn('N', '                              ' +
            'use to obtain the disk.')
        rh.printLn('N', '      <diskSize3390>        - ' +
            'Specifies the size of the ECKD minidisk.  ')
        rh.printLn('N', '      <diskSize9336>        - ' +
            'Specifies the size of the FBA type minidisk.')
        rh.printLn('N', '      <file>                - ' +
            'File to punch to the target system.')
        rh.printLn('N', '      --filesystem <fsType> - ' +
            'Specifies type of filesystem to be created on')
        rh.printLn('N', '                              the minidisk.')
        rh.printLn('N', '      --invparms <invParms> - ' +
            'Specifies the parameters to be specified in the')
        rh.printLn('N', '                              ' +
            'invocation script to call the aeScript.')
        rh.printLn('N', '      --loadparms <loadParms> - ' +
            'Specifies a 1 to 8-character load parameter that')
        rh.printLn('N', '                                ' +
            "is used by the IPL'd system.")
        rh.printLn('N', '      --lun <lun>           - ' +
            'One to eight-byte logical unit number of the')
        rh.printLn('N', '                              FCP-I/O device.')
        rh.printLn('N', '      --mode <mode>         - ' +
            'Specifies the access mode for the minidisk.')
        rh.printLn('N', '      --multipw <multi_pw>  - ' +
            'Specifies the password that allows sharing the')
        rh.printLn('N', '                              ' +
            'minidisk in multiple-write mode.')
        rh.printLn('N', '      --parms <parmString>  - ' +
            'Specifies a parameter string to pass to the')
        rh.printLn('N', '                              ' +
            'virtual machine in general-purpose registers at')
        rh.printLn('N', '                              ' +
            "user's the completion of the IPL.")
        rh.printLn('N', '      --readpw <read_pw>    - ' +
            'Specifies the password that allows sharing the')
        rh.printLn('N', '                              ' +
            'minidisk in read mode.')
        rh.printLn('N', '      --scpdata <scpdata>   - ' +
            'Provides the SCP data information.')
        rh.printLn('N', '      --scpdatatype <scpdatatype> - ' +
            'Specifies whether the scp data is in hex,')
        rh.printLn('N', '                              ' +
            'EBCDIC, or should be deleted.')
        rh.printLn('N', '      <userid>              - ' +
            'Userid of the target virtual machine.')
        rh.printLn('N', '      <vAddr>               - ' +
            'Virtual address of the device.')
        rh.printLn('N', '      --writepw <write_pw>  - ' +
            'Specifies is the password that allows sharing')
        rh.printLn('N', '                              ' +
            'the minidisk in write mode.')
        rh.printLn('N', '      --wwpn <wwpn>         - ' +
            'The world-wide port number.')
    return


def reverse_order(order_array):
    """
    Returns the effective 'inverse' of the given order array, that is by
    returning the order array that would be needed to re-arrange back to the
    correct order.
    """
    if not hasattr(order_array, '__iter__'):
        raise TypeError('Non-iterable type passed as order_array argument.')
    length = len(order_array)
    new_array = [None] * length
    for index, replace in enumerate(order_array):
        new_array[replace] = index
    return new_array


def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
    """Read MetaMorph STK UIC2Tag from file and return as dict."""
    assert dtype == '2I' and byteorder == '<'
    values = fh.read_array('<u4', 6 * planecount).reshape(planecount, 6)
    return {'ZDistance': values[:, (0)] / values[:, (1)], 'DateCreated':
        values[:, (2)], 'TimeCreated': values[:, (3)], 'DateModified':
        values[:, (4)], 'TimeModified': values[:, (5)]}


def flatten(data=None, name=None, attr=None, out=None, **kwargs):
    """Flattens the input array into a 2-D array by collapsing the higher dimensions.
    .. note:: `Flatten` is deprecated. Use `flatten` instead.
    For an input array with shape ``(d1, d2, ..., dk)``, `flatten` operation reshapes
    the input array into an output array of shape ``(d1, d2*...*dk)``.
    Note that the behavior of this function is different from numpy.ndarray.flatten,
    which behaves similar to mxnet.ndarray.reshape((-1,)).
    Example::
        x = [[
            [1,2,3],
            [4,5,6],
            [7,8,9]
        ],
        [    [1,2,3],
            [4,5,6],
            [7,8,9]
        ]],
        flatten(x) = [[ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.],
           [ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]]

    Defined in src/operator/tensor/matrix_op.cc:L250

    Parameters
    ----------
    data : Symbol
        Input array.

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

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


def _show_mpl_pos(exec_name, trajectory_list, **kwargs):
    """
    Produces a matplotlib plot of the trajectory
    """
    for traj in trajectory_list:
        traj.show_mpl_pos(**kwargs)


def getParent():
    """Get the portlet parent of the current context.

        This is used to aggregate portlets by walking up the content hierarchy.

        This should be adaptable to IPortletContext. If there is no portlet
        parent (e.g. this is the site root), return None.
        """


def str2float(inp):
    """
    Convert a set number of columns to float, or returns None.

    Parameters
    ----------
    inp : str
        string with a list of floats in it

    Returns
    -------
    output : float
        all columns returned as floats
    """
    if inp.strip() == '':
        return None
    return float(inp)


def echo_command(*inp):
    """Print all the words that were passed on the command line

	This is just a simple echo command.
	"""
    print(' '.join(inp))


def create_D_matrix(cost_matrix, pi_vector_new):
    """
    According to the paper, transofrmation into the D matrix significantly improves the approximation.
    D[i][j] = cost_matrix[i][j] + pi[i]+pi[j], where pi is a vector.
    pi^(k+1) = pi^k + t^k*v^k

    The aim is now to find a transformation C->D, given by the vector pi = (pi1, pi2, ..., pin), that maximizes the lower bound
    w(pi)=L(Tn) - 2*sum(pii).
    Args:
        cost_matrix (2d np. array):

    Returns:
    Transformed cost matrix into D_matrix (2d np.array).
    """
    nodes_count = len(cost_matrix)
    for row in range(nodes_count):
        for col in range(nodes_count):
            cost_matrix[row][col] = cost_matrix[row][col] + pi_vector_new[row
                ] + pi_vector_new[col]
    return cost_matrix


def get_highest_occupied_band(bands, threshold=0.005):
    """Retun the index of the highest-occupied molecular orbital.

    The expected structure of the bands node is the following:

        * an array called `occupations`
        * with 3 dimensions if spin polarized, otherwise 2 dimensions
        * dimensions loop over, spin channel, kpoints, bands

    .. note::

        The threshold is used both as a limit below which a band is considered as unoccupied as well as a measure of
        numerical noise in the occupancies. The first band to have an occupancy below the threshold at all kpoints is
        marked as the LUMO. All subsequent bands are then expected to have an occupation that is less than twice the
        threshold. The reason for the factor two is that in the worst case when the LUMO has an occupation exactly equal
        to the threshold and a subsequent has twice that value, we can still consider that as not to break the
        requirement of all bands above the LUMO to be empty. It can be considered as having the exact same value (equal
        to the threshold) plus an numerical error also equal to the threshold.

    :param bands: the `BandsData` node
    :param threshold: raise a `ValueError` if the last band has an occupation above this threshold at any k-point
    :raises ValueError: if `bands` is not a `BandsData` node
    :raises ValueError: if `bands` does not contain the array `occupations`
    :raises ValueError: if `occupations` array has an invalid shape
    :raises ValueError: if any occupation above LUMO exceeds `2 * threshold`
    :raises ValueError: if the last band has an occupation above the threshold
    """
    from numpy import shape
    from aiida.orm import BandsData
    if not isinstance(bands, BandsData):
        raise ValueError('bands should be a `{}` node'.format(BandsData.
            __name__))
    try:
        occupations = bands.get_array('occupations')
    except KeyError:
        raise ValueError('BandsData does not contain a `occupations` array')
    lumo_indices = []
    if len(shape(occupations)) == 3:
        spin_channels = occupations
    elif len(shape(occupations)) == 2:
        spin_channels = [occupations]
    else:
        raise ValueError('invalid shape for `occupations` array')
    for l, spin_channel in enumerate(spin_channels):
        for k, kpoint in enumerate(spin_channel):
            lumo_index = None
            lumo_occupation = None
            for n, occupation in enumerate(kpoint):
                if lumo_index is not None:
                    if occupation > 2 * threshold:
                        warning_args = [occupation, n, lumo_occupation,
                            lumo_index, l, k]
                        raise ValueError(
                            'Occupation of {} at n={} after lumo lkn<{},{},{}>'
                            .format(*warning_args))
                elif occupation < threshold:
                    lumo_index = n
                    lumo_occupation = occupation
                    lumo_indices.append(lumo_index)
            else:
                if kpoint[-1] >= threshold:
                    warning_args = [kpoint[-1], l, k, len(kpoint)]
                    raise ValueError(
                        'Occupation of {} at last band lkn<{},{},{}>'.
                        format(*warning_args))
    homo = max(lumo_indices)
    return homo


def dbh_office(path, contenttype, extension, roottag, nsurl):
    """ Generic Web Page Handler - Returns image_generic for Web browser supported images """
    if extension.lower() in ['odt', 'doc', 'docx', 'ods', 'xls', 'xlst',
        'ppt', 'odp', 'pptx']:
        return 'db_office_viewer'
    else:
        return False


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

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

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


def upgrade():
    """Upgrade database."""


def prepend(string, prefix):
    """Append something to the beginning of another string.

    Parameters
    ----------
    string : str
        String to prepend to.
    prefix : str
        String to add to the beginning.

    Returns
    -------
    str
        String with the addition to the beginning.

    Notes
    -----
    This function deals with empty inputs, and returns an empty string in that case.
    """
    return prefix + string if string else string


@classmethod
def parse_store(cls, storefile):
    """Parse the store."""
    if not hasattr(storefile, 'read'):
        storefile = open(storefile, 'rb')
    return cls.parse_simple_csv(storefile.read(), storefile)


@classmethod
def from_dictionary(cls, args):
    """Construct settings from dictionary containing parameter values.

        Construct an instance of RbfoptSettings by looking up the value
        of the parameters from a given dictionary. The dictionary must
        contain only parameter values in the form args['name'] =
        value. Anything else present in the dictionary will raise an
        exception.

        Parameters
        ----------

        args : Dict[string]
            A dictionary containing the values of the parameters in a
            format args['name'] = value.

        Returns
        -------
        RbfoptSettings
            An instance of the object of the class.

        Raises
        ------
        ValueError
            If the dictionary contains invalid parameters.
        """
    valid_params = vars(cls())
    for param in args.keys():
        if param not in valid_params:
            raise ValueError('Parameter name {:s}'.format(param) +
                'not recognized')
    return cls(**args)


def argsort(seq):
    """ Returns a list of indices that would sort a list.

    Parameters
    ----------
    seq: List
        The list.

    Returns
    -------
    List[int]
        The list of indices that would sort the given list ``seq``.

    Notes
    -----
    If the returned list of indices can be a NumPy array, use `numpy.lexsort`
    instead. If the given list ``seq`` is a NumPy array, use `numpy.argsort`
    instead.

    """
    return sorted(range(len(seq)), key=seq.__getitem__)


@classmethod
def table_name_col(cls):
    """
        Returns the name of the metadata column used to store the feature table
        name.
        """
    return 'f_table_name'


def generatePparseParams(rawfilepath, outputpath, isolationWindow, coElute=0):
    """Generates a string containing the parameters for a pParse parameter file
    but doesn't write any file yet.

    :param rawfilepath: location of the thermo ".raw" file
    :param outputpath: path to the output directory of pParse
    :param isolationWindow: MSn isolation window that was used for the
        aquisition of the specified thermo raw file
    :param coElute: 0 or 1, see "[Advanced Options]" below

    :returns: string containing pParse parameters

    .. note:
        # pParse.para params template
        # For help: mail to tuhuijun@ict.ac.cn
        # Time: 2014.12.08

        [Basic Options]
        datapath = C:iledirectoryilename
        logfilepath = C:iledirectory
        outputpath = C:iledirectory

        [Advanced Options]
        co-elute = 1
        # 0, output single precursor for single scan;
        # 1, output all co-eluted precursors.
        input_format = raw
        # raw / ms1
        isolation_width = 1.6
        # 2 / 2.5 / 3 / 4
        mars_threshold = -0.5
        ipv_file = .\\IPV.txt
        trainingset = EmptyPath

        [Internal Switches]
        output_mars_y = 0
        delete_msn = 0
        output_mgf = 1
        output_pf = 1
        debug_mode = 0
        check_activationcenter = 1
        output_all_mars_y = 0
        rewrite_files = 0
        export_unchecked_mono = 0
        cut_similiar_mono = 1
        mars_model = 4
        output_trainingdata = 0
    """
    output = str()
    output = '\n'.join([output, ' = '.join(['datapath', rawfilepath])])
    output = '\n'.join([output, ' = '.join(['logfilepath', outputpath])])
    output = '\n'.join([output, ' = '.join(['outputpath', outputpath])])
    output = '\n'.join([output, ' = '.join(['co-elute', str(coElute)])])
    output = '\n'.join([output, ' = '.join(['input_format', 'raw'])])
    output = '\n'.join([output, ' = '.join(['isolation_width', str(
        isolationWindow)])])
    output = '\n'.join([output, ' = '.join(['mars_threshold', '-0.5'])])
    output = '\n'.join([output, ' = '.join(['ipv_file', '.\\IPV.txt'])])
    output = '\n'.join([output, ' = '.join(['trainingset', 'EmptyPath'])])
    output = '\n'.join([output, ' = '.join(['output_mars_y', '0'])])
    output = '\n'.join([output, ' = '.join(['delete_msn', '0'])])
    output = '\n'.join([output, ' = '.join(['output_mgf', '1'])])
    output = '\n'.join([output, ' = '.join(['output_pf', '0'])])
    output = '\n'.join([output, ' = '.join(['debug_mode', '0'])])
    output = '\n'.join([output, ' = '.join(['check_activationcenter', '1'])])
    output = '\n'.join([output, ' = '.join(['output_all_mars_y', '0'])])
    output = '\n'.join([output, ' = '.join(['rewrite_files', '0'])])
    output = '\n'.join([output, ' = '.join(['export_unchecked_mono', '0'])])
    output = '\n'.join([output, ' = '.join(['cut_similiar_mono', '1'])])
    output = '\n'.join([output, ' = '.join(['mars_model', '4'])])
    output = '\n'.join([output, ' = '.join(['output_trainingdata', '0'])])
    return output


def getId():
    """Return item unique identifier attribute value"""


def unicode_is_ascii(u_string):
    """Determine if unicode string only contains ASCII characters.

    :param str u_string: unicode string to check. Must be unicode
        and not Python 2 `str`.
    :rtype: bool
    """
    assert isinstance(u_string, str)
    try:
        u_string.encode('ascii')
        return True
    except UnicodeEncodeError:
        return False


def nodoc(obj):
    """Add a flag which autodoc can use to decide whether to skip a member."""
    obj.nodoc = True
    return obj


def addOutputLevel(parser):
    """
    Add options to get more or less messages.
    """
    import logging
    parser.add_option('--verbose', action='store_const', const=logging.INFO,
        dest='log_level', help='print more information')
    parser.add_option('--debug', action='store_const', const=logging.DEBUG,
        dest='log_level', help='print debug messages')
    parser.add_option('--quiet', action='store_const', const=logging.
        WARNING, dest='log_level', help='print only warning messages (default)'
        )
    parser.set_defaults(log_level=logging.WARNING)
    return parser


@classmethod
def by_pid(cls, data_dir, pid):
    """Retrieves PID file from given directory by PID value"""
    for candidate_pid_file in cls.all(data_dir):
        if candidate_pid_file.pid == pid:
            pid_file = candidate_pid_file
            break
    else:
        pid_file = None
    return pid_file


def enter(s, blk, rtlir):
    """Entry point for RTLIR generation."""
    s.blk = blk
    s.globals = blk.__globals__
    s.closure = {}
    for i, var in enumerate(blk.__code__.co_freevars):
        try:
            s.closure[var] = blk.__closure__[i].cell_contents
        except ValueError:
            pass
    return s.visit(rtlir)


@staticmethod
def _add_property(obj, key, stix_value, group=False):
    """
        Add stix_value to dictionary based on the input key, the key can be '.'-separated path to inner object

        :param obj: the dictionary we are adding our key to
        :param key: the key to add
        :param stix_value: the STIX value translated from the input object
        """
    split_key = key.split('.')
    child_obj = obj
    parent_props = split_key[0:-1]
    for prop in parent_props:
        if prop not in child_obj:
            child_obj[prop] = {}
        child_obj = child_obj[prop]
    if split_key[-1] not in child_obj.keys():
        child_obj[split_key[-1]] = stix_value
    elif group is True:
        if isinstance(child_obj[split_key[-1]], list):
            child_obj[split_key[-1]].extend(stix_value)


def p_plugin_name(p):
    """plugin_name : IDENTIFIER"""
    p[0] = p[1]


def is_null(value):
    """ Check if a value is equivalent to null in Dynamo """
    return value is None or isinstance(value, (set, frozenset)) and len(value
        ) == 0


def check_step_motion_from_dissonance(movement: int,
    is_last_element_consonant: bool, **kwargs) ->bool:
    """
    Check that there is step motion from a dissonating element.

    Note that this rule prohibits double neighboring tones.

    :param movement:
        melodic interval (in scale degrees) for line continuation
    :param is_last_element_consonant:
        indicator whether last element of counterpoint line (not including
        a new continuation in question) forms consonance with cantus firmus
    :return:
        indicator whether a continuation is in accordance with the rule
    """
    if is_last_element_consonant:
        return True
    return movement in [-1, 1]


def assert_minimum_rank(inputs, rank: int):
    """Asserts the rank of the input is at least `rank`."""
    if inputs.ndim < rank:
        raise ValueError('Input %r must have rank >= %d' % (inputs, rank))


def unzip(listOfLists):
    """ Inverse of zip to split lists. """
    return zip(*listOfLists)


def logloss(labels, predictions):
    """
    accuracy by penalising false classifications
    """
    from sklearn.metrics import log_loss
    return log_loss(labels, predictions)


def move_after(_list, static, dynamic):
    """
    Move *static* elem. after *dynamic* elem. in list *_list*
    Both *static* and *dynamic* MUST belong to *_list*.
    :return list: return _list with moved *dynamic* elem.
    """
    _list.remove(dynamic)
    next_pos = _list.index(static) + 1
    _list.insert(next_pos, dynamic)
    return _list


def calculate_start_row_index(curr_page, nb_table_rows):
    """ Calculates row index of data that will be displayed given
        current page and number of rows in the table.

        Note:
            The first row of the table is reserved for displaying categories.

        Args:
            curr_page (int): current page number. Pages start from 1.
            nb_table_rows (int): number of rows in the table.

        Returns:
            int: data row index
    """
    if curr_page == 0:
        return 0
    return (curr_page - 1) * (nb_table_rows - 1)


def read_signature(filename, length=4):
    """ Read the signature, first length bytes, from filename."""
    with open(filename, 'rb') as file_handle:
        return file_handle.read(length)


def create_indexed_document(index_instance, model_items, action):
    """
    Creates the document that will be passed into the bulk index function.
    Either a list of serialized objects to index, or a a dictionary specifying the primary keys of items to be delete.
    """
    data = []
    if action == 'delete':
        for pk in model_items:
            data.append({'_id': str(pk), '_op_type': action})
    else:
        for doc in model_items:
            if index_instance.matches_indexing_condition(doc):
                d = index_instance.serialize_object(doc)
                pk = getattr(doc, index_instance.id_field)
                if pk is not None:
                    d['_id'] = str(pk)
                data.append(d)
    return data


def return_error(facility, message=''):
    """ Receives an error message to send to whatever facility is appropriate for a project. defaults to print. """
    if facility:
        facility(message)
    else:
        print(message)


def append_mids(mids1, mids2):
    """used when we have two lists of mids. Joins these two """
    for i in range(len(mids2[0])):
        emu = mids2[0][i]
        mid = mids2[1][i]
        if not emu in mids1[0]:
            mids1[0].append(emu)
            mids1[1].append(mid)
    return mids1


def set_basic_data(wall_out, element):
    """Set basic data of building elements.

    Parameters
    ----------
    wall_out : collection.OrderedDict
        OrderedDict for walls

    element : TEASERClass
        teaser class representation of a building element

    """
    wall_out['year_of_construction'] = element.year_of_construction
    wall_out['year_of_retrofit'] = element.year_of_retrofit
    wall_out['construction_type'] = element.construction_type
    wall_out['area'] = element.area
    wall_out['tilt'] = element.tilt
    wall_out['orientation'] = element.orientation
    wall_out['inner_radiation'] = element.inner_radiation
    wall_out['inner_convection'] = element.inner_convection
    if type(element).__name__ == 'OuterWall' or type(element
        ).__name__ == 'Rooftop' or type(element).__name__ == 'Door':
        wall_out['outer_radiation'] = element.outer_radiation
        wall_out['outer_convection'] = element.outer_convection
    elif type(element).__name__ == 'Window':
        wall_out['outer_radiation'] = element.outer_radiation
        wall_out['outer_convection'] = element.outer_convection
        wall_out['g_value'] = element.g_value
        wall_out['a_conv'] = element.a_conv
        wall_out['shading_g_total'] = element.shading_g_total
        wall_out['shading_max_irr'] = element.shading_max_irr


def start(st_reg_number):
    """Checks the number valiaty for the Minas Gerais state"""
    number_state_registration_first_digit = st_reg_number[0:3
        ] + '0' + st_reg_number[3:len(st_reg_number) - 2]
    weights_first_digit = [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
    wights_second_digit = [3, 2, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
    first_digit = st_reg_number[-2]
    second_digit = st_reg_number[-1]
    sum_first_digit = 0
    sum_second_digit = 0
    sum_result_digit = ''
    sum_end = 0
    if len(st_reg_number) != 13:
        return False
    for i in range(0, 12):
        sum_first_digit = weights_first_digit[i] * int(
            number_state_registration_first_digit[i])
        sum_result_digit = sum_result_digit + str(sum_first_digit)
    for i in range(0, len(sum_result_digit)):
        sum_end = sum_end + int(sum_result_digit[i])
    if sum_end % 10 == 0:
        check_digit_one = 0
    elif sum_end < 10:
        check_digit_one = 10 - sum_end
    elif sum_end > 10:
        check_digit_one = 10 - sum_end % 10
    if str(check_digit_one) != first_digit:
        return False
    number_state_registration_second_digit = st_reg_number + str(
        check_digit_one)
    for i in range(0, 12):
        sum_second_digit = sum_second_digit + wights_second_digit[i] * int(
            number_state_registration_second_digit[i])
    check_second_digit = 11 - sum_second_digit % 11
    if sum_second_digit == 1 or sum_second_digit == 0:
        return second_digit == '0'
    else:
        return str(check_second_digit) == second_digit


def change_frame(frame: int=0):
    """Interactively change the current frame number

    :param frame: Frame
    :type frame: int
    """
    pass


@classmethod
def deg(cls, a):
    """Degree of polynomial a (-1 if a is zero polynomial)."""
    a = cls._intern(a)
    return cls._deg(a)


def is_positive(value):
    """
    Returns True is the value is a positive number
    """
    return value > 0


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


@classmethod
def get_between(cls, outV, inV, page_num=None, per_page=None):
    """
        Return all the edges with a given label between two vertices.

        :param outV: The vertex the edge comes out of.
        :type outV: Vertex
        :param inV: The vertex the edge goes into.
        :type inV: Vertex
        :param page_num: The page number of the results
        :type page_num: int
        :param per_page: The number of results per page
        :type per_page: int
        :rtype: list

        """
    return cls._get_edges_between(out_v=outV, in_v=inV, label=cls.get_label
        (), page_num=page_num, per_page=per_page)


def getLockType():
    """ returns the lock type ('write') """


def plaintext_to_html(s):
    """
    @return: An HTML string that encodes the given plaintext string.
    In particular, special characters (such as C{'<'} and C{'&'})
    are escaped.
    @rtype: C{string}
    """
    s = s.replace('&', '&').replace('"', '"')
    s = s.replace('<', '<').replace('>', '>')
    return s


@classmethod
def cached_property(cls, icls):
    """replicate sdtlib @cached_property decorator"""
    obj = cls(icls)
    obj.is_property = True
    obj.is_cached = True
    return obj


def tag_resource(Resource=None, Tags=None):
    """
    Creates a list of tags (key-value pairs) on the Lambda function. Requires the Lambda function ARN (Amazon Resource Name). If a key is specified without a value, Lambda creates a tag with the specified key and a value of null.
    See also: AWS API Documentation

    :example: response = client.tag_resource(
        Resource='string',
        Tags={
            'string': 'string'
        }
    )

    :type Resource: string
    :param Resource: [REQUIRED]
            The ARN (Amazon Resource Name) of the Lambda function.

    :type Tags: dict
    :param Tags: [REQUIRED]
            The list of tags (key-value pairs) you are assigning to the Lambda function.
            (string) --
            (string) --

    """
    pass


def labelize_flip(couple):
    """
    Returns a string from a 2-uple couple of the form (name, flip).

    TESTS::

        sage: from surface_dynamics.interval_exchanges.reduced import labelize_flip
        sage: labelize_flip((4,1))
        ' 4'
        sage: labelize_flip(('a',-1))
        '-a'
    """
    if couple[1] == -1:
        return '-' + str(couple[0])
    return ' ' + str(couple[0])


def enum_member_name(state):
    """
    All enum member names have the form <EnumClassName>.<EnumMemberName>. For
    our rendering we only want the member name, so we take their representation
    and split it.
    """
    return str(state).split('.', 1)[1]


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        Ensure data.message is string, since it can be very large

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
         {
            "dynamic":true,
            "properties": {
                "data": {
                    "properties": {
                        "message": {
                            "type": "text",
                            "index": true
                        }
                    }
                }
            }
        }
        """
    return {'items': mapping}


@staticmethod
def combine_results(result_1, result_2):
    """Combine two sets of results from this analysis.

        This can be used to combine results after parallelizing the
        analysis. The default is not implemented; it will only be
        implemented in cases where such a combination is feasible.
        """
    raise NotImplementedError


def safe_float(string_, default=1.0):
    """Convert a string into a float.
    If the conversion fails, return the default value.
    """
    try:
        ret = float(string_)
    except ValueError:
        return default
    else:
        return ret


def binary_to_bool_1(raw_input):
    """Map (0,1) to (False, True)"""
    mapping = {'0': False, '1': True}
    if raw_input in mapping.keys():
        return mapping[raw_input]
    else:
        return None


def _update(config, **kw):
    """ Set configuration attributes given as keyword arguments."""
    for name, value in kw.items():
        setter = config._name_to_setter.get(name, None)
        if name is None:
            raise ValueError('Invalid setting name: {0!r}'.format(name))
        else:
            setter(value)


def is_integer(val):
    """Returns whether the given value is an integer.

    Args:
      val (object): value to check

    Returns:
      ``True`` if the given value is an integer, otherwise ``False``.
    """
    try:
        val += 1
    except TypeError:
        return False
    return True


def _find_in_smiles(idx, reactants):
    """
    Find atom label in list of reactant SMILES.
    Input:  idx: atom index.
            reactants: list of reactant SMILES.
    Output: reactant: SMILES of reactant that has the indicated atom.
    """
    search = ':' + idx + ']'
    for reactant in reactants:
        if search in reactant:
            return reactant


def is_GWTC1_file(path):
    """Determine if the results file is one released as part of the GWTC1
    catalog

    Parameters
    ----------
    path: str
        path to the results file
    """
    import h5py
    f = h5py.File(path, 'r')
    keys = list(f.keys())
    f.close()
    if 'Overall_posterior' in keys or 'overall_posterior' in keys:
        return True
    return False


def describe_environment_managed_actions(EnvironmentName=None,
    EnvironmentId=None, Status=None):
    """
    Lists an environment's upcoming and in-progress managed actions.
    See also: AWS API Documentation

    :example: response = client.describe_environment_managed_actions(
        EnvironmentName='string',
        EnvironmentId='string',
        Status='Scheduled'|'Pending'|'Running'|'Unknown'
    )

    :type EnvironmentName: string
    :param EnvironmentName: The name of the target environment.

    :type EnvironmentId: string
    :param EnvironmentId: The environment ID of the target environment.

    :type Status: string
    :param Status: To show only actions with a particular status, specify a status.

    :rtype: dict
    :return: {
        'ManagedActions': [
            {
                'ActionId': 'string',
                'ActionDescription': 'string',
                'ActionType': 'InstanceRefresh'|'PlatformUpdate'|'Unknown',
                'Status': 'Scheduled'|'Pending'|'Running'|'Unknown',
                'WindowStartTime': datetime(2015, 1, 1)
            },
        ]
    }

    """
    pass


def find_system_uptime():
    """
    Find the system's uptime.

    :returns: The uptime in seconds (a float).

    This function returns the first number found in ``/proc/uptime``.
    """
    with open('/proc/uptime') as handle:
        contents = handle.read()
        fields = contents.split()
        return float(fields[0])


def normals_make_consistent(inside: bool=False):
    """Make face and vertex normals point either outside or inside the mesh

    :param inside: Inside
    :type inside: bool
    """
    pass


@staticmethod
def string_to_type(x):
    """
        Method to return name of the data type
        :param x: input item
        :return: string
        """
    if type(x).__name__ == 'str':
        x = x.strip()
        try:
            val = int(x)
        except ValueError:
            try:
                val = float(x)
            except ValueError:
                try:
                    val = str(x)
                except:
                    val = None
        x = val
    return x


@staticmethod
def to_str(value):
    """
        Convert value a string. If value is already a str or None, returne it
        unchanged. If value is a byte, decode it as utf8. Otherwise, fall back
        to the value's repr.
        """
    if value is None:
        return ''
    if isinstance(value, str):
        return value
    elif isinstance(value, bytes):
        return value.decode()
    return repr(value)


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

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

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


def create_substitutes(logs_location_base, storage_location_base,
    dynamodb_table_name):
    """Return an object which can be used to replace strings in the policy
    files

    The two *_base strings are expected to be bucket/path representations
    Current strings supported are:
    - ${DATALAKE_BUCKET}
    - ${DYNAMODB_TABLE_NAME}
    - ${LOGS_LOCATION_BASE}
    - ${STORAGE_LOCATION_BASE}

"""
    s = {'LOGS_LOCATION_BASE': logs_location_base, 'STORAGE_LOCATION_BASE':
        storage_location_base, 'DYNAMODB_TABLE_NAME': dynamodb_table_name,
        'DATALAKE_BUCKET': storage_location_base.split('/')[0]}
    return s


def GetFFC5(ElSym):
    """Get 5 term form factor and Compton scattering data

    :param ElSym: str(1-2 character element symbol with proper case);
    :return El: dictionary with 5 term form factor & compton coefficients
    """
    import FormFactors as FF
    El = {}
    FF5 = FF.FFac5term[ElSym]
    El['fa'] = FF5[:5]
    El['fc'] = FF5[5]
    El['fb'] = FF5[6:]
    Cmp5 = FF.Compton[ElSym]
    El['cmpz'] = Cmp5[0]
    El['cmpa'] = Cmp5[1:6]
    El['cmpb'] = Cmp5[6:]
    return El


@staticmethod
def midi_map(plugin, param, midi_chanel, midi_cc):
    """
        ``midi_map <instance_number> <param_symbol> <midi_channel> <midi_cc>``

        This command maps a MIDI controller to a parameter

        e.g.::

            midi_map 0 gain 0 7

        .. note::

            Not implemented yet
        """
    pass


@staticmethod
def toggle_all_outputs(ramp):
    """Generate a command that toggles all output-ports.

        Toggle mode: (on->off, off->on).

        :param    int    ramp:    Ramp value
        :return:    The PCK command (without address header) as text
        :rtype:    str
        """
    return 'AU{:03d}'.format(ramp)


def process_contexts(server, contexts, p_ctx, error=None):
    """Method to be called in the auxiliary context."""
    for ctx in contexts:
        ctx.descriptor.aux.initialize_context(ctx, p_ctx, error)
        if error is None or ctx.descriptor.aux.process_exceptions:
            ctx.descriptor.aux.process_context(server, ctx)


def get_allowed_edit():
    """
        Get the list of groups that are allowed to add content to the tile
        """


def parse_args(arguments):
    """
        Create dict of argument and value
        :return dictionary of payload
    """
    payload = {}
    for argument in arguments:
        argument = argument.split('=')
        key = argument[0]
        value = '='.join(argument[1:])
        payload[key] = value
    return payload


def narrowmatch(match=None, includeexact=False):
    """Obtain a matcher for the narrowspec."""


def check_foreign_keys(conn):
    """Check for foreign key errors.

    Return an iterator of rows with errors.
    """
    result = conn.execute('PRAGMA foreign_key_check')
    yield from result


def rip_move(MESH_OT_rip=None, TRANSFORM_OT_translate=None):
    """Rip polygons and move the result

    :param MESH_OT_rip: Rip, Disconnect vertex or edges from connected geometry
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def _get_sanitized_version(version_string):
    """
	Removes "-..." prefix from version strings.

	Tests:
	    >>> _get_sanitized_version(None)
	    >>> _get_sanitized_version("1.2.15")
	    '1.2.15'
	    >>> _get_sanitized_version("1.2.15-dev12")
	    '1.2.15'
	"""
    if version_string is not None and '-' in version_string:
        version_string = version_string[:version_string.find('-')]
    return version_string


def ld_power2(mu, a):
    """
    Evaluate power-2 limb-darkening law

    :param mu: cos of angle between surface normal and line of sight
    :param a: array or tuple [c, alpha]

    :returns:  1 - c * (1-mu**alpha)

    """
    c, alpha = a
    return 1 - c * (1 - mu ** alpha)


def simplify2(word):
    """
    normalize and simplify a vni word:
    * move tone digit to the end
    * return only digits
    * return 0 if there is no digit
    """
    if word.isalpha():
        return '0'
    ret = ''
    tone = ''
    for letter in word:
        if '1' <= letter <= '9':
            if '1' <= letter <= '5':
                if len(tone) > 0:
                    return '#'
                tone = letter
            else:
                ret += letter
    return ret + tone


def _multi_adamw_update(*data, **kwargs):
    """Update function for AdamW optimizer.

    AdamW is seen as a modification of Adam by decoupling the weight decay from the
    optimization steps taken w.r.t. the loss function.

    Adam update consists of the following steps, where g represents gradient and m, v
    are 1st and 2nd order moment estimates (mean and variance).

    .. math::

     g_t = \\nabla J(W_{t-1})\\\\
     m_t = \\beta_1 m_{t-1} + (1 - \\beta_1) g_t\\\\
     v_t = \\beta_2 v_{t-1} + (1 - \\beta_2) g_t^2\\\\
     W_t = W_{t-1} - \\eta_t (\\alpha \\frac{ m_t }{ \\sqrt{ v_t } + \\epsilon } + wd W_{t-1})

    It updates the weights using::

     m = beta1*m + (1-beta1)*grad
     v = beta2*v + (1-beta2)*(grad**2)
     w -= eta * (learning_rate * m / (sqrt(v) + epsilon) + w * wd)

    Note that gradient is rescaled to grad = rescale_grad * grad. If rescale_grad is NaN, Inf, or 0,
    the update is skipped.

    Defined in src/operator/contrib/adamw.cc:L167

    Parameters
    ----------
    data : Symbol[]
        data
    lrs : tuple of <float>, required
        Learning rates
    beta1 : float, optional, default=0.899999976
        The decay rate for the 1st moment estimates.
    beta2 : float, optional, default=0.999000013
        The decay rate for the 2nd moment estimates.
    epsilon : float, optional, default=9.99999994e-09
        A small constant for numerical stability.
    wds : tuple of <float>, required
        Weight decay augments the objective function with a regularization term that penalizes large weights. The penalty scales with the square of the magnitude of each weight.
    etas : tuple of <float>, required
        Learning rates schedule multiplier
    clip_gradient : float, optional, default=-1
        Clip gradient to the range of [-clip_gradient, clip_gradient] If clip_gradient <= 0, gradient clipping is turned off. grad = max(min(grad, clip_gradient), -clip_gradient).
    num_weights : int, optional, default='1'
        Number of updated weights.

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

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


def bracket_monotonic(f, x0=0.0, x1=1.0, factor=2.0):
    """Return `(x0, x1)` where `f(x0)*f(x1) < 0`.

    Assumes that `f` is monotonic and that the root exists.

    Proceeds by increasing the size of the interval by `factor` in the
    direction of the root until the root is found.

    Examples
    --------

    >>> import math
    >>> bracket_monotonic(lambda x:10 - math.exp(x))
    (0.0, 3.0)
    >>> bracket_monotonic(lambda x:10 - math.exp(-x), factor=1.5)
    (4.75, -10.875)
    """
    assert abs(x1 - x0) > 0
    assert factor > 1.0
    f0 = f(x0)
    f1 = f(x1)
    if f1 < f0:
        x0, x1 = x1, x0
        f0, f1 = f1, f0
    while f0 * f1 >= 0:
        x0, x1 = x1, x0 - factor * (x1 - x0)
        f0, f1 = f1, f(x1)
    return x0, x1


@staticmethod
def get_node_id(id_):
    """Return generic node_id"""
    return '{}'.format(id_)


def pol_linear_combination(f, g, h):
    """
    Write ``f`` as ``f = a*g + b*h`` with ``deg(a) < deg(h).

    INPUT:

    - ``f``, ``g``, ``h`` -- polynomials over a field k

    We assume that `g` and `h` are relatively prime.

    OUTPUT: a pair `(a, b)` of polynomials such that

    .. MATH::

            f = a\\cdot g + b\\cdot h

    and such that `deg(a) < deg(h)`.

    """
    d, A, B = g.xgcd(h)
    C, a = (f * A).quo_rem(h)
    b = B * f + C * g
    return a, b


def value_for_key(tuple_of_tuples, key):
    """Processes a tuple of 2-element tuples and returns the value
    corresponding to the given key. If not value is found, the key is returned.
    """
    for t in tuple_of_tuples:
        if t[0] == key:
            return t[1]
    else:
        return key


def reusable(records):
    """
    >>> reusable(i for i in range(5))
    [0, 1, 2, 3, 4]
    >>> reusable([0, 1, 2, 3, 4])
    [0, 1, 2, 3, 4]
    :param records: an iterable
    :return: a list or tuple
    """
    if isinstance(records, (list, tuple)):
        return records
    return list(records)


def extrude_faces_move(MESH_OT_extrude_faces_indiv=None,
    TRANSFORM_OT_shrink_fatten=None):
    """Extrude faces and move result

    :param MESH_OT_extrude_faces_indiv: Extrude Individual Faces, Extrude individual faces only
    :param TRANSFORM_OT_shrink_fatten: Shrink/Fatten, Shrink/fatten selected vertices along normals
    """
    pass


def worker_pool():
    """use the 'worker pool' strategy; hence one job is allocated to each
worker, and the next new work item is provided when a node completes its work"""
    return 'mpi_pool'


def update():
    """
        update the item registered in the canonical
        check that there aren't two translations on the same language
        (used for changing the contexts language)
        """


def get_height_from_ratio(width, ratio_w, ratio_h):
    """
    Used to calculate thumbnail height from given width and ratio
    """
    return width * ratio_h / ratio_w


@classmethod
def rebuild(cls, session, tree_id=None):
    """ This function rebuid tree.

        Args:
            session (:mod:`sqlalchemy.orm.session.Session`): SQLAlchemy session

        Kwargs:
            tree_id (int or str): id of tree, default None

        Example:

        * :mod:`sqlalchemy_mptt.tests.TestTree.test_rebuild`
        """
    trees = session.query(cls).filter_by(parent_id=None)
    if tree_id:
        trees = trees.filter_by(tree_id=tree_id)
    for tree in trees:
        cls.rebuild_tree(session, tree.tree_id)


def write(data):
    """
        Write some data to the physical connection, in sequence, in a
        non-blocking fashion.

        If possible, make sure that it is all written.  No data will
        ever be lost, although (obviously) the connection may be closed
        before it all gets through.
        """


@staticmethod
def to_string(value):
    """
        Coerce a value into a String

        :param float value: a value to be coerced
        """
    return str(value)


def track_science(track_each_call=False):
    """configure science references -- determine whether or not each call separately or only the first for each
    reference."""
    global track_science_references, track_each_reference_call
    track_science_references = True
    track_each_reference_call = track_each_call


def union(setA: list, setB: list):
    """
    union of two lists with basic datatype
    """
    setC = []
    setC.extend(setA)
    for item in setA:
        if item in setB:
            setB.remove(item)
    setC.extend(setB)
    return setC


def createMainWidget(argv):
    """
    Function to create the main widget.

    @param argv list of commandline parameters (list of strings)
    @return reference to the main widget (QWidget)
    """
    from Tools.UIPreviewer import UIPreviewer
    if len(argv) > 1:
        fn = argv[1]
    else:
        fn = None
    previewer = UIPreviewer(fn, None, 'UIPreviewer')
    return previewer


def define(zelf, *args, **kwargs):
    """ set a attribute on this ding. """
    name = args[0]
    value = args[1]
    zelf[name] = value


def package_root(varmap):
    """Return correct directory for the root package.

    The "root" package is the one where modules which do not
    belong to a package are located (see the distutils docs).
    This function should not need to be called directly in
    your actual setup script, but it can be useful for testing.
    Note that it looks for a ``package_root`` setup var, which
    can be used as a shortcut if your "root" package is not in
    the standard place (which is your setup script directory),
    rather than having to declare a ``package_dir`` dictionary
    with a ``''`` key.
    """
    try:
        return varmap['package_dir']['']
    except KeyError:
        try:
            result = varmap['package_root']
        except KeyError:
            return '.'
        else:
            dirmap = varmap.setdefault('package_dir', {})
            if '' not in dirmap:
                dirmap[''] = result
            return result


@staticmethod
def p_attribute_defaults_list(p):
    """attribute_defaults_list : attribute_default
                                   | attribute_default attribute_defaults_list"""
    try:
        p[0] = [p[1]] + p[2]
    except IndexError:
        p[0] = [p[1]]


def __of__(context):
    """Get the object in a context.
        """


def print_summary(summary):
    """Print summary of data that could be lost or inaccurate."""
    keys = summary.keys()
    if len(keys) > 0:
        for key in keys:
            step = summary[key]
            step_keys = step.keys()
            if len(step_keys) > 0:
                print(f'\n\n\nConversion step: {key}')
            if 'LOST_TABLE' in step_keys:
                print('\nWarning: data in the following tables have been lost:'
                    )
                for item in step['LOST_TABLE']:
                    print(item)
            if 'LOST_COLUMN' in step_keys:
                print(
                    '\nWarning: data in the following columns have been lost:')
                for item in step['LOST_COLUMN']:
                    print(item)
            if 'LOST_DATA' in step_keys:
                print(
                    '\nWarning: a subset of data in the following columns have been lost:'
                    )
                for item in step['LOST_DATA']:
                    print(item)
            if 'INACCURATE_COLUMN' in step_keys:
                print(
                    """
Warning: data in the following columns have been auto-populated and may be inaccurate:"""
                    )
                for item in step['INACCURATE_COLUMN']:
                    print(item)


def _get_element_and_line(xray_line):
    """
    Returns the element name and line character for a particular X-ray line as
    a tuple.

    By example, if xray_line = 'Mn_Ka' this function returns ('Mn', 'Ka')
    """
    lim = xray_line.find('_')
    if lim == -1:
        raise ValueError('Invalid xray-line: %' % xray_line)
    return xray_line[:lim], xray_line[lim + 1:]


def asciilower(s):
    """convert a string to lowercase if ASCII

    Raises UnicodeDecodeError if non-ASCII characters are found."""
    s.decode('ascii')
    return s.lower()


def p_line_to_statement(p):
    """
    line : statement NEWLINE
    """
    p[0] = p[1]


@classmethod
def bind(cls, ns, location=None):
    """
        Bind a namespace to a schema location (URI).

        This is used for imports that do not specify a schemaLocation.

        @param ns: A namespace-uri.
        @type ns: str
        @param location: The (optional) schema location for the namespace.
            (default=ns)
        @type location: str

        """
    if location is None:
        location = ns
    cls.locations[ns] = location


def angle_diff(angle1, angle2):
    """show the difference between two angles in degrees"""
    ret = angle1 - angle2
    if ret > 180:
        ret -= 360
    if ret < -180:
        ret += 360
    return ret


def qtr_to_master_url(qtr):
    """
    Build the URL for the master index of a given quarter.

    :param qtr: given qtr
    :return: string that represents the URL
    """
    assert type(qtr) == tuple
    url = 'https://www.sec.gov/Archives/edgar/full-index'
    return '{}/{}/QTR{}/master.zip'.format(url, qtr[0], qtr[1])


@classmethod
def from_const_ptr(cls, ptr):
    """Create a new instance from a const pointer"""
    new = cls.__new__(cls)
    super(cls, new).__init__(ptr, is_const=True)
    return new


def build_index(index_list):
    """This function builds two index. One with just name and version the other
    including vendor (aka group) string

    :param index_list:
    :return: Normal index and vendor index
    """
    idx = {}
    vendor_idx = {}
    for d in index_list:
        ver_range_str = str(d.get('min_version')) + '-' + str(d.get(
            'max_version'))
        curr_list = idx.get(d['name'], [])
        curr_list.append(ver_range_str)
        idx[d['name']] = curr_list
        if d.get('vendor'):
            vendor_idx_key = d.get('vendor') + '|' + d['name']
            vendor_list = vendor_idx.get(vendor_idx_key, [])
            vendor_list.append(ver_range_str)
            vendor_idx[vendor_idx_key] = vendor_list
    return idx, vendor_idx


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


def make_valid_index(list_wid):
    """
    Returns a valid new index for the given list widget `list_wid`
    """
    lowest_allowed = 0
    if str(list_wid.objectName()) == 'listActions':
        lowest_allowed = 1
    for i in range(lowest_allowed, 31):
        valid = True
        for row in range(0, list_wid.count()):
            if int(str(list_wid.item(row).text()).split()[0]) == i:
                valid = False
        if valid is True:
            return i


def describe_security_groups(DryRun=None, GroupNames=None, GroupIds=None,
    Filters=None):
    """
    Describes one or more of your security groups.
    A security group is for use with instances either in the EC2-Classic platform or in a specific VPC. For more information, see Amazon EC2 Security Groups in the Amazon Elastic Compute Cloud User Guide and Security Groups for Your VPC in the Amazon Virtual Private Cloud User Guide .
    See also: AWS API Documentation

    :example: response = client.describe_security_groups(
        DryRun=True|False,
        GroupNames=[
            'string',
        ],
        GroupIds=[
            'string',
        ],
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

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

    :type GroupNames: list
    :param GroupNames: [EC2-Classic and default VPC only] One or more security group names. You can specify either the security group name or the security group ID. For security groups in a nondefault VPC, use the group-name filter to describe security groups by name.
            Default: Describes all your security groups.
            (string) --

    :type GroupIds: list
    :param GroupIds: One or more security group IDs. Required for security groups in a nondefault VPC.
            Default: Describes all your security groups.
            (string) --

    :type Filters: list
    :param Filters: One or more filters. If using multiple filters for rules, the results include security groups for which any combination of rules - not necessarily a single rule - match all filters.
            description - The description of the security group.
            egress.ip-permission.prefix-list-id - The ID (prefix) of the AWS service to which the security group allows access.
            group-id - The ID of the security group.
            group-name - The name of the security group.
            ip-permission.cidr - An IPv4 CIDR range that has been granted permission in a security group rule.
            ip-permission.from-port - The start of port range for the TCP and UDP protocols, or an ICMP type number.
            ip-permission.group-id - The ID of a security group that has been granted permission.
            ip-permission.group-name - The name of a security group that has been granted permission.
            ip-permission.ipv6-cidr - An IPv6 CIDR range that has been granted permission in a security group rule.
            ip-permission.protocol - The IP protocol for the permission (tcp | udp | icmp or a protocol number).
            ip-permission.to-port - The end of port range for the TCP and UDP protocols, or an ICMP code.
            ip-permission.user-id - The ID of an AWS account that has been granted permission.
            owner-id - The AWS account ID of the owner of the security group.
            tag-key - The key of a tag assigned to the security group.
            tag-value - The value of a tag assigned to the security group.
            vpc-id - The ID of the VPC specified when the security group was created.
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :rtype: dict
    :return: {
        'SecurityGroups': [
            {
                'OwnerId': 'string',
                'GroupName': 'string',
                'GroupId': 'string',
                'Description': 'string',
                'IpPermissions': [
                    {
                        'IpProtocol': 'string',
                        'FromPort': 123,
                        'ToPort': 123,
                        'UserIdGroupPairs': [
                            {
                                'UserId': 'string',
                                'GroupName': 'string',
                                'GroupId': 'string',
                                'VpcId': 'string',
                                'VpcPeeringConnectionId': 'string',
                                'PeeringStatus': 'string'
                            },
                        ],
                        'IpRanges': [
                            {
                                'CidrIp': 'string'
                            },
                        ],
                        'Ipv6Ranges': [
                            {
                                'CidrIpv6': 'string'
                            },
                        ],
                        'PrefixListIds': [
                            {
                                'PrefixListId': 'string'
                            },
                        ]
                    },
                ],
                'IpPermissionsEgress': [
                    {
                        'IpProtocol': 'string',
                        'FromPort': 123,
                        'ToPort': 123,
                        'UserIdGroupPairs': [
                            {
                                'UserId': 'string',
                                'GroupName': 'string',
                                'GroupId': 'string',
                                'VpcId': 'string',
                                'VpcPeeringConnectionId': 'string',
                                'PeeringStatus': 'string'
                            },
                        ],
                        'IpRanges': [
                            {
                                'CidrIp': 'string'
                            },
                        ],
                        'Ipv6Ranges': [
                            {
                                'CidrIpv6': 'string'
                            },
                        ],
                        'PrefixListIds': [
                            {
                                'PrefixListId': 'string'
                            },
                        ]
                    },
                ],
                'VpcId': 'string',
                'Tags': [
                    {
                        'Key': 'string',
                        'Value': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


def load(dbname):
    """Return a Database instance from the traces stored on disk.

    This function should do the following:

     * Create a Database instance `db`.
     * Assign to `db` Trace instances corresponding to the pymc tallyable
       objects that are stored on disk.
     * Assign to `db` a _state_ attribute storing the stepping methods state.
       If this is not implemented, simply set db._state_ = {}.

    After loading a database `db`, we should be able to call
    the gettrace method of each tallyable object stored in the database.
    """
    pass


def get_chains_list(mmtf_dict, groups):
    """Creates a list of chain dictionaries from a .mmtf dictionary by zipping
    together some of its fields.

    :param dict mmtf_dict: the .mmtf dictionary to read.
    :rtype: ``list``"""
    chains = []
    for i_id, id, group_num in zip(mmtf_dict['chainIdList'], mmtf_dict[
        'chainNameList'], mmtf_dict['groupsPerChain']):
        chain = {'id': id, 'internal_id': i_id, 'groups': groups[:group_num]}
        del groups[:group_num]
        for entity in mmtf_dict['entityList']:
            if len(chains) in entity['chainIndexList']:
                chain['type'] = entity['type']
                chain['sequence'] = entity.get('sequence', '')
                chain['full_name'] = entity.get('description', None)
                break
        chains.append(chain)
    return chains


@staticmethod
def empty_cell(cell):
    """Test if excel cell is empty or contains only whitespace."""
    if cell.ctype == 0:
        return True
    if str(cell.value).strip() == '':
        return True
    return False


def _tabulate_coefficients(dof_data):
    """This function tabulates the element coefficients that are
    generated by FIAT at compile time."""
    f_comment = format['comment']
    f_table = format['static const float declaration']
    f_coefficients = format['coefficients']
    f_component = format['component']
    f_decl = format['declaration']
    f_tensor = format['tabulate tensor']
    f_new_line = format['new line']
    coefficients = dof_data['coeffs']
    code = [f_comment('Table(s) of coefficients')]
    num_mem = dof_data['num_expansion_members']
    for i, coeffs in enumerate(coefficients):
        name = f_component(f_coefficients(i), num_mem)
        code += [f_decl(f_table, name, f_new_line + f_tensor(coeffs))] + ['']
    return code


def snapstr(number):
    """
    return formatted string for snapshot number
    (4 digit, zero padded string). Can take both
    strings and integers as argument.
    """
    if hasattr(number, '__len__') and not isinstance(number, str):
        print(
            "You've given me a list for a snapshot number? I'm going to try element 0:"
            , number[0])
        number = number[0]
    errormsg = "'" + str(number) + "' is not an integer."
    if isinstance(number, float):
        raise ValueError(errormsg)
    import numpy as np
    try:
        n = int(number)
    except ValueError:
        raise ValueError(errormsg)
    return '{0:04d}'.format(n)


def bytes_to_human(size, decimal_places=2):
    """ Returns a human readable file size from a number of bytes. """
    for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
        if size < 1024:
            break
        size /= 1024
    return f'{size:.{decimal_places}f}{unit}B'


def extractContent(completeDocument):
    """ Function to separate the document from the preamble(LaTeX formating)
            and the information after the document. It returns an array of strings
            with the parts.

            Args:
                    completeDocument: The first parameter.

            Returns:
                    array: It returns an array of strings with the parts.

    """
    try:
        preamble = completeDocument[:completeDocument.index(
            '\\begin{document}')]
        document = completeDocument[completeDocument.index(
            '\\begin{document}'):completeDocument.index('\\end{document}') +
            len('\\end{document}')]
        epilogue = completeDocument[completeDocument.index(
            '\\end{document}') + len('\\end{document}'):]
    except ValueError:
        print('\\begin{document} or \\end{document} not found.\n')
    return [preamble, document, epilogue]


def _min_dummies(dummies, sym, indices):
    """
    Return list of minima of the orbits of indices in group of dummies
    see `double_coset_can_rep` for the description of `dummies` and `sym`
    indices is the initial list of dummy indices

    Examples
    ========

    >>> from sympy.combinatorics.tensor_can import _min_dummies
    >>> _min_dummies([list(range(2, 8))], [0], list(range(10)))
    [0, 1, 2, 2, 2, 2, 2, 2, 8, 9]
    """
    num_types = len(sym)
    m = []
    for dx in dummies:
        if dx:
            m.append(min(dx))
        else:
            m.append(None)
    res = indices[:]
    for i in range(num_types):
        for c, i in enumerate(indices):
            for j in range(num_types):
                if i in dummies[j]:
                    res[c] = m[j]
                    break
    return res


def checkRegionalIndex(esM, data):
    """
    Necessary if the data rows represent the location-dependent data:
    Check if the row-indices match the location indices of the energy system model.
    """
    if set(data.index) != esM.locations:
        raise ValueError(
            """Location indices do not match the one of the specified energy system model.
"""
             + 'Data indices: ' + str(set(data.index)) + '\n' +
            'Energy system model regions: ' + str(esM.locations))


def rsquared_adj(r, nobs, df_res, has_constant=True):
    """
    Compute the adjusted R^2, coefficient of determination.

    Args:
        r (float): rsquared value
        nobs (int): number of observations the model was fit on
        df_res (int): degrees of freedom of the residuals (nobs - number of model params)
        has_constant (bool): whether the fitted model included a constant (intercept)

    Returns:
        float: adjusted coefficient of determination
    """
    if has_constant:
        return 1.0 - (nobs - 1) / df_res * (1.0 - r)
    else:
        return 1.0 - nobs / df_res * (1.0 - r)


@classmethod
def route(cls, master, message, socket):
    """
        Determines, based on whether the trait is intended or not for slave/master, the
          broadcast to use: the master itself or a slave given by a key.
        """
    return master.forward(socket, message.kwargs.get(getattr(cls,
        'SLAVE_KEY_ATTR', 'slave'), None) if not getattr(cls,
        'MASTER_TRAIT', False) else None)


def parse_int(v, fallback_to=0):
    """Parses a string as an integer value. Falls back to zero when failed to
    parse."""
    try:
        return int(v)
    except ValueError:
        return fallback_to


@staticmethod
def handle(event, _event_data, _listener_data):
    """
        Handles a ExitMessage received event.

        :param enarksh.event.Event.Event event: The event.
        :param * _event_data: Not used.
        :param * _listener_data: Not used.
        """
    del _event_data, _listener_data
    event.event_controller.exit = True


@staticmethod
def get_elastic_mappings(es_major):
    """Get Elasticsearch mapping.

        :param es_major: major version of Elasticsearch, as string
        :returns:        dictionary with a key, 'items', with the mapping
        """
    mapping = """
        {
            "properties": {
                "description_analyzed": {
                  "type": "text",
                  "index": true
                }
           }
        } """
    return {'items': mapping}


def convert_list_to_dict(data_list, key):
    """Convert list of dictionaries to a dictionary of dictionaries

    :param data_list: List of dictionaries.
    :type data_list: list
    :param key: key in each dictionary to become the returned dictionary key.
    :type key: str
    :returns:
        Dictionary of all dictionaries. Returns an empty dictionary if
        all intended keys are not unique.
    :rtype: dict
    """
    data_dict = {}
    for element_dict in data_list:
        if element_dict[key] not in data_dict.keys():
            data_dict[element_dict[key]] = element_dict
    diff = len(data_list) - len(data_dict)
    if diff != 0:
        print(
            '\nUnable to create dictionary since some intended keys are duplicated.'
            )
        data_dict = {}
    return data_dict


def jwt_get_username_from_payload_handler(payload):
    """
    Override this function if username is formatted differently in payload
    """
    return payload.get('username')


def gcd(a, b):
    """
    2.8 times faster than egcd(a,b)[2]
    """
    a, b = (b, a) if a < b else (a, b)
    while b:
        a, b = b, a % b
    return a


def T(*args):
    """
    Always returns true
    @sig T :: _ -> Bool
    """
    return True


def compact_repeating_words(words):
    """
    Remove adjacent repeating words.

    :param words: An iterable of words (strings), assumed to already be
                  normalized (lowercased).
    :returns: An iterable of words with adjacent repeating words replaced by a
              single word.

    This is used to avoid awkward word repetitions in the package name
    conversion algorithm. Here's an example of what I mean:

    >>> from py2deb import compact_repeating_words
    >>> name_prefix = 'python'
    >>> package_name = 'python-mcrypt'
    >>> combined_words = [name_prefix] + package_name.split('-')
    >>> print(list(combined_words))
    ['python', 'python', 'mcrypt']
    >>> compacted_words = compact_repeating_words(combined_words)
    >>> print(list(compacted_words))
    ['python', 'mcrypt']
    """
    last_word = None
    for word in words:
        if word != last_word:
            yield word
        last_word = word


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

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

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


def get_zone_wildcards(name):
    """ A generator of wildcards out of a zone name.
    For a DNS name, returns series of:
     - the name itself
     - the name with first label substitued as *
     - the name with first label dropped and second substittuted as *
     - ...
     - single *
"""
    yield name
    labels = name.split('.')
    while labels:
        labels[0] = '*'
        yield '.'.join(labels)
        labels.pop(0)


@classmethod
def map_create_multipart_upload_params(cls, request_params, cli_params):
    """Map CLI params to CreateMultipartUpload request params"""
    cls._set_general_object_params(request_params, cli_params)
    cls._set_sse_request_params(request_params, cli_params)
    cls._set_sse_c_request_params(request_params, cli_params)
    cls._set_metadata_params(request_params, cli_params)
    cls._set_request_payer_param(request_params, cli_params)


def hide_toggle():
    """Toggle hiding of selected nodes

    """
    pass


def detect_moderation_labels(Image=None, MinConfidence=None):
    """
    Detects explicit or suggestive adult content in a specified JPEG or PNG format image. Use DetectModerationLabels to moderate images depending on your requirements. For example, you might want to filter images that contain nudity, but not images containing suggestive content.
    To filter images, use the labels returned by DetectModerationLabels to determine which types of content are appropriate. For information about moderation labels, see  howitworks-moderateimage .
    See also: AWS API Documentation

    :example: response = client.detect_moderation_labels(
        Image={
            'Bytes': b'bytes',
            'S3Object': {
                'Bucket': 'string',
                'Name': 'string',
                'Version': 'string'
            }
        },
        MinConfidence=...
    )

    :type Image: dict
    :param Image: [REQUIRED]
            Provides the source image either as bytes or an S3 object.
            You pass image bytes to a Rekognition API operation by using the Bytes property. For example, you would use the Bytes property to pass an image loaded from a local file system. Image bytes passed by using the Bytes property must be base64-encoded. Your code may not need to encode image bytes if you are using an AWS SDK to call Rekognition API operations. For more information, see example4 .
            You pass images stored in an S3 bucket to a Rekognition API operation by using the S3Object property. Images stored in an S3 bucket do not need to be base64-encoded.
            The region for the S3 bucket containing the S3 object must match the region you use for Amazon Rekognition operations.
            If you use the Amazon CLI to call Amazon Rekognition operations, passing image bytes using the Bytes property is not supported. You must first upload the image to an Amazon S3 bucket and then call the operation using the S3Object property.
            For Amazon Rekognition to process an S3 object, the user must have permission to access the S3 object. For more information, see manage-access-resource-policies .
            Bytes (bytes) --Blob of image bytes up to 5 MBs.
            S3Object (dict) --Identifies an S3 object as the image source.
            Bucket (string) --Name of the S3 bucket.
            Name (string) --S3 object key name.
            Version (string) --If the bucket is versioning enabled, you can specify the object version.

    :type MinConfidence: float
    :param MinConfidence: Specifies the minimum confidence level for the labels to return. Amazon Rekognition doesn't return any labels with a confidence level lower than this specified value.
            If you don't specify MinConfidence , the operation returns labels with confidence values greater than or equal to 50 percent.

    :rtype: dict
    :return: {
        'ModerationLabels': [
            {
                'Confidence': ...,
                'Name': 'string',
                'ParentName': 'string'
            },
        ]
    }

    """
    pass


def is_transformed_name(name):
    """
    Quickly check if a name was transformed with `get_transformed_name`

    Parameters
    ----------
    name : str
        Name to check

    Returns
    -------
    bool
        Boolean, whether the string could have been produced by `get_transformed_name`
    """
    return name.endswith('__') and name.count('_') >= 3


@classmethod
def from_api_data(cls, data):
    """Creates a new Commission object from API data from ticketswitch.

        Args:
            data (dict): the part of the response from a ticketswitch API call
                that concerns a commission payable to the user.

        Returns:
            :class:`Commission <pyticketswitch.commission.Commission>`: a new
            :class:`Commission <pyticketswitch.commission.Commission>` object
            populated with the data from the api.

        """
    kwargs = {'including_vat': data.get('amount_including_vat'),
        'excluding_vat': data.get('amount_excluding_vat'), 'currency_code':
        data.get('commission_currency_code')}
    return cls(**kwargs)


@staticmethod
def prorate_transfer(amount, provider):
    """
        Return processing fee associated to a transfer (i.e. nothing here).
        """
    return 0


def assert_is_list_of(value, cls, min=None, max=None):
    """
    If value is not a list of cls instances, raises TypeError.
    """
    if not isinstance(value, list):
        raise TypeError('Must be list of {}'.format(cls.__name__))
    for item in value:
        if not isinstance(item, cls):
            raise TypeError('Must be list of {}'.format(cls.__name__))
        if min is not None and item < min or max is not None and item > max:
            raise ValueError('All values must be in range {} to {}'.format(
                min, max))


@classmethod
def get_username(cls, user):
    """Return the username for given user"""
    raise NotImplementedError('Implement in subclass')


@classmethod
def getSupportedRoiClasses(cls):
    """Returns the default available ROI classes

        :rtype: List[class]
        """
    return tuple(cls._MODE_ACTIONS_PARAMS.keys())


@staticmethod
def query_data(database, sql_statement):
    """
        query a table by sql statement and retrieve the given columns
        :param database: Database, reference of the database
        :param sql_statement: str, sql statement
        :return: StreamedResultSet, Iterator with list as rows, each list has the values of the columns
        """
    with database.snapshot() as snapshot:
        results = snapshot.execute_sql(sql_statement)
        return results


def rtrd_str2list(str):
    """Format Route Target string to list"""
    if not str:
        return []
    if isinstance(str, list):
        return str
    return str.split(',')


@staticmethod
def find_wrapper(element):
    """Abstract static method to find an appropriate wrapper"""
    raise NotImplementedError()


def __init__(context, request):
    """
        Initialize the task preprocessor.

        Extracts target url and authentication from the current
        context and url.

        :param context: Current context for the calling view.
        :type context: A Plone object

        :param request: Current request for the calling view.
        """


def xarray(shape, yx=[0, 0], th=None):
    """2D array of x values.

    Parameters
    ----------
    shape : tuple of int
      The shape of the resulting array, (y, x).
    yx : tuple of float
      Offset the array to align with this y, x center.
    th : Quantity, optional
      Place the x-axis along this position angle, measured
      counterclockwise from the original x-axis.

    Returns
    -------
    x : ndarray
      An array of x values.

    Examples
    --------
    >>> from sbpy.imageanalysis.utils import xarray
    >>> x = xarray((10, 10))
    >>> x[0, 3]
    3

    """
    import numpy as np
    import astropy.units as u
    y, x = np.indices(shape)[-2:]
    y = y - yx[0]
    x = x - yx[1]
    if th is not None:
        x = x * np.cos(th.to(u.rad).value) + y * np.sin(th.to(u.rad).value)
    return x


def view_all():
    """View all the strips in the sequencer

    """
    pass


def create_domain_name(domainName=None, certificateName=None,
    certificateBody=None, certificatePrivateKey=None, certificateChain=None,
    certificateArn=None):
    """
    Creates a new domain name.
    See also: AWS API Documentation

    :example: response = client.create_domain_name(
        domainName='string',
        certificateName='string',
        certificateBody='string',
        certificatePrivateKey='string',
        certificateChain='string',
        certificateArn='string'
    )

    :type domainName: string
    :param domainName: [REQUIRED]
            (Required) The name of the DomainName resource.

    :type certificateName: string
    :param certificateName: The user-friendly name of the certificate.

    :type certificateBody: string
    :param certificateBody: [Deprecated] The body of the server certificate provided by your certificate authority.

    :type certificatePrivateKey: string
    :param certificatePrivateKey: [Deprecated] Your certificate's private key.

    :type certificateChain: string
    :param certificateChain: [Deprecated] The intermediate certificates and optionally the root certificate, one after the other without any blank lines. If you include the root certificate, your certificate chain must start with intermediate certificates and end with the root certificate. Use the intermediate certificates that were provided by your certificate authority. Do not include any intermediaries that are not in the chain of trust path.

    :type certificateArn: string
    :param certificateArn: The reference to an AWS-managed certificate. AWS Certificate Manager is the only supported source.

    :rtype: dict
    :return: {
        'domainName': 'string',
        'certificateName': 'string',
        'certificateArn': 'string',
        'certificateUploadDate': datetime(2015, 1, 1),
        'distributionDomainName': 'string'
    }

    """
    pass


def desc_from_builder(builder):
    """ Desc From Builder """
    class_name = builder.__class__.__name__
    if 'CMakeBuilder' in class_name:
        return 'C++ projects'
    if 'Linguist' in class_name:
        return 'translations'
    if 'Python' in class_name:
        return 'Python projects'
    return None


def potrf(A=None, name=None, attr=None, out=None, **kwargs):
    """Performs Cholesky factorization of a symmetric positive-definite matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, the Cholesky factor *B* of the symmetric, positive definite matrix *A* is
    computed. *B* is triangular (entries of upper or lower triangle are all zero), has
    positive diagonal entries, and:

      *A* = *B* \\* *B*\\ :sup:`T`  if *lower* = *true*
      *A* = *B*\\ :sup:`T` \\* *B*  if *lower* = *false*

    If *n>2*, *potrf* is performed separately on the trailing two dimensions for all inputs
    (batch mode).

    .. note:: The operator supports float32 and float64 data types only.

    Examples::

       Single matrix factorization
       A = [[4.0, 1.0], [1.0, 4.25]]
       potrf(A) = [[2.0, 0], [0.5, 2.0]]

       Batch matrix factorization
       A = [[[4.0, 1.0], [1.0, 4.25]], [[16.0, 4.0], [4.0, 17.0]]]
       potrf(A) = [[[2.0, 0], [0.5, 2.0]], [[4.0, 0], [1.0, 4.0]]]

    Defined in src/operator/tensor/la_op.cc:L214

    Parameters
    ----------
    A : Symbol
        Tensor of input matrices to be decomposed

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

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


def maybe_pluralize(count, singular, plural):
    """
    Returns a formatted string containing count and plural if count is not 1
    Returns count and singular if count is 1

    maybe_pluralize(0, 'Article', 'Articles') -> '0 Articles'
    maybe_pluralize(1, 'Article', 'Articles') -> '1 Article'
    maybe_pluralize(2, 'Article', 'Articles') -> '2 Articles'

    """
    selection = plural
    if count == 1:
        selection = singular
    return '{} {}'.format(count, selection)


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

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

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


def set_bits(data, value, offset, bits=1):
    """
        Set specified bits in integer

        >>> bin(set_bits(0,0b1010,0,4))
        '0b1010'
        >>> bin(set_bits(0,0b1010,3,4))
        '0b1010000'
    """
    mask = (1 << bits) - 1 << offset
    clear = 65535 ^ mask
    data = data & clear | value << offset & mask
    return data


def prepare(environ):
    """ Prepares the response for being called as a WSGI application """


@classmethod
def list_by_node_id(cls, context, node_id, limit=None, marker=None,
    sort_key=None, sort_dir=None):
    """Return a list of VolumeConnector objects related to a given node ID.

        :param context: security context
        :param node_id: the integer ID of the node
        :param limit: maximum number of resources to return in a single result
        :param marker: pagination marker for large data sets
        :param sort_key: column to sort results by
        :param sort_dir: direction to sort. "asc" or "desc".
        :returns: a list of :class:`VolumeConnector` objects
        :raises: InvalidParameterValue if sort_key does not exist
        """
    db_connectors = cls.dbapi.get_volume_connectors_by_node_id(node_id,
        limit=limit, marker=marker, sort_key=sort_key, sort_dir=sort_dir)
    return cls._from_db_object_list(context, db_connectors)


def bvor(a, b):
    """
    Bitwise OR: a | b
    """
    return '(bvor {} {})'.format(a, b)


def permission_settings(permission=None):
    """Return user-role permission settings.

        If 'permission' is passed to the method then only the settings for
        'permission' is returned.
        """


def lookupService(name, timeout=None):
    """
        Perform an SRV record lookup.

        @type name: L{bytes} or L{str}
        @param name: DNS name to resolve.

        @type timeout: Sequence of C{int}
        @param timeout: Number of seconds after which to reissue the query.
            When the last timeout expires, the query is considered failed.

        @rtype: L{Deferred}
        @return: A L{Deferred} which fires with a three-tuple of lists of
            L{twisted.names.dns.RRHeader} instances.  The first element of the
            tuple gives answers.  The second element of the tuple gives
            authorities.  The third element of the tuple gives additional
            information.  The L{Deferred} may instead fail with one of the
            exceptions defined in L{twisted.names.error} or with
            C{NotImplementedError}.
        """


def fmt_minutes(seconds):
    """Format seconds as minutes and seconds.

    Args:
        seconds (int): The number of seconds.

    Returns:
        str: The value formatted as `mm:ss`.
    """
    m, s = divmod(seconds, 60)
    return f'{m}:{s:02}'


def listify(l):
    """Encapsulate l with list[] if not."""
    return [l] if not isinstance(l, list) else l


def __init__(cls, name, bases, ns):
    """
        Check the operations supported unless told otherwise.

        If the class defines the ``bypass_operation_check`` attribute and it
        evaluates to ``True``, :meth:`check_operations` won't be run.

        """
    type.__init__(cls, name, bases, ns)
    if not ns.get('bypass_operation_check'):
        cls.check_operations(name)


def _new_object(cls):
    """Helper function for pickle"""
    return cls.__new__(cls)


def run(args):
    """Initializes the REST application with all configured component endpoints.
    """
    from clearshare import app, start, stop
    start()


def markers_make_local():
    """Move selected scene markers to the active Action as local ‘pose’ markers

    """
    pass


def get_build_config(build_worktree, args):
    """ Get a CMakeBuildConfig object from an argparse.Namespace object """
    build_config = build_worktree.build_config
    if hasattr(args, 'config'):
        if args.config:
            build_config.set_active_config(args.config)
    if hasattr(args, 'build_type'):
        build_config.build_type = args.build_type
    if hasattr(args, 'cmake_generator'):
        build_config.cmake_generator = args.cmake_generator
    if hasattr(args, 'verbose_make'):
        build_config.verbose_make = args.verbose_make
    if hasattr(args, 'cmake_flags') and args.cmake_flags:
        user_flags = list()
        for flag_string in args.cmake_flags:
            if '=' not in flag_string:
                raise Exception('Expecting a flag looking like -Dkey=value')
            key, value = flag_string.split('=', 1)
            user_flags.append((key, value))
        build_config.user_flags = user_flags
    if hasattr(args, 'num_jobs'):
        build_config.num_jobs = args.num_jobs
    if hasattr(args, 'build_prefix'):
        if args.build_prefix:
            build_config.build_prefix = args.build_prefix
    return build_config


@classmethod
def _mel2hz(cls, mel):
    """
        Convert the given Mel value to Hz frequency.

        :param float mel: the Mel value to convert
        :rtype: float
        """
    return 700.0 * (10 ** (mel / cls.MEL_10) - 1)


@staticmethod
def to_kelvin(newton):
    """ Convert newton to kelvin """
    return newton * 100 / 33 + 273.15


@classmethod
def from_dict(cls, data):
    """Decodes a dictionary into a new `DataObject` instance."""
    self = cls()
    self.update_from_dict(data)
    return self


@staticmethod
def _remove_blank(l):
    """ Removes trailing zeros in the list of integers and returns a new list of integers"""
    ret = []
    for i, _ in enumerate(l):
        if l[i] == 0:
            break
        ret.append(l[i])
    return ret


def getid(obj):
    """Return id if argument is a Resource.

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


@classmethod
def failed_coerce(cls, thing, push_type):
    """Raise PushError when something fails to coerce to a PushType."""
    return cls('Could not convert {typ1} {th} to {typ2}.'.format(th=thing,
        typ1=type(thing), typ2=push_type))


def load_submission(path):
    """return json object.
    Input file format:
        <query_unique_id1> <uid11>,<uid12>,<uid13>,...
        <query_unique_id2> <uid21>,<uid22>,<uid23>,...
        <query_unique_id3> <uid31>,<uid32>,<uid33>,...
    Return json format:
        {
            <query_unique_id1>: [ uid11, uid12, uid13, ... ]
            <query_unique_id2>: [ uid21, uid22, uid23, ... ]
            <query_unique_id3>: [ uid31, uid32, uid33, ... ]
        }
    """
    json_list = {}
    with open(path) as f:
        for line in f:
            line = line.strip()
            tmp = line.split(' ')
            if len(tmp) > 1:
                q_id = tmp[0].strip()
                c_ids = tmp[1].strip().split(',')
                json_list[q_id] = c_ids
    return json_list


def reboot(isdsAppliance, check_mode=False, force=False):
    """
    Reboot the appliance
    """
    if check_mode is True:
        return isdsAppliance.create_return_object(changed=True)
    else:
        return isdsAppliance.invoke_post('Rebooting appliance',
            '/diagnostics/restart_shutdown/reboot', {})


@staticmethod
def get_job_metadata():
    """Collect metadata for extractor-job"""
    return {}


def get_excluded_items():
    """Returns a list of all excluded items.
        """


def reverse(string):
    """
    Returns the string reversed ("abc" -> "cba").

    :param string: String to revert.
    :type string: str
    :return: Reversed string.
    :rtype: str
    """
    return string[::-1]


def chain():
    """Returns object chain."""


def validateToken():
    """
        Method that retrieves information from the authorization endpoint in order to retrieve the authorization code
        In order to validate the recived token, some steps must be accomplished according to Authentication Flow.
        In the current usage stage there is no need to validate it as it's only needed the acces_token
        """
    pass


@staticmethod
def rejoinFluxes(solutionSplit, reactionsSplit, reactions):
    """ rejoin the fluxes in the given solution by applying reactionsSplit

        This assumes that solutionSplit has been obtained by performing FBA on
        the split matrix corresponding to reactionsSplit. This function combines
        the split fluxes by subtracting the negative component from the positive
        one.

        Keyword arguments:

        solutionSplit  -- vector of non-negative fluxes
        reactionsSplit -- dictionary { name : tuple of indexes } - indexes can
                          be None; if both are not None, the first is the pos.
                          and the second is the neg. component (v = v[0] - v[1])
                          (as computed by FbAnalyzer.splitFluxes)
        reactions      -- dictionary of all reactions { name : original matrix
                                                                        column }

        Returns:  joined flux vector (indexed like original matrix columns)
        """
    if len(solutionSplit) == 0:
        return solutionSplit
    solution = [0.0] * len(reactions)
    for rea in reactionsSplit:
        rea_index_orig = reactions[rea]
        indexPos, indexNeg = reactionsSplit[rea]
        if indexPos is not None:
            solution[rea_index_orig] += solutionSplit[indexPos]
        if indexNeg is not None:
            solution[rea_index_orig] -= solutionSplit[indexNeg]
    return solution


@classmethod
def FromFile(cls, xml_file):
    """
        Creates an object from an XML file handle or file name
        """
    from xml.dom.minidom import parse
    dom = parse(xml_file)
    return cls(dom)


@classmethod
def get_cache_attr_name(cls):
    """
        Returns the name of the attribute that should be used to store
        a reference to the fetched/created object on a request.
        """
    return '_{}.{}'.format(cls._meta.app_label, cls._meta.model_name).lower()


@classmethod
def wrap_get_stream(cls, response):
    """Wrap the response from getting a stream into an instance
        and return it

        :param response: The response from getting a stream
        :type response: :class:`requests.Response`
        :returns: the new stream instance
        :rtype: :class:`list` of :class:`stream`
        :raises: None
        """
    json = response.json()
    s = cls.wrap_json(json['stream'])
    return s


def convert_new_lines(text):
    """ Convert new lines to a common format.  """
    return text.replace('\r\n', '\n').replace('\r', '\n')


def get_character_weight(char: str, options: dict) ->int:
    """
    Return an integer weight corresponding to `char`.
    The weight is determined by the Unicode code point of `char` and ranges specified by `options`.

    >>> char = '日'
    >>> options = {
    ...     'default_weight': 200,
    ...     'ranges': [
    ...         { 'start': 0, 'end': 4351, 'weight': 100 },
    ...         { 'start': 8192, 'end': 8205, 'weight': 100 }
    ...     ]
    >>> get_character_weight(char, options)
    200
    """
    ranges = options['ranges']
    char_code_point = ord(char[0])
    match = [range['weight'] for range in ranges if range['start'] <=
        char_code_point <= range['end']]
    weight = match[0] if match != [] else options['default_weight']
    return weight


@staticmethod
def distributed_repo():
    """True for distributed version controls systems, False otherwise."""
    return True


@classmethod
def _from_dict(cls, _dict):
    """Initialize a DeleteCredentials object from a json dictionary."""
    args = {}
    if 'credential_id' in _dict:
        args['credential_id'] = _dict.get('credential_id')
    if 'status' in _dict:
        args['status'] = _dict.get('status')
    return cls(**args)


@classmethod
def from_context(cls, context):
    """
        Create an event from audit context

        :type context: django_audit_events.context.AuditContext
        :return: An audit event object
        :rtype: AbstractAuditEvent
        """
    obj = cls()
    obj.user = context.user
    obj.remote_addr = context.remote_addr
    obj.url = context.url
    obj.query_params = context.query_params
    obj.post_data = context.post_data
    return obj


def SizeExpsOther(t):
    """Other expenses per policy at time t"""
    return 0