def list_ssh_public_keys(UserName=None, Marker=None, MaxItems=None):
    """
    Returns information about the SSH public keys associated with the specified IAM user. If there are none, the action returns an empty list.
    The SSH public keys returned by this action are used only for authenticating the IAM user to an AWS CodeCommit repository. For more information about using SSH keys to authenticate to an AWS CodeCommit repository, see Set up AWS CodeCommit for SSH Connections in the AWS CodeCommit User Guide .
    Although each user is limited to a small number of keys, you can still paginate the results using the MaxItems and Marker parameters.
    See also: AWS API Documentation

    :example: response = client.list_ssh_public_keys(
        UserName='string',
        Marker='string',
        MaxItems=123
    )

    :type UserName: string
    :param UserName: The name of the IAM user to list SSH public keys for. If none is specified, the UserName field is determined implicitly based on the AWS access key used to sign the request.
            This parameter allows (per its regex pattern ) a string of characters consisting of upper and lowercase alphanumeric characters with no spaces. You can also include any of the following characters: =,.@-

    :type Marker: string
    :param Marker: Use this parameter only when paginating results and only after you receive a response indicating that the results are truncated. Set it to the value of the Marker element in the response that you received to indicate where the next call should start.

    :type MaxItems: integer
    :param MaxItems: (Optional) Use this only when paginating results to indicate the maximum number of items you want in the response. If additional items exist beyond the maximum you specify, the IsTruncated response element is true .
            If you do not include this parameter, it defaults to 100. Note that IAM might return fewer results, even when there are more results available. In that case, the IsTruncated response element returns true and Marker contains a value to include in the subsequent call that tells the service where to continue from.

    :rtype: dict
    :return: {
        'SSHPublicKeys': [
            {
                'UserName': 'string',
                'SSHPublicKeyId': 'string',
                'Status': 'Active'|'Inactive',
                'UploadDate': datetime(2015, 1, 1)
            },
        ],
        'IsTruncated': True|False,
        'Marker': 'string'
    }

    """
    pass


def find_lists(start_marker, tag, para):
    """ Input: A bunch of junk
    Output: None if no modification done,
    otherwise return (formatted_line, unformatted_remainder) """
    unformatted_remainder = ''
    ret = ''
    assert ('<' not in tag and '>' not in tag, "sample tag is 'ol'")
    assert (len(start_marker) == 1,
        "This code assumes start_marker's length is 1")
    if para.strip() and para[0] == start_marker:
        ul = ''
        maybe_lis = para.split('\n')
        while maybe_lis:
            maybe_li = maybe_lis[0]
            if maybe_li and maybe_li[0] == start_marker:
                li = maybe_li[1:].strip()
                ul += '<li>' + li + '</li>'
                maybe_lis = maybe_lis[1:]
            else:
                unformatted_remainder += '\n'.join(maybe_lis)
                maybe_lis = []
        ret += '<%s>' % tag + ul + '</%s>' % tag
        return ret, unformatted_remainder


def check_query_type(type):
    """Check the query type.

    Only the following query types are allowed:
    AllowedType:
        AllLabels: Query all _labels of an instance
        PartLabels: Query part of labels of an instance (Only available in multi-label setting)
        Features: Query unlab_features of instances
    NotImplementedQueryType
        Relations: Query relations between two object
        Examples: Query examples given constrains

    AllLabels: query all labels of an selected instance.
        Support scene: binary classification, multi-class classification, multi-label classification, regression

    Partlabels: query part of labels of an instance.
        Support scene: multi-label classification

    Features: query part of features of an instance.
        Support scene: missing features

    Parameters
    ----------
    type: str
        query type.

    Returns
    -------
    result: bool
        if query type in ['AllLabels', 'PartLabels', 'Features'],return True.
    """
    assert isinstance(type, str)
    QueryType = ['AllLabels', 'PartLabels', 'Features']
    NotImplementedQueryType = ['Relations', 'Examples']
    if type in QueryType:
        return True
    else:
        return False


def sort_according_to_ref_list(fixturenames, param_names):
    """
    Sorts items in the first list, according to their position in the second.
    Items that are not in the second list stay in the same position, the others are just swapped.
    A new list is returned.

    :param fixturenames:
    :param param_names:
    :return:
    """
    cur_indices = []
    for pname in param_names:
        try:
            cur_indices.append(fixturenames.index(pname))
        except (ValueError, IndexError):
            pass
    target_indices = sorted(cur_indices)
    sorted_fixturenames = list(fixturenames)
    for old_i, new_i in zip(cur_indices, target_indices):
        sorted_fixturenames[new_i] = fixturenames[old_i]
    return sorted_fixturenames


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

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

    """
    pass


def format_size(size):
    """Return file size as string from byte size."""
    for unit in ('B', 'KB', 'MB', 'GB', 'TB'):
        if size < 2048:
            return '%.f %s' % (size, unit)
        size /= 1024.0


def hunkinrange(hunk, linerange):
    """Return True if `hunk` defined as (start, length) is in `linerange`
    defined as (lowerbound, upperbound).

    >>> hunkinrange((5, 10), (2, 7))
    True
    >>> hunkinrange((5, 10), (6, 12))
    True
    >>> hunkinrange((5, 10), (13, 17))
    True
    >>> hunkinrange((5, 10), (3, 17))
    True
    >>> hunkinrange((5, 10), (1, 3))
    False
    >>> hunkinrange((5, 10), (18, 20))
    False
    >>> hunkinrange((5, 10), (1, 5))
    False
    >>> hunkinrange((5, 10), (15, 27))
    False
    """
    start, length = hunk
    lowerbound, upperbound = linerange
    return lowerbound < start + length and start < upperbound


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


def dict_from_list(in_list, key):
    """From a list of dicts creates a dict of dicts using a given key name
    """
    d = {}
    for entry in in_list:
        d[entry[key]] = entry
    return d


@classmethod
def atomic(cls):
    """Do the database atomic action."""
    return cls._meta.database.atomic()


def subt(intf, ints):
    """
    overpython.subt(intf, ints)

    Subtract intf with ints. Raises ValueError if intf/ints is a string.
    """
    try:
        return float(intf) - float(ints)
    except ValueError:
        raise ValueError('%s/%s is not a number' % (intf, ints))


def extract_key_value(line):
    """Return key, value from given line if present, else return None.
    """
    segments = line.split('=', 1)
    if len(segments) < 2:
        return None
    key, value = segments
    value = value.strip()
    key = key.strip()
    value = value.strip()
    return key, value


def get_status(object):
    """
    Gets the lower Status information

    Args:
        object: The object containing Status

    Returns:
        The state within Status (None if not found)
        The health within Status (None if not found)
    """
    state = None
    health = None
    if 'Status' in object:
        state = object['Status'].get('State', None)
        health = object['Status'].get('Health', None)
    return state, health


def keyphrases2brat(keyphrases):
    """Receive keyphrases and return brat string"""
    brat_str = ''
    for keyphrase in keyphrases:
        keyphrase_id, (keyphrase_label_, (start, end)
            ), keyphrase_str = keyphrase
        brat_str += '%s\t%s %s %s\t%s\n' % (keyphrase_id, keyphrase_label_,
            start, end, keyphrase_str)
    return brat_str.strip('\n')


def _get_output_filename(dataset_dir, split_name):
    """Creates the output filename.

  Args:
    dataset_dir: The dataset directory where the dataset is stored.
    split_name: The name of the train/test split.

  Returns:
    An absolute file path.
  """
    return '%s/cifar10_%s.tfrecord' % (dataset_dir, split_name)


@staticmethod
def should_continue(best_particle):
    """
        Strategic method.

        Args:
            best_particle (Particle): best particle in swarm

        Raises:
            NotImplementedError: if not implemented.
        '"""
    raise NotImplementedError


def ballesteros_formula(color_bv):
    """
    Ballesteros formula.
    Estimate start temperature from B-V index.

    color_bv: B - V = -2.5 * log(F_b / F_v)

    :param color_bv: float; B-V index
    :return: float; temperature stimation
    """
    return 4600.0 * (1.0 / (0.92 * color_bv + 1.7) + 1.0 / (0.92 * color_bv +
        0.62))


def headTail(xs):
    """
    Return the head and tail from a list.
    """
    it = iter(xs)
    head = next(it)
    tail = list(it)
    return head, tail


def encrypt(message, key):
    """Encrypt message with key."""
    result = ''
    for letter in message:
        if letter.isalpha():
            num = ord(letter)
            if letter.isupper():
                base = ord('A')
            elif letter.islower():
                base = ord('a')
            num = (num - base + key) % 26 + base
            result += chr(num)
        elif letter.isdigit():
            result += letter
        else:
            result += letter
    return result


@staticmethod
def _sanityCheckExtensions(other):
    """Check if set extension settings are sane"""
    if other.useEncryptThenMAC not in (True, False):
        raise ValueError('useEncryptThenMAC can only be True or False')
    if other.useExtendedMasterSecret not in (True, False):
        raise ValueError('useExtendedMasterSecret must be True or False')
    if other.requireExtendedMasterSecret not in (True, False):
        raise ValueError('requireExtendedMasterSecret must be True or False')
    if other.requireExtendedMasterSecret and not other.useExtendedMasterSecret:
        raise ValueError(
            'requireExtendedMasterSecret requires useExtendedMasterSecret')
    if other.usePaddingExtension not in (True, False):
        raise ValueError('usePaddingExtension must be True or False')


def unitary_test():
    """ Unitary test for parallel.py script.
    """


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


@classmethod
def on(cls, window, *attributes):
    """Turn On Attributes."""
    collected = cls.collect(*attributes)
    window.attron(collected.value)
    return collected


@staticmethod
def change_contact_modhattr(contact, value):
    """Change contact modified host attribute value
        Format of the line that triggers function call::

        CHANGE_CONTACT_MODHATTR;<contact_name>;<value>

        :param contact: contact to edit
        :type contact: alignak.objects.contact.Contact
        :param value: new value to set
        :type value:str
        :return: None
        """
    contact.modified_host_attributes = int(value)


@classmethod
def _extract_error_message(cls, response):
    """Extracts an error message from an error response.

        If the server has sent a JSON response with an 'error' field, which is the typical
        behavior of the Realtime Database REST API, parses the response to retrieve the error
        message. If the server has sent a non-JSON response, returns the full response
        as the error message.
        """
    message = None
    try:
        data = response.json()
        if isinstance(data, dict):
            message = data.get('error')
    except ValueError:
        pass
    if not message:
        message = 'Unexpected response from database: {0}'.format(response.
            content.decode())
    return message


def _has_valid_ordered_variable_names(ordered_variable_names, variables):
    """Check if ordered_variable_names is present and that it includes all instance variables."""
    if not ordered_variable_names:
        return False
    return len(ordered_variable_names) == len(variables) and set(
        ordered_variable_names) == set(variables.keys())


def resolveRelationTokens(tokens):
    """Returns an iterable of relations for the tokens given"""


def bC_MgBOH4_Cl_FW86(T, P):
    """c-a: magnesium-borate chloride [FW86]."""
    b0 = 0.16
    b1 = 0
    b2 = 0
    C0 = 0
    C1 = 0
    alph1 = 2
    alph2 = -9
    omega = -9
    valid = T == 298.15
    return b0, b1, b2, C0, C1, alph1, alph2, omega, valid


def verify_line(line, length, lineno):
    """
    Verify the line read makes sense
    """
    if len(line) == 0 or line[0] == '':
        return False
    if len(line) == 1:
        raise ValueError('Error reading parameter %s on line %d' % (line[0],
            lineno))
    elif len(line) != length:
        raise ValueError('Cannot understand line %d' % lineno)
    return True


def wave_length_flv(frequency, wave_speed):
    """Usage: Finding the wave length using frequency and wave speed.
    λ=v/f"""
    return wave_speed / frequency


def add_commas_to_num(num: int):
    """Make numbers more readable"""
    new_num = ''
    num = str(num)[::-1]
    last_index = len(num) - 1
    for i, ltr in enumerate(num):
        new_num += ltr
        if (i + 1) % 3 == 0 and i < last_index:
            new_num += ','
    return new_num[::-1]


def string_to_version(verstring):
    """
    Return a tuple of (epoch, version, release) from a version string

    This function replaces rpmUtils.miscutils.stringToVersion, see
    https://bugzilla.redhat.com/1364504
    """
    components = verstring.split(':')
    if len(components) > 1:
        epoch = components[0]
    else:
        epoch = 0
    remaining = components[:2][0].split('-')
    version = remaining[0]
    release = remaining[1]
    return epoch, version, release


def html(text):
    """
    Macro tag <<html>>...<</html>>
    Pass-trought for html code (or other stuff)
    """
    return text


def _complete_from_cmd(cmd_obj, text, line, begidx, endidx):
    """Complete as though the user was typing inside cmd's cmdloop()"""
    from itertools import takewhile
    command_subcommand_params = line.split(None, 3)
    if len(command_subcommand_params) < (3 if text else 2):
        n = len(command_subcommand_params[0])
        n += sum(1 for _ in takewhile(str.isspace, line[n:]))
        return cmd_obj.completenames(text, line[n:], begidx - n, endidx - n)
    command, subcommand = command_subcommand_params[:2]
    n = len(command) + sum(1 for _ in takewhile(str.isspace, line))
    cfun = getattr(cmd_obj, 'complete_' + subcommand, cmd_obj.complete)
    return cfun(text, line[n:], begidx - n, endidx - n)


@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 = """
         {
            "dynamic":true,
            "properties": {
                "data": {
                    "properties": {
                        "commitMessage": {
                            "type": "text",
                            "index": true
                        },
                        "comments": {
                            "properties": {
                                "message": {
                                    "type": "text",
                                    "index": true
                                }
                            }
                        },
                        "subject": {
                            "type": "text",
                            "index": true
                        },
                        "patchSets": {
                            "properties": {
                                "approvals": {
                                    "properties": {
                                        "description": {
                                            "type": "text",
                                            "index": true
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        """
    return {'items': mapping}


def start_defrag(session, return_type=None, **kwargs):
    """
    Starts NAS share (XFS) defragging on the VPSA.

    :type session: zadarapy.session.Session
    :param session: A valid zadarapy.session.Session object.  Required.

    :type return_type: str
    :param return_type: If this is set to the string 'json', this function
        will return a JSON string.  Otherwise, it will return a Python
        dictionary.  Optional (will return a Python dictionary by default).

    :rtype: dict, str
    :returns: A dictionary or JSON data set as a string depending on
        return_type parameter.
    """
    path = '/api/settings/defrag_start.json'
    return session.post_api(path=path, return_type=return_type, **kwargs)


def extend_overstrand_forward(overstrand, end_cep):
    """
    Starting at a crossing (under or over), extend overstrand until you hit
    the next undercrossing.
    """
    cep = end_cep.next()
    overstrand.append(end_cep)
    while cep.is_over_crossing():
        overstrand.append(cep)
        cep = cep.next()
        if cep == overstrand[0]:
            break


def month_length(month):
    """Not the actual length of the month, but accounts for the 5 unlucky/nameless days"""
    if month == "Wayeb'":
        return 5
    else:
        return 20


@staticmethod
def should_analyze_file(modname, path, is_argument=False):
    """Returns whether or not a module should be checked.

        This implementation returns True for all python source file, indicating
        that all files should be linted.

        Subclasses may override this method to indicate that modules satisfying
        certain conditions should not be linted.

        :param str modname: The name of the module to be checked.
        :param str path: The full path to the source code of the module.
        :param bool is_argument: Whetter the file is an argument to pylint or not.
                                 Files which respect this property are always
                                 checked, since the user requested it explicitly.
        :returns: True if the module should be checked.
        :rtype: bool
        """
    if is_argument:
        return True
    return path.endswith('.py')


def _is_central_object_admin(object_list, bundle):
    """Return true if the central server user is allowed to access the objects"""
    user = bundle.request.user
    if not user.is_authenticated():
        return False
    else:
        for obj in object_list:
            if not user.get_profile().has_permission_for_object(obj):
                return False
        return True


def _getattr(obj, name, default):
    """Like getattr but return `default` if None or False.

    By default, getattr(obj, name, default) returns default only if
    attr does not exist, here, we return `default` even if attr evaluates to
    None or False.
    """
    value = getattr(obj, name, default)
    if value:
        return value
    else:
        return default


def consolidateBy(requestContext, seriesList, consolidationFunc):
    """
    Takes one metric or a wildcard seriesList and a consolidation function
    name.

    Valid function names are 'sum', 'average', 'min', and 'max'.

    When a graph is drawn where width of the graph size in pixels is smaller
    than the number of datapoints to be graphed, Graphite consolidates the
    values to to prevent line overlap. The consolidateBy() function changes
    the consolidation function from the default of 'average' to one of 'sum',
    'max', or 'min'. This is especially useful in sales graphs, where
    fractional values make no sense and a 'sum' of consolidated values is
    appropriate.

    Example::

        &target=consolidateBy(Sales.widgets.largeBlue, 'sum')
        &target=consolidateBy(Servers.web01.sda1.free_space, 'max')

    """
    for series in seriesList:
        series.consolidationFunc = consolidationFunc
        series.name = 'consolidateBy(%s,"%s")' % (series.name, series.
            consolidationFunc)
        series.pathExpression = series.name
    return seriesList


def start(st_reg_number):
    """Checks the number valiaty for the Ceara state"""
    divisor = 11
    if len(st_reg_number) > 9:
        return False
    if len(st_reg_number) < 9:
        return False
    sum_total = 0
    peso = 9
    for i in range(len(st_reg_number) - 1):
        sum_total = sum_total + int(st_reg_number[i]) * peso
        peso = peso - 1
    rest_division = sum_total % divisor
    digit = divisor - rest_division
    if digit == 10 or digit == 11:
        digit = 0
    return digit == int(st_reg_number[len(st_reg_number) - 1])


def update_package_data(distribution):
    """update build_py options to get package_data changes"""
    build_py = distribution.get_command_obj('build_py')
    build_py.finalize_options()


def change_owner_to(conn, schema, table, role):
    """Changes table's ownership to role

    Parameters
    ----------
    conn : sqlalchemy connection object
        A valid connection to a database
    schema : str
        The database schema
    table : str
        The database table
    role : str
        database role that access is granted to

    """
    sql_str = ("""ALTER TABLE {schema}.{table}
        OWNER TO {role};""".
        format(schema=schema, table=table, role=role))
    conn.execute(sql_str)


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 merge_included_mmd(mmd, included_mmd):
    """
    Merges two modulemds. This merges only metadata which are needed in
    the `main` when it includes another module defined by `included_mmd`
    """
    included_xmd = included_mmd.get_xmd()
    if 'rpms' in included_xmd['mbs']:
        xmd = mmd.get_xmd()
        if 'rpms' not in xmd['mbs']:
            xmd['mbs']['rpms'] = included_xmd['mbs']['rpms']
        else:
            xmd['mbs']['rpms'].update(included_xmd['mbs']['rpms'])
    mmd.set_xmd(xmd)


def intersect(i1, i2):
    """ Does the interval intersect with *i2*? """
    return i1.inf < i2.sup and i2.inf < i1.sup


@staticmethod
def address(peers):
    """Return rank in peers communicator"""
    return peers.Get_rank()


def get_headers(kwargs):
    """Get a single set of headers from the kwargs dict. A user agent is added
       as it is helpful in most cases.

       Parameters
       ==========
       kwargs: the dictionary of keyword arguments that may contain url
               parameters (format is url_param_<name>
    """
    headers = {'User-Agent': 'Mozilla/5.0'}
    for key, value in kwargs.items():
        if key.startswith('header_'):
            name = key.replace('header_', '', 1)
            if value is not None:
                headers[name] = value
            elif value is None and name in headers:
                del headers[name]
    return headers


def setitem_via_pathlist(ol, value, pathlist):
    """
        from elist.elist import *
        y = ['a',['b',["bb"]],'c']
        y[1][1]
        setitem_via_pathlist(y,"500",[1,1])
        y
    """
    this = ol
    for i in range(0, pathlist.__len__() - 1):
        key = pathlist[i]
        this = this.__getitem__(key)
    this.__setitem__(pathlist[-1], value)
    return ol


def set_masked_default(choice):
    """Set whether tables should be masked or not by default (True or False)"""
    global __masked__
    __masked__ = choice


def __getitem__(key):
    """
        Get the given key.  If item doesn't exist, raises C{KeyError}
        """


def delete_route_table(DryRun=None, RouteTableId=None):
    """
    Deletes the specified route table. You must disassociate the route table from any subnets before you can delete it. You can't delete the main route table.
    See also: AWS API Documentation

    Examples
    This example deletes the specified route table.
    Expected Output:

    :example: response = client.delete_route_table(
        DryRun=True|False,
        RouteTableId='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 RouteTableId: string
    :param RouteTableId: [REQUIRED]
            The ID of the route table.

    :return: response = client.delete_route_table(
        RouteTableId='rtb-22574640',
    )

    print(response)

    """
    pass


@classmethod
def decorated(cls):
    """
        Return a list of SEO meta instances for the class that decorate views.
        """
    metas = []
    for meta in list(cls._decorated.values()):
        if callable(meta.path):
            for path in meta.path():
                sub_meta = cls(**meta._document, path=path)
                metas.append(sub_meta)
        else:
            metas.append(meta)
    return metas


def _cons2tuple(seq, couple_alone=None, astype=tuple):
    """
    >>> _cons2tuple((4,))
    4
    >>> _cons2tuple((4,), couple_alone=0, astype=list)
    [4, 0]
    >>> _cons2tuple((4, 5, 6, 7))
    (4, 7)
    """
    if len(seq) == 1:
        ret = seq[0]
        if couple_alone is not None:
            if couple_alone != 'duplicate':
                ret = astype((seq[0], couple_alone))
            else:
                ret = astype((seq[0], seq[0]))
        return ret
    return astype((min(seq), max(seq)))


def get_flow_namespace(flow_class, base_namespace, ns_map=None):
    """Construct flow namespace from relative `ns_map` and current `base_namespace`."""
    if ns_map:
        ns = ns_map.get(flow_class) or ns_map.get(type(flow_class))
        if ns:
            return '{}:{}'.format(base_namespace, ns) if base_namespace else ns
    return base_namespace


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

        :param PaperContentArchiveDetails val:
        :rtype: EventDetails
        """
    return cls('paper_content_archive_details', val)


def ungroup(iterator):
    """Reverses the operation of `itertools.groupby`:func: (or similar).

    The `iterator` should produce pairs of ``(_, xs)``; where ``xs`` is
    another iterator (or iterable).

    It's guaranteed that the `iterator` will be consumed at the *boundaries*
    of each pair, i.e. before taking another pair ``(_, ys)`` from `iterator`
    the first ``xs`` will be fully yielded.

    Demonstration:

      >>> def groups():
      ...    def chunk(s):
      ...       for x in range(s, s+3):
      ...           print('Yielding x:', x)
      ...           yield x
      ...
      ...    for g in range(2):
      ...       print('Yielding group', g)
      ...       yield g, chunk(g)

      >>> list(ungroup(groups()))
      Yielding group 0
      Yielding x: 0
      Yielding x: 1
      Yielding x: 2
      Yielding group 1
      Yielding x: 1
      Yielding x: 2
      Yielding x: 3
      [0, 1, 2, 1, 2, 3]

    This is not the same as::

      >>> import itertools
      >>> xs = itertools.chain(*(xs for _, xs in groups()))
      Yielding group 0
      Yielding group 1

    Notice that the iterator was fully consumed just to create the arguments
    to ``chain()``.

    .. versionadded:: 1.7.3

    """
    for _, xs in iterator:
        for x in xs:
            yield x


def calc_chiller_quality_grade(nominal_conditions):
    """
    Calculates the quality grade for a given point of operation.

    Note
    ----
    This function is rather experimental.
    Please do not use it to estimate the quality grade of a real machine.
    A single point of operation might not be representative!

    .. calc_chiller_quality_grade-equations:

        :math:`\\eta =
        \\frac{\\dot{Q}_\\mathrm{chilled,nominal}}{\\dot{Q}_\\mathrm{hot,nominal}} /
        \\frac{T_\\mathrm{high, nominal}}{T_\\mathrm{high, nominal}
        - T_\\mathrm{low, nominal}}`

    Parameters
    ----------
    nominal_conditions : dict
        Dictionary describing one operating point (e.g., operation under STC)
        of the chiller by its
        cooling capacity, its electricity consumption and its COP
        ('nominal_Q_chill', 'nominal_el_consumption' and 'nominal_cop')

    Returns
    -------
    q_grade : numerical value
        Quality grade

    """
    t_h = nominal_conditions['t_high_nominal'] + 273.15
    t_l = nominal_conditions['t_low_nominal'] + 273.15
    nominal_cop = nominal_conditions['nominal_Q_chill'] / nominal_conditions[
        'nominal_el_consumption']
    q_grade = nominal_cop / (t_l / (t_h - t_l))
    return q_grade


@staticmethod
def b2_path(path):
    """
        Adjust a regular path to the form b2 can use in source code.
        """
    return path.replace('\\', '/')


@staticmethod
def competence(stochastic):
    """
        The competence function for AdaptiveMetropolis.
        The AM algorithm is well suited to deal with multivariate
        parameters, particularly those which are correlated with one
        another. However, it does not work reliably with all multivariate
        stochastics, so it must be applied manually via MCMC.use_step_method().
        """
    return 0


def processEnded(reason):
    """
        Called when the child process exits and all file descriptors associated
        with it have been closed.

        @type reason: L{twisted.python.failure.Failure}
        @param reason: A failure giving the reason the child process
            terminated.  The type of exception for this failure is either
            L{twisted.internet.error.ProcessDone} or
            L{twisted.internet.error.ProcessTerminated}.
        """


@staticmethod
def json_to_caption(subtitles_json):
    """Loops through the subtitles of the json response, concatenates all
        lines and returns all subtitles combined as a complete caption.

        Parameters
        ----------
        subtitles_json: dict
            The json response containing the subtitles of
            the screencap.

        Returns
        -------
        caption: str
            The subtitles combined as a complete caption."""
    caption = ''
    for quote in subtitles_json['Subtitles']:
        caption += quote['Content'] + ' '
    return caption


def shaderfx_remove(shaderfx: str=''):
    """Remove a shaderfx from the active grease pencil object

    :param shaderfx: Shader, Name of the shaderfx to edit
    :type shaderfx: str
    """
    pass


def int_or_str(text):
    """Helper function for argument parsing."""
    try:
        return int(text)
    except ValueError:
        return text


def cache_div(key, value=2, expires=None, cache=None):
    """Divides the specified key value by the specified value.

    * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.9.html#math-for-cache

    :param str|unicode key:

    :param int value:

    :param int expires: Expire timeout (seconds).

    :param str|unicode cache: Cache name with optional address (if @-syntax is used).

    :rtype: bool
    """
    return False


def parse_numeric(s):
    """
    For use in graph analysis,
    function returns list with [PHX] converted to numeric [X]
    """
    case_list = []
    for i in s:
        case_list = case_list + [i.split('H')[-1]]
    return case_list


def makeVocabulary(source, targets=None):
    """Returns a list of aggregated brains.

        The targets argument may be either None or a list of IBrainAggregates.
        None is to signal that the provider must build a list of
        IBrainAggregates itself. If targets are given, the provider must filter
        them."""


def __or__(i1, i2):
    """ Return the union of i1 and i2
        """
    return i1.__class__(i1.x | i2.x, i1.y | i2.y)


@classmethod
def lookup_boxtype(cls, name):
    """
        Find the appropriate BoxType associated with the given name.
        """
    for spec in cls.definitions.values():
        for boxlist in spec.values():
            for boxtype in boxlist:
                if boxtype.name == name:
                    return boxtype


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

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

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

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

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

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

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

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


@staticmethod
def _calc_decimaldegree(degree, minute, second):
    """
        Calculate decimal degree form degree, minute, second
        """
    return degree + minute / 60.0 + second / 3600.0


def single_fscore_PR(prec, rec, beta):
    """ Computes an F-score from a precision and recall score """
    betasq = beta ** 2
    if prec == 0.0 or rec == 0.0:
        return 0.0
    return (1 + betasq) / (1.0 / prec + betasq / rec)


@staticmethod
def concat_url(endpoint, url):
    """Concatenate endpoint and final URL.

        E.g., "http://keystone/v2.0/" and "/tokens" are concatenated to
        "http://keystone/v2.0/tokens".

        :param endpoint: the base URL
        :param url: the final URL
        """
    return '%s/%s' % (endpoint.rstrip('/'), url.strip('/'))


def is_model_abstract(model):
    """True if abstract is True in Meta class"""
    return model._meta.abstract


def getNodeType(nodeIdentifier):
    """ Return type of a node.

        @return: a deferred that returns either 'leaf' or 'collection'
        """


def first_true(pred, iterable, default=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    source: https://docs.python.org/3/library/itertools.html
    """
    return next(filter(pred, iterable), default)


def Varsigma(D_ox, D_red):
    """
    See explantion in C_redox_Estep_semiinfinite()
    Kristian B. Knudsen (kknu@berkeley.edu || Kristianbknudsen@gmail.com)
    """
    return (D_ox / D_red) ** (1 / 2)


def metric_set(key, value):
    """Sets metric value.

    :param str|unicode key:

    :param int|long value:

    :rtype: bool
    """
    return False


def compute_resize_scale(image_shape, min_side=800, max_side=1333):
    """
    Compute an image scale such that the image size is constrained to min_side and max_side.

    Args
        min_side: The image's min side will be equal to min_side after resizing.
        max_side: If after resizing the image's max side is above max_side, resize until the max side is equal to max_side.

    Returns
        A resizing scale.
    """
    rows, cols, _ = image_shape
    smallest_side = min(rows, cols)
    scale = min_side / smallest_side
    largest_side = max(rows, cols)
    if largest_side * scale > max_side:
        scale = max_side / largest_side
    return scale


def flags_from_dict(kw):
    """
    This turns a dict with keys that are flags (e.g. for CLOSECIRCUIT,
    CLOSESTREAM) only if the values are true.
    """
    if len(kw) == 0:
        return ''
    flags = ''
    for k, v in kw.items():
        if v:
            flags += ' ' + str(k)
    return flags


@staticmethod
def get_configure_command(config_options=None):
    """
        Get the command to configure the package

        Parameters
        ----------
        config_options : dict
            Configuration options to use with `./configure`.
            The configuration options will be converted to `--key=val` during
            runtime

        Returns
        -------
        config_str : str
            The configuration command
        """
    options = ''
    if config_options is not None:
        for key, val in config_options.items():
            if val is not None:
                options += f' --{key}={val}'
            else:
                options += f' --{key}'
    config_str = f'./configure{options}'
    return config_str


@classmethod
def get_instance(cls, template_path='templates'):
    """Singleton get instance"""
    if cls.__instance is None:
        cls.__instance = cls(template_path)
    return cls.__instance


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

    """
    pass


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


def __call__():
    """Return an iterable of the group ids for the adapted principal
        """


@classmethod
def from_celcius(cls, val):
    """Convert `val` ºC to K"""
    return (val + 273.15) * cls.kelvin


def rolling_volatility(data, n=10):
    """
	Generate Rolling Standard Deviation of a Series
	n= window size
	"""
    return data.rolling(window=n).std()


def create_qtr_list(time_range):
    """
    From a given time_range, create the list of qtr contained in it. Includes both qtr in the time_range. time_range
    is of the form [(year, QTR), (year, QTR)].

    :param time_range: a list of two tuples representing the start and finish qtr
    :return: a list of all the qtr included in the time_range.
    """
    assert len(time_range) == 2
    assert 1994 <= time_range[0][0] and 1994 <= time_range[1][0]
    assert 1 <= time_range[0][1] <= 4 and 1 <= time_range[1][1] <= 4
    assert time_range[1][0] >= time_range[0][0]
    if time_range[1][0] == time_range[0][0]:
        assert time_range[1][1] >= time_range[0][1]
    list_qtr = []
    for year in range(time_range[0][0], time_range[1][0] + 1):
        for qtr in range(1, 5):
            if year == time_range[0][0]:
                if qtr < time_range[0][1]:
                    continue
            if year == time_range[1][0]:
                if qtr > time_range[1][1]:
                    break
            list_qtr.append((year, qtr))
    assert list_qtr[0] == time_range[0]
    assert list_qtr[-1] == time_range[1]
    return list_qtr


def sens_info():
    """Gives back max coil number of coefficient number."""
    return 8, 36


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

        :param SharedContentChangeMemberRoleDetails val:
        :rtype: EventDetails
        """
    return cls('shared_content_change_member_role_details', val)


def _get_domain_id(physical_ports):
    """Get CFAB domain_id from port."""
    return physical_ports[0]


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

        :param NoteSharedType val:
        :rtype: EventType
        """
    return cls('note_shared', val)


@staticmethod
def node_name(node):
    """
        Returns the name of the given node
        :param node: str
        :return: str
        """
    return node


def _append_commands(dct, module_name, commands):
    """Append entry point strings representing the given Command objects.

    Args:
        dct: The dictionary to append with entry point strings. Each key will
            be a primary command with a value containing a list of entry point
            strings representing a Command.
        module_name: The name of the module in which the command object
            resides.
        commands: A list of Command objects to convert to entry point strings.
    """
    for command in commands:
        entry_point = '{command}{subcommand} = {module}{callable}'.format(
            command=command.command, subcommand=':{}'.format(command.
            subcommand) if command.subcommand else '', module=module_name,
            callable=':{}'.format(command.callable) if command.callable else ''
            )
        dct.setdefault(command.command, set()).add(entry_point)


def _convert_seconds(seconds):
    """Convert seconds to minutes:seconds format"""
    return '{0:.0f}:{1:02.0f}'.format(*divmod(float(seconds), 60))


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

        :param GroupMovedType val:
        :rtype: EventType
        """
    return cls('group_moved', val)


def SET_IS_SUBSET(*expressions):
    """
    Takes two arrays and returns true when the first array is a subset of the second,
    including when the first array equals the second array, and false otherwise.
    https://docs.mongodb.com/manual/reference/operator/aggregation/setIsSubset/
    for more details
    :param expressions: The arrays (expressions)
    :return: Aggregation operator
    """
    return {'$setIsSubset': list(expressions)}


@classmethod
def primary_key(cls):
    """Return the name of the table's primary key

        :rtype: string

        """
    if cls.__from_class__:
        cls = cls.__from_class__
    return cls.__table__.primary_key.columns.values()[0].name


def arr_subtract(array):
    """
    definition: func( array[] ) {...}
    objective : returns the subtraction of all elements in the given array
    """
    result = array[0]
    for i in range(1, len(array), 1):
        result -= array[i]
    return result


def _apply_rewrites(date_classes, rules):
    """
    Return a list of date elements by applying rewrites to the initial date element list
    """
    for rule in rules:
        date_classes = rule.execute(date_classes)
    return date_classes


def unmatch_pair(suitor, reviewer):
    """ Unmatch a (suitor, reviewer) pair. """
    suitor.unmatch()
    reviewer.unmatch()


def cache_id(value):
    """Returns a cache id for the given value"""
    try:
        return getattr(value, 'cacheID')()
    except Exception:
        return str(value)


def __remove_col_and_row_and_set_to_inf(matrix, row_col_tuple):
    """Create new submatrix with row/col crossed out and (row, col) set to 0"""


def cmd_check(check_input, return_type=str):
    """
	Allows user to execute commands at any point

	check_input: Input to be checked
	"""
    if check_input == 'exit':
        exit()
    return check_input


def key_for_name(name):
    """Return the key name used to store the given queue name in Redis."""
    return 'hotqueue:%s' % name


@staticmethod
def __is_code_successful(response_code):
    """Check if the response is a successful response
        :type response_code: int
        :rtype: bool
        """
    return 200 <= response_code < 300


def valid_date_format(date):
    """Validates a general date by making sure it is 8 digits long, are only digits and the year can only contain a 2 or 1 in the front (to exlude 0123,3000,4000)

    Args:
        date:str
    Returns:
        returns Boolean
    """
    if len(date) == 8 and date.isdigit() and (date[0] == '2' or date[0] == '1'
        ):
        return True
    else:
        return False


def _extract_prop_general(line):
    """
    Extract the (key, value)-tuple from a "standard" property line like:
    >>> 'hardware ethernet 12:34:56:78:90:AB'
    :param line:
    :return: tuple (key, value)
    """
    pos = line.find(' ')
    return line[:pos], line[pos + 1:]


def is_iter(obj):
    """
    Check if obj contains '__iter__' attribute
    :param obj: the object of check
    :return: ``True`` if contains, other else, ``False``
    """
    return hasattr(obj, '__iter__')


def mean(values):
    """
    Compute the arithmetic mean (“average”) of values.

    :type  values: list[float]
    :param values: List of floats
    :return: Mean of values.

    .. deprecated:: 2.5.0
       Since Python 3.4, you can use the standard function :func:`statistics.mean`.
    """
    return sum(values) / len(values)


@classmethod
def set_bp(cls, ctx, register, address, trigger, watch):
    """
        Sets a hardware breakpoint.

        @see: clear_bp, find_slot

        @type  ctx: dict( str S{->} int )
        @param ctx: Thread context dictionary.

        @type  register: int
        @param register: Slot (debug register).

        @type  address: int
        @param address: Memory address.

        @type  trigger: int
        @param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}.

        @type  watch: int
        @param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}.
        """
    Dr7 = ctx['Dr7']
    Dr7 |= cls.enableMask[register]
    orMask, andMask = cls.triggerMask[register][trigger]
    Dr7 &= andMask
    Dr7 |= orMask
    orMask, andMask = cls.watchMask[register][watch]
    Dr7 &= andMask
    Dr7 |= orMask
    ctx['Dr7'] = Dr7
    ctx['Dr%d' % register] = address


def split_trailing_whitespace(word):
    """
    This function takes a word, such as 'test

' and returns ('test','

')
    """
    stripped_length = len(word.rstrip())
    return word[0:stripped_length], word[stripped_length:]


def _rolling_window_iter(iterator, window, step):
    """It yields lists of items with a window number of elements giving
     an iterator"""
    items = []
    for item in iterator:
        if len(items) >= window:
            yield items
            items = items[step:]
        items.append(item)
    else:
        if len(items) >= window:
            yield items


def get_rendition_upload_to(instance, filename):
    """
    Obtain a valid upload path for an image rendition file.

    This needs to be a module-level function so that it can be referenced within migrations,
    but simply delegates to the `get_upload_to` method of the instance, so that AbstractRendition
    subclasses can override it.
    """
    return instance.get_upload_to(filename)


@staticmethod
def filtered_iteritems(d, filter_keys):
    """A generator that filters a dict's items to keys in `filter_keys`.

        Args:
            d (:obj:`dict`): dictionary to filter.
            filter_keys (:obj:`list` of :obj:`str`): list of keys to retain.

        Yields:
            :obj:`tuple`: (key, value) tuples from `d` whose keys are in `filter_keys`.
        """
    for key, val in d.items():
        if key not in filter_keys:
            continue
        yield key, val


def _leadingTabs(text, tabSize, tabsAtMost=-1):
    """
    Returns the number of leading tabs.
    If there are 'tabSize' number of consecutive spaces,
    then this will interpreted as a single tab.

    text (string):
    The text from which to count the leading tabs from.

    tabSize (integer):
    The number of spaces in a tab.

    tabsAtMost (integer):
    The number of leading tabs to count at most.
    If this is negative, then the number of tabs
    to count is not limited.

    returns (integer, integer):
    The first number of is the number of leading tabs,
    as defined above. The second number is the number
    of leading characters taking part to this count.
    """
    tabs = 0
    consecutiveSpaces = 0
    characters = 0
    for c in text:
        if c == '\t':
            tabs += 1
            characters += consecutiveSpaces + 1
            consecutiveSpaces = 0
        elif c == ' ':
            consecutiveSpaces += 1
            if consecutiveSpaces == tabSize:
                tabs += 1
                characters += consecutiveSpaces
                consecutiveSpaces = 0
        else:
            break
        if tabsAtMost >= 0 and tabs == tabsAtMost:
            break
    return tabs, characters


@classmethod
def __register_instance(cls, instance):
    """
        Notify the callbacks in OphydObject.instantiation_callbacks of an instance.
        """
    for callback in cls.__instantiation_callbacks:
        callback(instance)


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 list_numbering_start(attrs):
    """extract numbering from list element attributes"""
    if 'start' in attrs:
        return int(attrs['start']) - 1
    else:
        return 0


def default_document_verifier(doc):
    """
    By default we try to index the document.

    In `production` environments you should set the `document_verifier` via
    `Solr.__init__()` in order to minimize the traffic to solr.
    """
    return {'ok': 'true'}


@staticmethod
def formatlist(data, name, fmt, sep):
    """convert iterable to appropriate list format"""
    return list(data)


def quote(str):
    """Prepare string to be used in a quoted string.

    Turns backslash and double quote characters into quoted pairs.  These
    are the only characters that need to be quoted inside a quoted string.
    Does not add the surrounding double quotes.
    """
    return str.replace('\\', '\\\\').replace('"', '\\"')


def specificity(tp=None, tn=None, fp=None, fn=None):
    """Specificity [0, 1]

    This function is designed to be used with the confusion performance
    function below. If you only want to specify tp and fn, please use keyword
    arguments when calling.

    :param int tp: number of true positives
    :param int tn: number of true negatives
    :param int fp: number of false positives
    :param int fn: number of false negatives
    :rtype: float
    """
    return tp / float(tp + fn)


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 make_lhs_reminder(lhs, canon):
    """Return a reminder for a relation's left hand side
    (i.e a VariableRef object).
    """
    try:
        lhs = canon['all_variables'][lhs.variable][0]
    except (KeyError, IndexError):
        pass
    return '=', lhs


@classmethod
def from_asyncio_future(cls, asyncio_f, loop=None):
    """
        Return a prompt_toolkit `Future` from the given asyncio Future.
        """
    f = cls(loop=loop)

    @asyncio_f.add_done_callback
    def _(asyncio_f):
        if asyncio_f.exception():
            f.set_exception(asyncio_f.exception())
        else:
            f.set_result(asyncio_f.result())
    return f


def truth(a):
    """Return True if a is true, False otherwise."""
    return True if a else False


def create_product(AcceptLanguage=None, Name=None, Owner=None, Description=
    None, Distributor=None, SupportDescription=None, SupportEmail=None,
    SupportUrl=None, ProductType=None, Tags=None,
    ProvisioningArtifactParameters=None, IdempotencyToken=None):
    """
    Creates a new product.
    See also: AWS API Documentation

    :example: response = client.create_product(
        AcceptLanguage='string',
        Name='string',
        Owner='string',
        Description='string',
        Distributor='string',
        SupportDescription='string',
        SupportEmail='string',
        SupportUrl='string',
        ProductType='CLOUD_FORMATION_TEMPLATE',
        Tags=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ],
        ProvisioningArtifactParameters={
            'Name': 'string',
            'Description': 'string',
            'Info': {
                'string': 'string'
            },
            'Type': 'CLOUD_FORMATION_TEMPLATE'
        },
        IdempotencyToken='string'
    )

    :type AcceptLanguage: string
    :param AcceptLanguage: The language code to use for this operation. Supported language codes are as follows:
            'en' (English)
            'jp' (Japanese)
            'zh' (Chinese)
            If no code is specified, 'en' is used as the default.

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

    :type Owner: string
    :param Owner: [REQUIRED]
            The owner of the product.

    :type Description: string
    :param Description: The text description of the product.

    :type Distributor: string
    :param Distributor: The distributor of the product.

    :type SupportDescription: string
    :param SupportDescription: Support information about the product.

    :type SupportEmail: string
    :param SupportEmail: Contact email for product support.

    :type SupportUrl: string
    :param SupportUrl: Contact URL for product support.

    :type ProductType: string
    :param ProductType: [REQUIRED]
            The type of the product to create.

    :type Tags: list
    :param Tags: Tags to associate with the new product.
            (dict) --Key/value pairs to associate with this provisioning. These tags are entirely discretionary and are propagated to the resources created in the provisioning.
            Key (string) -- [REQUIRED]The ProvisioningArtifactParameter.TagKey parameter from DescribeProvisioningParameters .
            Value (string) -- [REQUIRED]The esired value for this key.

    :type ProvisioningArtifactParameters: dict
    :param ProvisioningArtifactParameters: [REQUIRED]
            Parameters for the provisioning artifact.
            Name (string) --The name assigned to the provisioning artifact properties.
            Description (string) --The text description of the provisioning artifact properties.
            Info (dict) -- [REQUIRED]Additional information about the provisioning artifact properties.
            (string) --
            (string) --

            Type (string) --The type of the provisioning artifact properties.

    :type IdempotencyToken: string
    :param IdempotencyToken: [REQUIRED]
            A token to disambiguate duplicate requests. You can create multiple resources using the same input in multiple requests, provided that you also specify a different idempotency token for each request.
            This field is autopopulated if not provided.

    :rtype: dict
    :return: {
        'ProductViewDetail': {
            'ProductViewSummary': {
                'Id': 'string',
                'ProductId': 'string',
                'Name': 'string',
                'Owner': 'string',
                'ShortDescription': 'string',
                'Type': 'CLOUD_FORMATION_TEMPLATE',
                'Distributor': 'string',
                'HasDefaultPath': True|False,
                'SupportEmail': 'string',
                'SupportDescription': 'string',
                'SupportUrl': 'string'
            },
            'Status': 'AVAILABLE'|'CREATING'|'FAILED',
            'ProductARN': 'string',
            'CreatedTime': datetime(2015, 1, 1)
        },
        'ProvisioningArtifactDetail': {
            'Id': 'string',
            'Name': 'string',
            'Description': 'string',
            'Type': 'CLOUD_FORMATION_TEMPLATE',
            'CreatedTime': datetime(2015, 1, 1)
        },
        'Tags': [
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    }

    """
    pass


def preloaded_multi_mp_sgd_mom_update(*data, **kwargs):
    """Momentum update function for multi-precision Stochastic Gradient Descent (SGD) optimizer.

    Momentum update has better convergence rates on neural networks. Mathematically it looks
    like below:

    .. math::

      v_1 = \\alpha * \\nabla J(W_0)\\\\
      v_t = \\gamma v_{t-1} - \\alpha * \\nabla J(W_{t-1})\\\\
      W_t = W_{t-1} + v_t

    It updates the weights using::

      v = momentum * v - learning_rate * gradient
      weight += v

    Where the parameter ``momentum`` is the decay rate of momentum estimates at each epoch.

    Defined in src/operator/contrib/preloaded_multi_sgd.cc:L200

    Parameters
    ----------
    data : Symbol[]
        Weights, gradients, momentums, learning rates and weight decays
    momentum : float, optional, default=0
        The decay rate of momentum estimates at each epoch.
    rescale_grad : float, optional, default=1
        Rescale gradient to grad = rescale_grad*grad.
    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,


@classmethod
def get_schema_cls(cls):
    """ Returns the Schema class associated with the model class.
        """
    return cls._schema_cls


def _parse_rays_wrap_around(rays_wrap_around, radar):
    """ Parse the rays_wrap_around parameter. """
    if rays_wrap_around is None:
        if radar.scan_type == 'ppi':
            rays_wrap_around = True
        else:
            rays_wrap_around = False
    return rays_wrap_around


@classmethod
def get(cls, index):
    """
        Returns the :class:`.IOLine` for the given index.

        Args:
            index (Integer): Returns the :class:`.IOLine` for the given index.

        Returns:
            :class:`.IOLine`: :class:`.IOLine` with the given code, ``None`` if there is not any line with that index.
        """
    try:
        return cls.lookupTable[index]
    except KeyError:
        return None


def white_lowering_function(gamma_corrected_luma):
    """
    White is not very important for this filter.
    """
    t = 0.7
    if gamma_corrected_luma > t:
        return gamma_corrected_luma - gamma_corrected_luma * 0.25 * ((
            gamma_corrected_luma - t) / (1 - t))
    else:
        return gamma_corrected_luma


def escapeHDFDataName(name):
    """Return escaped dataset name for saving in HDF5 files.
    This is because names cannot include / characters in HDF5
    """
    name = name.replace('`', '`BT')
    name = name.replace('/', '`SL')
    return name.encode('utf-8')


def set_printoptions(precision=None, threshold=None, edgeitems=None,
    linewidth=None, suppress=None, nanstr=None, infstr=None, formatter=None):
    """
    Set printing options.

    These options determine the way floating point numbers, arrays and
    other NumPy objects are displayed.

    Parameters
    ----------
    precision : int, optional
        Number of digits of precision for floating point output (default 8).
    threshold : int, optional
        Total number of array elements which trigger summarization
        rather than full repr (default 1000).
    edgeitems : int, optional
        Number of array items in summary at beginning and end of
        each dimension (default 3).
    linewidth : int, optional
        The number of characters per line for the purpose of inserting
        line breaks (default 75).
    suppress : bool, optional
        Whether or not suppress printing of small floating point values
        using scientific notation (default False).
    nanstr : str, optional
        String representation of floating point not-a-number (default nan).
    infstr : str, optional
        String representation of floating point infinity (default inf).
    formatter : dict of callables, optional
        If not None, the keys should indicate the type(s) that the respective
        formatting function applies to.  Callables should return a string.
        Types that are not specified (by their corresponding keys) are handled
        by the default formatters.  Individual types for which a formatter
        can be set are::

            - 'bool'
            - 'int'
            - 'timedelta' : a `numpy.timedelta64`
            - 'datetime' : a `numpy.datetime64`
            - 'float'
            - 'longfloat' : 128-bit floats
            - 'complexfloat'
            - 'longcomplexfloat' : composed of two 128-bit floats
            - 'numpy_str' : types `numpy.string_` and `numpy.unicode_`
            - 'str' : all other strings

        Other keys that can be used to set a group of types at once are::

            - 'all' : sets all types
            - 'int_kind' : sets 'int'
            - 'float_kind' : sets 'float' and 'longfloat'
            - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat'
            - 'str_kind' : sets 'str' and 'numpystr'

    See Also
    --------
    get_printoptions, set_string_function, array2string

    Notes
    -----
    `formatter` is always reset with a call to `set_printoptions`.

    Examples
    --------
    Floating point precision can be set:

    >>> import numpy as np
    >>> np.set_printoptions(precision=4)
    >>> print(np.array([1.123456789]))
    [ 1.1235]

    Long arrays can be summarised:

    >>> np.set_printoptions(threshold=5)
    >>> print(np.arange(10))
    [0 1 2 ..., 7 8 9]

    Small results can be suppressed:

    >>> eps = np.finfo(float).eps
    >>> x = np.arange(4.)
    >>> x**2 - (x + eps)**2
    array([ -4.9304e-32,  -4.4409e-16,   0.0000e+00,   0.0000e+00])
    >>> np.set_printoptions(suppress=True)
    >>> x**2 - (x + eps)**2
    array([-0., -0.,  0.,  0.])

    A custom formatter can be used to display array elements as desired:

    >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)})
    >>> x = np.arange(3)
    >>> x
    array([int: 0, int: -1, int: -2])
    >>> np.set_printoptions()  # formatter gets reset
    >>> x
    array([0, 1, 2])

    To put back the default options, you can use:

    >>> np.set_printoptions(edgeitems=3,infstr='inf',
    ... linewidth=75, nanstr='nan', precision=8,
    ... suppress=False, threshold=1000, formatter=None)
    """
    global _summaryThreshold, _summaryEdgeItems, _float_output_precision, _line_width, _float_output_suppress_small, _nan_str, _inf_str, _formatter
    if linewidth is not None:
        _line_width = linewidth
    if threshold is not None:
        _summaryThreshold = threshold
    if edgeitems is not None:
        _summaryEdgeItems = edgeitems
    if precision is not None:
        _float_output_precision = precision
    if suppress is not None:
        _float_output_suppress_small = not not suppress
    if nanstr is not None:
        _nan_str = nanstr
    if infstr is not None:
        _inf_str = infstr
    _formatter = formatter


def run_one_step_catchment(area_m2, time_gap_sec, c_in_rain, c_in_peva,
    c_p_t, c_p_c, c_p_h, c_p_d, c_p_s, c_p_z, c_p_sk, c_p_fk, c_p_gk,
    c_s_v_ove, c_s_v_dra, c_s_v_int, c_s_v_sgw, c_s_v_dgw, c_s_v_ly1,
    c_s_v_ly2, c_s_v_ly3, c_s_v_ly4, c_s_v_ly5, c_s_v_ly6):
    """
    This function was written by Thibault Hallouin but is largely inspired by the work of Eva Mockler, namely for
    the work published in: Mockler, E., O’Loughlin, F., and Bruen, M.: Understanding hydrological flow paths in
    conceptual catchment models using uncertainty and sensitivity analysis, Computers & Geosciences, 90, 66–77,
    doi:10.1016/j.cageo.2015.08.015, 2016.

    Catchment model * c_ *
    _ Hydrology
    ___ Inputs * in_ *
    _____ c_in_rain         precipitation as rain [mm/time step]
    _____ c_in_peva         potential evapotranspiration [mm/time step]
    ___ Parameters * p_ *
    _____ c_p_t             T: rainfall aerial correction coefficient
    _____ c_p_c             C: evaporation decay parameter
    _____ c_p_h             H: quick runoff coefficient
    _____ c_p_d             D: drain flow parameter - fraction of saturation excess diverted to drain flow
    _____ c_p_s             S: soil outflow coefficient
    _____ c_p_z             Z: effective soil depth [mm]
    _____ c_p_sk            SK: surface routing parameter [hours]
    _____ c_p_fk            FK: inter flow routing parameter [hours]
    _____ c_p_gk            GK: groundwater routing parameter [hours]
    ___ States * s_ *
    _____ c_s_v_ove         volume of water in overland store [m3]
    _____ c_s_v_dra         volume of water in drain store [m3]
    _____ c_s_v_int         volume of water in inter store [m3]
    _____ c_s_v_sgw         volume of water in shallow groundwater store [m3]
    _____ c_s_v_dgw         volume of water in deep groundwater store [m3]
    _____ c_s_v_ly1         volume of water in first soil layer store [m3]
    _____ c_s_v_ly2         volume of water in second soil layer store [m3]
    _____ c_s_v_ly3         volume of water in third soil layer store [m3]
    _____ c_s_v_ly4         volume of water in fourth soil layer store [m3]
    _____ c_s_v_ly5         volume of water in fifth soil layer store [m3]
    _____ c_s_v_ly6         volume of water in sixth soil layer store [m3]
    ___ Outputs * out_ *
    _____ c_out_aeva        actual evapotranspiration [m3/s]
    _____ c_out_q_ove       overland flow [m3/s]
    _____ c_out_q_dra       drain flow [m3/s]
    _____ c_out_q_int       inter flow [m3/s]
    _____ c_out_q_sgw       shallow groundwater flow [m3/s]
    _____ c_out_q_dgw       deep groundwater flow [m3/s]
    """
    nb_soil_layers = 6.0
    c_p_sk *= 3600.0
    c_p_fk *= 3600.0
    c_p_gk *= 3600.0
    list_z_lyr = [0.0, c_p_z / nb_soil_layers, c_p_z / nb_soil_layers,
        c_p_z / nb_soil_layers, c_p_z / nb_soil_layers, c_p_z /
        nb_soil_layers, c_p_z / nb_soil_layers]
    list_lvl_lyr = [0.0, c_s_v_ly1 / area_m2 * 1000.0, c_s_v_ly2 / area_m2 *
        1000.0, c_s_v_ly3 / area_m2 * 1000.0, c_s_v_ly4 / area_m2 * 1000.0,
        c_s_v_ly5 / area_m2 * 1000.0, c_s_v_ly6 / area_m2 * 1000.0]
    lvl_total_start = sum(list_lvl_lyr)
    rain = c_in_rain * c_p_t
    excess_rain = rain - c_in_peva
    aeva = 0.0
    if excess_rain >= 0.0:
        aeva += c_in_peva
        h_prime = c_p_h * (lvl_total_start / c_p_z)
        overland_flow = h_prime * excess_rain
        excess_rain -= overland_flow
        for i in [1, 2, 3, 4, 5, 6]:
            space_in_lyr = list_z_lyr[i] - list_lvl_lyr[i]
            if excess_rain <= space_in_lyr:
                list_lvl_lyr[i] += excess_rain
                excess_rain = 0.0
            else:
                list_lvl_lyr[i] = list_z_lyr[i]
                excess_rain -= space_in_lyr
        drain_flow = c_p_d * excess_rain
        inter_flow = (1.0 - c_p_d) * excess_rain
        s_prime = c_p_s * (lvl_total_start / c_p_z)
        for i in [1, 2, 3, 4, 5, 6]:
            leak_interflow = list_lvl_lyr[i] * s_prime ** i
            if leak_interflow < list_lvl_lyr[i]:
                inter_flow += leak_interflow
                list_lvl_lyr[i] -= leak_interflow
        shallow_flow = 0.0
        for i in [1, 2, 3, 4, 5, 6]:
            leak_shallow_flow = list_lvl_lyr[i] * (s_prime / i)
            if leak_shallow_flow < list_lvl_lyr[i]:
                shallow_flow += leak_shallow_flow
                list_lvl_lyr[i] -= leak_shallow_flow
        deep_flow = 0.0
        for i in [6, 5, 4, 3, 2, 1]:
            leak_deep_flow = list_lvl_lyr[i] * s_prime ** (7 - i)
            if leak_deep_flow < list_lvl_lyr[i]:
                deep_flow += leak_deep_flow
                list_lvl_lyr[i] -= leak_deep_flow
    else:
        overland_flow = 0.0
        drain_flow = 0.0
        inter_flow = 0.0
        shallow_flow = 0.0
        deep_flow = 0.0
        deficit_rain = excess_rain * -1.0
        aeva += rain
        for i in [1, 2, 3, 4, 5, 6]:
            if list_lvl_lyr[i] >= deficit_rain:
                list_lvl_lyr[i] -= deficit_rain
                aeva += deficit_rain
                deficit_rain = 0.0
            else:
                aeva += list_lvl_lyr[i]
                deficit_rain = c_p_c * (deficit_rain - list_lvl_lyr[i])
                list_lvl_lyr[i] = 0.0
    c_out_aeva = aeva / 1000.0 * area_m2 / time_gap_sec
    c_out_q_h2o_ove = c_s_v_ove / c_p_sk
    c_s_v_ove += (overland_flow / 1000.0 * area_m2 - c_out_q_h2o_ove *
        time_gap_sec)
    if c_s_v_ove < 0.0:
        c_s_v_ove = 0.0
    c_out_q_h2o_dra = c_s_v_dra / c_p_sk
    c_s_v_dra += drain_flow / 1000.0 * area_m2 - c_out_q_h2o_dra * time_gap_sec
    if c_s_v_dra < 0.0:
        c_s_v_dra = 0.0
    c_out_q_h2o_int = c_s_v_int / c_p_fk
    c_s_v_int += inter_flow / 1000.0 * area_m2 - c_out_q_h2o_int * time_gap_sec
    if c_s_v_int < 0.0:
        c_s_v_int = 0.0
    c_out_q_h2o_sgw = c_s_v_sgw / c_p_gk
    c_s_v_sgw += (shallow_flow / 1000.0 * area_m2 - c_out_q_h2o_sgw *
        time_gap_sec)
    if c_s_v_sgw < 0.0:
        c_s_v_sgw = 0.0
    c_out_q_h2o_dgw = c_s_v_dgw / c_p_gk
    c_s_v_dgw += deep_flow / 1000.0 * area_m2 - c_out_q_h2o_dgw * time_gap_sec
    if c_s_v_dgw < 0.0:
        c_s_v_dgw = 0.0
    return (c_out_aeva, c_out_q_h2o_ove, c_out_q_h2o_dra, c_out_q_h2o_int,
        c_out_q_h2o_sgw, c_out_q_h2o_dgw, c_s_v_ove, c_s_v_dra, c_s_v_int,
        c_s_v_sgw, c_s_v_dgw, list_lvl_lyr[1] / 1000.0 * area_m2,
        list_lvl_lyr[2] / 1000.0 * area_m2, list_lvl_lyr[3] / 1000.0 *
        area_m2, list_lvl_lyr[4] / 1000.0 * area_m2, list_lvl_lyr[5] /
        1000.0 * area_m2, list_lvl_lyr[6] / 1000.0 * area_m2)


def convert2boolean(arg):
    """convert2boolean is used for environmental variables
       that must be returned as boolean

       Parameters
       ==========
       arg: the argument to convert to boolean. Must be a string given
       grabbed from environment.
    """
    if not isinstance(arg, bool):
        return arg.lower() in ('yes', 'true', 't', '1', 'y')
    return arg


def get_allowed_types():
    """Return a dictionnary, with two keys, ``requires`` and
        ``excepts`` that would a list of interfaces that items should
        implement in order to be collected.
        """


def format_msg(message, line, lnum):
    """ Fromats and returns error message with line number. """
    return '{0}, line {2}: {1}'.format(message, line.strip(), lnum + 1)


def _convert_hex_str_to_int(val):
    """Convert hexadecimal formatted ids to signed int64"""
    if val is None:
        return None
    hex_num = int(val, 16)
    if hex_num > 9223372036854775807:
        hex_num -= 18446744073709551616
    assert -9223372036854775808 <= hex_num <= 9223372036854775807
    return hex_num


def savebackup(tr, backupname):
    """Save current dirstate into backup file"""


def getArguments(parser):
    """Provides additional validation of the arguments collected by argparse."""
    return parser.parse_args()


def callback_exclusion_v1(name, path_type):
    """
    Example of an exclusion callback function.
    """
    print('Excluding', path_type, name)


def idxwidth(nbidx):
    """return the max width of number used for index

    This is similar to log10(nbidx), but we use custom code here
    because we start with zero and we'd rather not deal with all the
    extra rounding business that log10 would imply.
    """
    nbidx -= 1
    idxwidth = 0
    while nbidx:
        idxwidth += 1
        nbidx //= 10
    if not idxwidth:
        idxwidth = 1
    return idxwidth


def chunks(list_, count_items_in_chunk):
    """
    разбить list (l) на куски по n элементов

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


def union(a, b):
    """Returns a new list of the union between a and b"""
    return set(a) | set(b)


def psi_Ca_CO3_HCO3_HMW84(T, P):
    """c-a-a': calcium carbonate bicarbonate [HMW84]."""
    psi = 0.0
    valid = T == 298.15
    return psi, valid


def mip_row_val(me, rid):
    """mip_row_val with transparent index mapping."""
    rid = me._rowmap.map(rid)
    if rid:
        return me._mip_row_val(rid)


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

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


def lin_weighting(G, node, neighbor):
    """ A weight is the edge weight divided to the node degree. """
    return G[node][neighbor].get('weight', 1.0) / G.degree[neighbor]


@classmethod
def get_currency(klass, text):
    u"""
        >>> Currency.get_currency(u'42')
        None
        >>> Currency.get_currency(u'42 €')
        u'EUR'
        >>> Currency.get_currency(u'$42')
        u'USD'
        >>> Currency.get_currency(u'42.000,00€')
        u'EUR'
        >>> Currency.get_currency(u'$42 USD')
        u'USD'
        >>> Currency.get_currency(u'%42 USD')
        u'USD'
        >>> Currency.get_currency(u'US1D')
        None
        """
    curtexts = klass.EXTRACTOR.sub(' ', text.upper()).split()
    for currency, symbols in klass.CURRENCIES.items():
        for curtext in curtexts:
            if curtext == currency:
                return currency
            for symbol in symbols:
                if curtext == symbol:
                    return currency
    return None


@staticmethod
def _get_LMv1_with_session_security_response(client_challenge):
    """
        [MS-NLMP] v28.0 2016-07-14

        2.2.2.3 LM_RESPONSE
        The LM_RESPONSE structure defines the NTLM v1 authentication
        LmChallengeResponse in the AUTHENTICATE_MESSAGE. This response is used
        only when NTLM v1 authentication is configured and
        NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY is flages.

        :param client_challenge: A random 8-byte response generated by the
            client for the AUTHENTICATE_MESSAGE
        :return response: LmChallengeResponse to the server challenge
        """
    response = client_challenge + b'\x00' * 16
    return response


def task_status(task_id, cursor):
    """
    Returns rds task status of given task id.
    """
    cursor.execute(
        """
        EXEC msdb.dbo.rds_task_status @task_id={}
    """.
        format(task_id))
    return cursor.fetchall()


@classmethod
def convert_name_to_id(cls, name: str) ->str:
    """
        Convert result name to configuration name.

        The name given in CCCC results is different than the name given in CCCC
        configuration. This will map the name in the configuration file to the
        name given in the results.
        """
    name_id = ''
    if name == 'IF4':
        name_id = 'IF4'
    elif name == 'fan_out_concrete':
        name_id = 'FOc'
    elif name == 'IF4_visible':
        name_id = 'IF4v'
    elif name == 'coupling_between_objects':
        name_id = 'CBO'
    elif name == 'fan_in_visible':
        name_id = 'FIv'
    elif name == 'weighted_methods_per_class_unity':
        name_id = 'WMC1'
    elif name == 'fan_out':
        name_id = 'FO'
    elif name == 'weighted_methods_per_class_visibility':
        name_id = 'WMCv'
    elif name == 'fan_out_visible':
        name_id = 'FOv'
    elif name == 'IF4_concrete':
        name_id = 'IF4c'
    elif name == 'depth_of_inheritance_tree':
        name_id = 'DIT'
    elif name == 'number_of_children':
        name_id = 'NOC'
    elif name == 'fan_in_concrete':
        name_id = 'FIc'
    elif name == 'fan_in':
        name_id = 'FI'
    elif name == 'lines_of_comment':
        name_id = 'COM'
    elif name == 'lines_of_code_per_line_of_comment':
        name_id = 'L_C'
    elif name == 'McCabes_cyclomatic_complexity':
        name_id = 'MVGper'
    elif name == 'lines_of_code':
        name_id = 'LOCp'
    elif name == 'McCabes_cyclomatic_complexity_per_line_of_comment':
        name_id = 'M_C'
    return name_id


def label_encoder(df):
    """Label Encodingto
    Args:
        - df: DataFrame
    Return:
        - df: DataFrame
            - 옹호 = 1, 부정 = -1, 중립 = 0"""
    df['평가'].replace('옹호', 1, inplace=True)
    df['평가'].replace('부정', -1, inplace=True)
    df['평가'].replace('중립', 0, inplace=True)
    return df


def filter_out_hydrogens(mol):
    """Get indices for non-hydrogen atoms.

    Parameters
    ----------
    mol : rdkit.Chem.rdchem.Mol
        RDKit molecule instance.

    Returns
    -------
    indices_left : list of int
        Indices of non-hydrogen atoms.
    """
    indices_left = []
    for i, atom in enumerate(mol.GetAtoms()):
        atomic_num = atom.GetAtomicNum()
        if atomic_num != 1:
            indices_left.append(i)
    return indices_left


def to_networkx(g, node_attrs=None, edge_attrs=None):
    """Convert to networkx graph.

    The edge id will be saved as the 'id' edge attribute.

    Parameters
    ----------
    g : DGLGraph or DGLHeteroGraph
        For DGLHeteroGraphs, we currently only support the
        case of one node type and one edge type.
    node_attrs : iterable of str, optional
        The node attributes to be copied. (Default: None)
    edge_attrs : iterable of str, optional
        The edge attributes to be copied. (Default: None)

    Returns
    -------
    networkx.DiGraph
        The nx graph
    """
    return g.to_networkx(node_attrs, edge_attrs)


def application_enabled(cmd, namespace):
    """Validates account has auto-storage enabled"""
    from azure.mgmt.batch import BatchManagementClient
    from azure.cli.core.commands.client_factory import get_mgmt_service_client
    client = get_mgmt_service_client(cmd.cli_ctx, BatchManagementClient)
    acc = client.batch_account.get(namespace.resource_group_name, namespace
        .account_name)
    if not acc:
        raise ValueError("Batch account '{}' not found.".format(namespace.
            account_name))
    if not acc.auto_storage or not acc.auto_storage.storage_account_id:
        raise ValueError("Batch account '{}' needs auto-storage enabled.".
            format(namespace.account_name))


def integral_image(image):
    """Integral image / summed area table.

    The integral image contains the sum of all elements above and to the
    left of it, i.e.:

    .. math::

       S[m, n] = \\sum_{i \\leq m} \\sum_{j \\leq n} X[i, j]

    Parameters
    ----------
    image : ndarray
        Input image.

    Returns
    -------
    S : ndarray
        Integral image/summed area table of same shape as input image.

    References
    ----------
    .. [1] F.C. Crow, "Summed-area tables for texture mapping,"
           ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212.

    """
    S = image
    for i in range(image.ndim):
        S = S.cumsum(axis=i)
    return S


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

        :param UserSelectorArg val:
        :rtype: UserResendResult
        """
    return cls('invalid_user', val)


@staticmethod
def _abbreviate(phrase: str) ->str:
    """return words replaced with abbreviations"""
    subs = [('Hash Join', 'HJ'), ('Merge Join', 'MJ'), ('Product Join',
        'PJ'), (' Join', '-J'), ('Product', 'Prod'), ('Inclusion ', '+'), (
        'Exclusion ', '-'), ('Dynamic ', 'D-'), ('Correlated', 'Corr')]
    for word, abbr in subs:
        if word in phrase:
            phrase = phrase.replace(word, abbr)
    return phrase


@staticmethod
def _check_name_in_list_settings_entry(name_to_check, list_settings_entry):
    """
        manage object models : STT, TRIGGERS, TTS, PLAYERS because they have "name" attributes
        :param name_to_check: name to find in the list_settings_entry ~brain.core.Models.settings.SettingsEntry.SettingsEntry
        :param list_settings_entry: the list of SettingsEntry to inspect
        :return: True if the name_to_check corresponds to a name in the SettingsEntry list provided.
        """
    found = False
    for settings_entry in list_settings_entry:
        if settings_entry.name == name_to_check:
            found = True
            break
    return found


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 members():
    """collect object members from incoming things"""


def persist_unique_identifiers(metamodel, path, mode='w'):
    """
    Persist all unique identifiers in a *metamodel* by serializing them and
    saving to a *path* on disk.
    """
    with open(path, mode) as f:
        for metaclass in metamodel.metaclasses.values():
            for index_name, attribute_names in metaclass.indices.items():
                attribute_names = ', '.join(attribute_names)
                s = 'CREATE UNIQUE INDEX %s ON %s (%s);\n' % (index_name,
                    metaclass.kind, attribute_names)
                f.write(s)


def merge_dicts(source_dicts, merge_dicts, join_key, merge_keys):
    """
    Insert specified fields from a merge dictionary to a source dictionary
    based on a matching key/val. Join field must exist in both source and
    merge dictionaries
    """
    merged = []
    for merge_dict in merge_dicts:
        for source_dict in source_dicts:
            try:
                if str(merge_dict[join_key]) == str(source_dict[join_key]):
                    for key in merge_dict:
                        if key in merge_keys:
                            source_dict[key] = merge_dict[key]
                    merged.append(source_dict)
                    continue
            except KeyError:
                continue
    return merged


def error_msg_from_exception(e):
    """Translate exception into error message

    Database have different ways to handle exception. This function attempts
    to make sense of the exception object and construct a human readable
    sentence.

    TODO(bkyryliuk): parse the Presto error message from the connection
                     created via create_engine.
    engine = create_engine('presto://localhost:3506/silver') -
      gives an e.message as the str(dict)
    presto.connect('localhost', port=3506, catalog='silver') - as a dict.
    The latter version is parsed correctly by this function.
    """
    msg = ''
    if hasattr(e, 'message'):
        if isinstance(e.message, dict):
            msg = e.message.get('message')
        elif e.message:
            msg = e.message
    return msg or str(e)


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


def _name_or_asname(alias):
    """Take alias node from AST and return the name bound to import"""
    return alias.asname if alias.asname else alias.name


def is_hashed(input_str):
    """Check if given input_str is hashed."""
    return input_str.startswith('$2')


def screaming_snake_to_snake_case(text: str) ->str:
    """Convert SCREAMING_SNAKE_CASE to snake_case."""
    return text.lower()


def filename(prefix, i, p, a, t):
    """Returns the filename"""
    return '{}_{:.2f}_{:.2f}_{:.2f}_{:d}.fits'.format(prefix, i, p, a, t)


def decode_jpeg(encoded, tables=b'', photometric=None, ycbcr_subsampling=
    None, ycbcr_positioning=None):
    """Decode JPEG encoded byte string (using _czifile extension module)."""
    from czifile import _czifile
    image = _czifile.decode_jpeg(encoded, tables)
    if photometric == 'rgb' and ycbcr_subsampling and ycbcr_positioning:
        pass
    return image.tostring()


def set_node_nested_field(node, collection, field, value):
    """Set a value in a dictionary field of a node.

    :param node: Node object.
    :param collection: Name of the field with the dictionary.
    :param field: Nested field name.
    :param value: New value.
    """
    col = getattr(node, collection)
    col[field] = value
    setattr(node, collection, col)


def preloaded_multi_mp_sgd_update(*data, **kwargs):
    """Update function for multi-precision Stochastic Gradient Descent (SDG) optimizer.

    It updates the weights using::

     weight = weight - learning_rate * (gradient + wd * weight)

    Defined in src/operator/contrib/preloaded_multi_sgd.cc:L140

    Parameters
    ----------
    data : Symbol[]
        Weights, gradients, learning rates and weight decays
    rescale_grad : float, optional, default=1
        Rescale gradient to grad = rescale_grad*grad.
    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 get_document_path(DocumentId=None, Limit=None, Fields=None, Marker=None):
    """
    Retrieves the path information (the hierarchy from the root folder) for the requested document.
    By default, Amazon WorkDocs returns a maximum of 100 levels upwards from the requested document and only includes the IDs of the parent folders in the path. You can limit the maximum number of levels. You can also request the names of the parent folders.
    See also: AWS API Documentation

    :example: response = client.get_document_path(
        DocumentId='string',
        Limit=123,
        Fields='string',
        Marker='string'
    )

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

    :type Limit: integer
    :param Limit: The maximum number of levels in the hierarchy to return.

    :type Fields: string
    :param Fields: A comma-separated list of values. Specify 'NAME' to include the names of the parent folders.

    :type Marker: string
    :param Marker: This value is not supported.

    :rtype: dict
    :return: {
        'Path': {
            'Components': [
                {
                    'Id': 'string',
                    'Name': 'string'
                },
            ]
        }
    }

    """
    pass


def row_includes_spans(table, row, spans):
    """
    Determine if there are spans within a row

    Parameters
    ----------
    table : list of lists of str
    row : int
    spans : list of lists of lists of int

    Returns
    -------
    bool
        Whether or not a table's row includes spans
    """
    for column in range(len(table[row])):
        for span in spans:
            if [row, column] in span:
                return True
    return False


@classmethod
def build_from_file(cls, path, skip_model_cls_init=False):
    """Build Framework File from model path.

        Args:
            path (str): Path to file.
            skip_model_cls_init (bool): If True, model is loaded directly
                from file and not instantiated as the Framework type.

        Returns: CoreMLFile instance.
        """
    if skip_model_cls_init:
        model = open(path, 'rb').read()
        return cls(model, is_byte_representation=True)
    import coremltools
    model = coremltools.models.MLModel(path)
    return cls(model)


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

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


@staticmethod
def tree_remains_active_and_my_rpc_changes(interface: 'TreeInterfaceDownstream'
    ) ->None:
    """
        Tree is Active AND
        interface not directly connected to the source AND
        MyRPC changes
        """
    interface.logger.debug('tree_remains_active_and_my_rpc_changes')
    interface.send_i_am_upstream()


def filter_stupid_characters(string):
    """filter_stupid_characters"""
    for char in ['$', '\\', ' ', '__', '___']:
        string = string.replace(char, '_')
    if string.startswith('_'):
        string = string[1:-1]
    return string


def underline(line, underline='~'):
    """Return an underline string for ``line``.

    Intended for use with level 3 and lower headings.

    Note that the default for ``underline`` assumes that the level
    1 and 2 underlines are the standard ``=`` and ``-``. You can
    pass a different underline character to this function if needed.
    """
    if line.endswith('\n'):
        line = line[:-1]
    return '{}\n'.format(underline * len(line))


def requirement_args(argv, want_paths=False, want_other=False):
    """Return an iterable of filtered arguments.

    :arg argv: Arguments, starting after the subcommand
    :arg want_paths: If True, the returned iterable includes the paths to any
        requirements files following a ``-r`` or ``--requirement`` option.
    :arg want_other: If True, the returned iterable includes the args that are
        not a requirement-file path or a ``-r`` or ``--requirement`` flag.

    """
    was_r = False
    for arg in argv:
        if was_r:
            if want_paths:
                yield arg
            was_r = False
        elif arg in ['-r', '--requirement']:
            was_r = True
        elif want_other:
            yield arg


def startswith_str(text, prefix, start=None, end=None):
    """
    Determines if ``text`` starts with the specified prefix.

    The prefix can also be a tuple of prefixes to look for. With optional parameter ``start``,
    the test will begin at that position. With optional parameter ``end``, the test will
    stop comparing at that position.

    :param text: The string to search
    :type text:  ``str``

    :param prefix: The prefix to search for
    :type prefix:  ``str`` or ``tuple`` of ``str``

    :param start: The start of the search range
    :type start:  ``int``

    :param end: The end of the search range
    :type end:  ``int``

    :return: True if ``text`` starts with the specified prefix, otherwise return False.
    :rtype:  ``int``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.startswith(prefix, start, end)


def mathcontour(x, y, errx, erry, cov):
    """
Suppose I want to draw the error ellipses for two parameters 'x' and 'y'
with 1 s.d. uncertainties and the covariance between these uncertainties.
I have a mathematica notebook that does that: 'chisq contour plot.nb'.

This method takes the values 'x,y,errx,erry,cov' and outputs Mathematica
code that I can just copy and paste in the appropriate notebook in order
to draw the ellipses.
	"""
    print('x0=', x, ';')
    print('y0=', y, ';')
    print('\\[Sigma]x=', errx, ';')
    print('\\[Sigma]y=', erry, ';')
    print('\\[Sigma]xy=', cov, ';')


def argtopk(input, k, dim, descending=True):
    """Return the indices of the k largest elements of the given input tensor
    along the given dimension.

    If descending is False then the k smallest elements are returned.

    Parameters
    ----------
    input : Tensor
        The input tensor.
    k : int
        The number of elements.
    dim : int
        The dimension to sort along.
    descending : bool
        Controls whether to return largest/smallest elements.
    """
    pass


def cut_off_str(obj, max_len):
    """
    Creates a string representation of an object, no longer than
    max_len characters

    Uses repr(obj) to create the string representation.
    If this is longer than max_len -3 characters, the last three will
    be replaced with elipsis.
    """
    s = repr(obj)
    if len(s) > max_len - 3:
        s = s[:max_len - 3] + '...'
    return s


def _from_bytes(bytes, byteorder='big', signed=False):
    """This is the same functionality as ``int.from_bytes`` in python 3"""
    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)


def pop_until(sequence, condition=bool):
    """
    Look for item in `sequence` that passes `condition`, popping away others.

    When sequence is empty, propagates the `IndexError`.
    """
    from python_toolbox import cute_iter_tools
    for item in cute_iter_tools.iterate_pop(sequence):
        if condition(item):
            return item


def _print(txt):
    """print line without /r, /n or white space"""
    print(txt.rstrip())


def parse_argstring(parser, s):
    """Return parsed args from arg string."""
    import shlex
    args = parser.parse_args(shlex.split(s))
    return args


@staticmethod
def __linear(i, pulses_per_mm, total_pulses, velocity_mm_per_sec):
    """ Helper function for linear movement.
        """
    if total_pulses == 0.0 or i >= total_pulses:
        return None
    return i / pulses_per_mm / velocity_mm_per_sec


def slash_url_suffix(url, suffix):
    """Adds a slash either to the beginning or the end of a suffix
    (which is to be appended to a URL), depending on whether or not
    the URL ends with a slash."""
    return url.endswith('/') and '%s/' % suffix or '/%s' % suffix


def _gen_path_responses(http_method, resource_name):
    """
    This function receives a HTTP method and a resource name and generates the standard responses of the method

    :param str http_method:
        http method used

    :param str resource_name:
        name of the resource being served

    :rtype dict:
    :return: dict containing the standard responses of the method
    """
    if http_method == 'GET_Collection':
        return {'200': {'description': 'successful operation', 'schema': {
            'type': 'array', 'items': {'$ref': '#/definitions/%s' %
            resource_name}}}}
    elif http_method == 'PUT':
        return {'204': {'description': 'successfully updated'}, '400': {
            'description': 'invalid %s supplied' % resource_name}, '404': {
            'description': '%s not found' % resource_name}}
    elif http_method == 'GET':
        return {'200': {'description': 'successful operation', 'schema': {
            '$ref': '#/definitions/%s' % resource_name}}, '400': {
            'description': 'invalid ID supplied'}, '404': {'description':
            '%s not found' % resource_name}}
    elif http_method == 'POST':
        return {'201': {'description': 'the %s was created successfully' %
            resource_name}, '405': {'description': 'invalid input'}}
    elif http_method == 'DELETE':
        return {'204': {'description': 'successfully deleted'}, '400': {
            'description': 'invalid ID supplied'}, '404': {'description':
            '%s not found' % resource_name}}
    return None


def join_to(foreign_keys, table, primary_key='id'):
    """
    Given a set of ids for an object, and a list of the objects these ids refer
    to, select out the objects by joining using the specified primary key
    (which defaults to 'id').
    """
    joined = []
    for foreign_key in foreign_keys:
        selected_row = None
        for row in table:
            if row[primary_key] == foreign_key:
                selected_row = row
                break
        joined.append(selected_row)
    return joined


def common_string_sequence(s, t):
    """
    Find a sequence of characters that occurs, in order, in both s and t.
    The sequence need not be contiguous in either.

    Doesn't necessarily return the "best" (or longest) such sequence.
    """
    common = []
    p = 0
    for c in s:
        pos = t[p:].find(c)
        if pos > -1:
            common.append(c)
            p += pos + 1
    return ''.join(common)


def get_file_extension(fn):
    """
    get file extension and check if it is compressed
    :param: str, file path
    :return: str,bool
    """
    compressed_file_ext = ['gz']
    fn_part = fn.split('.')
    compressed = False
    ext = fn_part[-1]
    if ext in compressed_file_ext:
        compressed = True
        ext = fn_part[-2]
    return ext, compressed