def __init__(símismo, variables, nombre):
    """
        La función de inicialización de todos modelos, conectados o no.

        Parameters
        ----------
        variables : VariablesMod
            Los variables del modelo.
        nombre : str
            El nombre del modelo.

        """
    símismo.nombre = nombre
    símismo.variables = variables
    símismo.corrida = None
    símismo.vars_clima = {}


def _counter_inc(stats, stat, key, increment=1):
    """
    Helper for incrementing given statistical parameter within given statistical
    bundle.

    :param dict stats: Structure containing all statistics.
    :param str stat: Name of the statistical category.
    :param str key: Name of the statistical key.
    :param int increment: Counter increment.
    :return: Updated structure containing statistics.
    :rtype: dict
    """
    if not stat in stats:
        stats[stat] = {}
    stats[stat][str(key)] = stats[stat].get(str(key), 0) + increment
    return stats


def lovasz_grad(gt_sorted):
    """
    Computes gradient of the Lovasz extension w.r.t sorted errors
    See Alg. 1 in paper
    """
    p = len(gt_sorted)
    gts = gt_sorted.sum()
    intersection = gts - gt_sorted.float().cumsum(0)
    union = gts + (1 - gt_sorted).float().cumsum(0)
    jaccard = 1.0 - intersection / union
    if p > 1:
        jaccard[1:p] = jaccard[1:p] - jaccard[0:-1]
    return jaccard


def save(event):
    """ make a kernel dump. """
    from bot.space import alias, kernel, seen
    alias.sync()
    kernel.sync()
    seen.sync()
    event.reply('saved')


def is_iterable(obj):
    """Tests whether an object is iterable. Returns False for strings"""
    return hasattr(obj, '__iter__')


def create_project(source, repo):
    """
        Create the repo "repo" on the host
        Returns the URL for the created project or False on error.

        :return: url or False
        """


@classmethod
def format_sub_part(cls, field, length):
    """
        Generate the SQL to format the sub_part length of an indexed column name

          >>> schemaobjects.index.IndexSchema.format_sub_part('column', 0)
          '`column`'
          >>> schemaobjects.index.IndexSchema.format_sub_part('column', 5)
          '`column`(5)'
        """
    try:
        if not length:
            raise ValueError
        length = int(length)
        return '`%s`(%d)' % (field, length)
    except ValueError:
        return '`%s`' % (field,)


@staticmethod
def parent_only_text(elem):
    """
        Returns the text for the current element without the text of child elements.

        :param elem:
        :return string:
        """
    parent_only_text = elem.lxml.findtext('./')
    return parent_only_text


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

        :param SingleUserLock val:
        :rtype: FileLockContent
        """
    return cls('single_user', val)


def mergeDicts(a, b):
    """
    Merge the dictionaries a and b such that entries in b have priority and the
    input Dictionary a remains unchanged.
    """
    c = a.copy()
    c.update(b)
    return c


def subtract_sorted(data):
    """Subtracts the sorted sequence elements from each other, discarding zeros.
    Used in the Second Order test
    """
    sec = data.copy()
    sec.sort_values(inplace=True)
    sec = sec - sec.shift(1)
    sec = sec.loc[sec != 0]
    return sec


def card_type_finder(filename):
    """ Function to extract all unique values from a data set

    :param filename: input filename fro analysis

    card_type_finder(str) -> list
    """
    fhand = open(filename, 'r')
    types = {}
    for line in fhand:
        line1 = line.split(',')
        line2 = line1[13].split('[')
        type_u = line2[0].strip()
        if type_u not in types:
            types[type_u] = 1
        else:
            types[type_u] += 1
    fhand.close()
    print(types)


def _high_pass(data, alpha=0.5):
    """
    Runs a high pass RC filter over the given data.

    Parameters
    ----------
    data : array_like

    alpha : float
            Smoothing factor between 0.0 (exclusive) and 1.0 (inclusive).
            A lower value means more filtering.  A value of 1.0 equals no
            filtering. Defaults is 0.5.

    Returns
    -------
    hpf : array_like
          Filtered data.

    Based on http://en.wikipedia.org/wiki/High-pass_filter

    """
    mean = data.mean()
    data = data - mean
    hpf = data.copy()
    for k in range(1, len(data)):
        hpf[k] = alpha * hpf[k - 1] + alpha * (data[k] - data[k - 1])
    return hpf + mean


def reindex_doc(docid, obj):
    """ Reindex the document numbered ``docid`` using in the
        information on object ``obj``"""


def _split_header_params(s):
    """Split header parameters."""
    result = []
    while s[:1] == b';':
        s = s[1:]
        end = s.find(b';')
        while end > 0 and s.count(b'"', 0, end) % 2:
            end = s.find(b';', end + 1)
        if end < 0:
            end = len(s)
        f = s[:end]
        result.append(f.strip())
        s = s[end:]
    return result


def chance_adjusted_agreement(observed_agreement, chance_agreement):
    """Return the chance-adjusted agreement given the specified agreement
    and expected agreement.

    Defined by (observed_agreement - chance_agreement)/(1.0 - chance_agreement)

    Arguments
    ---------
    observed_agreement : float
        Agreement computed from the data

    chance_agreement : float
        Agreement expected by chance give the assumptions of the statistics

    Return
    ------
    result : float
        Chance adjusted agreement value
    """
    return (observed_agreement - chance_agreement) / (1.0 - chance_agreement)


@classmethod
def transform_content(cls, content):
    """Transform content to a Nikola-friendly format."""
    return content


def options(opt):
    """Adds command line options to the *waf* build environment

    :param opt: Options context from the *waf* build environment.
    :type opt: waflib.Options.OptionsContext
    """
    opt.add_option('--tree-loc', dest='tree_loc', default=False, action=
        'store_true', help='use physical file locations when printing tree')


def assert_string_data(value: str) ->None:
    """Asserts value is string type."""
    assert isinstance(value, str
        ), f'Input value type must be string. Actual type: {type(value)}, value: {value}'


def yesno_as_boolean(yesno_string):
    """converts text containing yes or no to a bool"""
    valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
    return valid[yesno_string.lower()]


def searchUsers(attrs=(), exact_match=False, **kw):
    """ Search for user records by one or more attributes.

        This method takes any passed-in search parameters and values as
        keyword arguments and will sort out invalid keys automatically. It
        accepts all three forms an attribute can be known as, its real
        ldap name, the name an attribute is mapped to explicitly, and the
        friendly name it is known by.

        Permission: *Manage users*
        """


def not_contains(x, y):
    """
    Python's operator module does not have a function for the ``not in`` operator. That's a shame.
    """
    return y not in x


def __new__(mcs, name, bases, attrs):
    """ @param name: Name of the class
        @param bases: Base classes (tuple)
        @param attrs: Attributes defined for the class
    """
    new_cls = type.__new__(mcs, name, bases, attrs)
    mcs.REGISTRY[new_cls.__module__ + '.' + new_cls.__name__] = new_cls
    return new_cls


def git_commit_eq(c1, c2):
    """
        Compares two commits for equality, ignoring length and case
    """
    clen = min(len(c1), len(c2))
    return c1.lower()[:clen] == c2.lower()[:clen]


def clear_useless_actions(only_unused: bool=True):
    """Mark actions with no F-Curves for deletion after save & reload of file preserving “action libraries”

    :param only_unused: Only Unused, Only unused (Fake User only) actions get considered
    :type only_unused: bool
    """
    pass


def disconnect(connection):
    """
    Disconnect to MySQL server

    @Args:
    * [connection] connection to disconnect to server
    """
    connection.close()


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 model_from_config(config, custom_objects=None):
    """Instantiates a Keras model from its config.

    # Arguments
        config: Configuration dictionary.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.

    # Returns
        A Keras model instance (uncompiled).

    # Raises
        TypeError: if `config` is not a dictionary.
    """
    if isinstance(config, list):
        raise TypeError(
            '`model_from_config` expects a dictionary, not a list. Maybe you meant to use `Sequential.from_config(config)`?'
            )
    from ..layers import deserialize
    return deserialize(config, custom_objects=custom_objects)


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

        :param files.LookupError val:
        :rtype: ListSharedLinksError
        """
    return cls('path', val)


def add_params(param_list_left, param_list_right):
    """Add two lists of parameters one by one

    :param param_list_left: list of numpy arrays
    :param param_list_right: list of numpy arrays
    :return: list of numpy arrays
    """
    res = []
    for x, y in zip(param_list_left, param_list_right):
        res.append(x + y)
    return res


def _round_multiple(x: int, mult: int=None) ->int:
    """Calc `x` to nearest multiple of `mult`."""
    return int(x / mult + 0.5) * mult if mult is not None else x


def negative_real(var, var_name):
    """
    Check if parameter *var* is a negative number.

    :raises TypeError: Parameter *var* must be a real number.
    :raises ValueError: Parameter *var* must be a negative number.

    """
    if not isinstance(var, (int, float)):
        raise TypeError('\n\nParameter {} must be a real number.\n'.format(
            var_name))
    if var >= 0:
        raise ValueError('\n\nParameter {} must be a negative number.\n'.
            format(var_name))


def feed_hdf5_spt(dtsFunc, objQ, vecSplt):
    """
    Feed FIFO queue for placement of spatial segments in hdf5 file.

    Parameters
    ----------
    dtsFunc : h5py dataset
        Dataset within h5py file.
    objQ : queue.Queue
        Queue from which voxel time courses are retrieved.
    vecSplt : np.array
        Indices of chunks of voxels in fMRI time course. Looping voxels by
        voxels is too slow. Instread, read & write a chunk of voxels at a
        time.

    Notes
    -----
    Place spatial segments (i.e. chunks of voxels) in hdf5 file. There is a
    corresponding function for placement of temporal segments.

    """
    varNumCnk = vecSplt.shape[0]
    for idxChnk in range(varNumCnk - 1):
        varIdx01 = vecSplt[idxChnk]
        varIdx02 = vecSplt[idxChnk + 1]
        dtsFunc[:, varIdx01:varIdx02] = objQ.get()


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


def interpret_wcsname_type(wcsname):
    """Interpret WCSNAME as a standardized human-understandable description """
    wcstype = ''
    fit_terms = {'REL': 'relatively aligned to {}', 'IMG':
        'aligned image-by-image to {}', 'SVM': 'aligned by visit to {}'}
    post_fit = 'a posteriori solution '
    default_fit = 'a priori solution based on {}'
    base_terms = {'IDC': 'undistorted ', 'OPU': 'pipeline default '}
    no_fit = 'not aligned'
    wcsname = wcsname.upper()
    wcsname_list = wcsname.split('-')
    wcsname_term = wcsname_list[0][:3]
    if wcsname_term not in base_terms:
        wcstype = 'user-defined'
        return wcstype
    wcstype += base_terms[wcsname_term]
    fit_term = wcsname_list[1] if len(wcsname_list) > 1 else None
    if len(wcsname_list) == 1:
        wcstype += no_fit
    elif 'FIT' not in fit_term:
        wcstype += default_fit.format(fit_term)
    else:
        wcstype += post_fit
        postfit_type = fit_term.split('_')
        wcstype += fit_terms[postfit_type[1]].format(postfit_type[2])
    return wcstype


def _check_isinstance(left, right, cls):
    """
    Helper method for our assert_* methods that ensures that
    the two objects being compared have the right type before
    proceeding with the comparison.

    Parameters
    ----------
    left : The first object being compared.
    right : The second object being compared.
    cls : The class type to check against.

    Raises
    ------
    AssertionError : Either `left` or `right` is not an instance of `cls`.
    """
    err_msg = '{name} Expected type {exp_type}, found {act_type} instead'
    cls_name = cls.__name__
    if not isinstance(left, cls):
        raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
            act_type=type(left)))
    if not isinstance(right, cls):
        raise AssertionError(err_msg.format(name=cls_name, exp_type=cls,
            act_type=type(right)))


def sav_to_pandas_rpy2(input_file):
    """
    SPSS .sav files to Pandas DataFrame through Rpy2

    :param input_file: string

    :return:
    """
    import pandas.rpy.common as com
    w = com.robj.r('foreign::read.spss("%s", to.data.frame=TRUE)' % input_file)
    return com.convert_robj(w)


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

    """
    pass


@classmethod
def from_frame(cls, frame):
    """Creates a ``Reflection`` that mirrors at the ``Frame``.

        Parameters
        ----------
        frame : :class:`Frame`

        """
    return cls(frame.point, frame.normal)


@staticmethod
def _from_db_object(resource, db_resource):
    """Converts a database entity to a formal object."""
    for field in resource.fields:
        setattr(resource, field, db_resource[field])
    resource.obj_reset_changes()
    return resource


def encode_synchsafe_int(i, per_byte):
    """Encode synchsafe integers for ID3v2 tags."""
    if i > 2 ** (per_byte * 4) - 1:
        raise ValueError(
            f'{i} is too large to be represented by a synchsafe integer with {per_byte} bits per byte.'
            )
    v = 0
    mask = 127
    value = i
    while mask ^ 2147483647 > 0:
        v = value & ~mask
        v = v << 8 - per_byte
        v = v | value & mask
        mask = (mask + 1 << 8) - 1
        value = v
    return value.to_bytes(4, byteorder='big')


def clear(scrollback: bool=True, history: bool=False):
    """Clear text by type

    :param scrollback: Scrollback, Clear the scrollback history
    :type scrollback: bool
    :param history: History, Clear the command history
    :type history: bool
    """
    pass


@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')


@staticmethod
def team_key(identifier):
    """
        Take raw team number or string key and return string key.

        Used by all team-related methods to support either an integer team number or team key being passed.

        (We recommend passing an integer, just because it's cleaner. But whatever works.)

        :param identifier: int team number or str 'frc####'
        :return: string team key in format 'frc####'
        """
    return identifier if type(identifier) == str else 'frc%s' % identifier


def no_log_warn(logical_line):
    """Disallow 'LOG.warn('

    https://bugs.launchpad.net/tempest/+bug/1508442

    Heat301
    """
    if logical_line.startswith('LOG.warn('):
        yield 0, 'Heat301 Use LOG.warning() rather than LOG.warn()'


def _print_locators_list(header, locators_list):
    """ Print on console a formatted list of locators.

    :param header: Title of list.
    :type header: str
    :param locators_list: Locators list.
    :type locators_list: list or set
    :return: None
    """
    components = list(locators_list)
    components.insert(0, header)
    message = '\n'.join(components)
    print(message)


def __to_upper(val):
    """Convert val into ucase value."""
    try:
        return val.upper()
    except (ValueError, TypeError):
        return val


def cluster_total_volume(adj, c, cluster_num, dict_bool):
    """Determines the volume of a community.

    Parameters
    ----------
    adj : SciPy sparse matrix (csr or csc)
        The N x N rescaled Adjacency matrix constructed from
        N x N adjacency matrix of the graph and scale r.
    c : Integer array
        Array of community labels for the nodes in the graph as ordered
        by the adjacency matrix.
    cluster_num : Integer
        Label of the community of interest.
    dict_bool : dictionary
        Tracks the nodes in each community, with cluster labels as dictionary-
        keys, and the corresponding boolean arrays (c == label) as values.

    Returns
    -------
    float
        Total volume of all nodes in the rescaled topology of
        cluster 'cluster_num'.

    """
    return adj[dict_bool[cluster_num]].sum()


def json_get(parsed_json, key):
    """
    Retrieves the key from a parsed_json dictionary, or raises an exception if the
    key is not present
    """
    if key not in parsed_json:
        raise ValueError('JSON does not contain a {} field'.format(key))
    return parsed_json[key]


def decrease_heading_order(doc, tag=1, order=1):
    """Decrease heading number except specified element (by order).

    The purpose is the same as `decrease_heading`,
    except you specify keep-element by heading number and order.
    So e.g. argument ``'tag=2, order=3'`` means
    third ``
`` tag element in the document.

    >>> el = fromstring('

aaa

bbb

ccc

')
    >>> decrease_heading_order(el, 1, 2)
    >>> tostring(el)
    '

aaa

bbb

ccc

'
    """
    for i in range(5, 0, -1):
        for j, el in enumerate(doc.xpath('//h' + str(i))):
            if i == int(tag) and j + 1 == int(order):
                continue
            el.tag = 'h' + str(i + 1)


@classmethod
def get_mailing_addrobj(cls, party):
    """ get first mailing-address
        """
    if not isinstance(party, type(None)):
        if not isinstance(party.addresses, type(None)):
            for i in party.addresses:
                if i.mailing_addr == True:
                    return i
    cls.raise_user_error('no_mailing_addr', party.name)


@classmethod
def generate_mask(cls, shape, min_value, max_value, start_at, end_at):
    """Generate a linear horizontal gradient mask.

        Added in 0.4.0.

        Parameters
        ----------
        shape : tuple of int
            Shape of the image. The mask will have the same height and
            width.

        min_value : number
            Minimum value of the gradient in interval ``[0.0, 1.0]``.

        max_value : number
            Maximum value of the gradient in interval ``[0.0, 1.0]``.

        start_at : number
            Position on the x-axis where the linear gradient starts, given as
            a fraction of the axis size. Interval is ``[0.0, 1.0]``.

        end_at : number
            Position on the x-axis where the linear gradient ends, given as
            a fraction of the axis size. Interval is ``[0.0, 1.0]``.

        Returns
        -------
        ndarray
            ``float32`` mask array with same height and width as the image.
            Values are in ``[0.0, 1.0]``.

        """
    return cls._generate_mask(axis=0, shape=shape, min_value=min_value,
        max_value=max_value, start_at=start_at, end_at=end_at)


@classmethod
def package_install(cls, options):
    """Install packages remotely."""
    cls.command_sub = 'package install'
    return cls.execute(cls._construct_command(options), output_format='csv')


def _prop_bnds_leaf_to_root_GeneralExpression(node, bnds_dict, feasibility_tol
    ):
    """
    Propagate bounds from children to parent

    Parameters
    ----------
    node: pyomo.core.base.expression._GeneralExpressionData
    bnds_dict: ComponentMap
    feasibility_tol: float
        If the bounds computed on the body of a constraint violate the bounds of the constraint by more than
        feasibility_tol, then the constraint is considered infeasible and an exception is raised. This tolerance
        is also used when performing certain interval arithmetic operations to ensure that none of the feasible
        region is removed due to floating point arithmetic and to prevent math domain errors (a larger value
        is more conservative).
    """
    expr_lb, expr_ub = bnds_dict[node.expr]
    bnds_dict[node] = expr_lb, expr_ub


def put(zelf, *args, **kwargs):
    """ put arguments/kwargs to the Runner. """
    zelf._queue.put((args, kwargs))
    return zelf


def asList(obj):
    """Always returns a list, wrapping any other object type into a list

    :param obj: The value to be wrapped if necessary
    :type obj: Any
    :return: obj if it was already a list, otherwise object wrapped in a list
    :rtype: list
    """
    if isinstance(obj, list):
        return obj
    else:
        return list([obj])


def isAlphanum(c):
    """return true if the character is a letter, digit, underscore,
           dollar sign, or non-ASCII character.
    """
    return (c >= 'a' and c <= 'z' or c >= '0' and c <= '9' or c >= 'A' and
        c <= 'Z' or c == '_' or c == '$' or c == '\\' or c is not None and
        ord(c) > 126)


@staticmethod
def ternary(cond, t, f):
    """
		Use it if you need ternary operator
		"""
    return (cond and [t] or [f])[0]


def _get_method(cls, key):
    """Get method for the given key.

    Args:
      key: Method ID, method name or (interface ID, method ID). If just method
        ID or name, the interface ID is looked up. Otherwise, the interface ID
        is used to get the correct method.
    Returns: Interface ID, Method object.
    """
    if isinstance(key, tuple):
        id, method_id = key
        if cls.id == id:
            key = method_id
        else:
            for supercls in cls.__superclasses__:
                if supercls.id == id:
                    return supercls._get_method(method_id)
    id = cls.id
    if isinstance(key, int):
        method = cls.__id_methods__.get(key)
    else:
        method = cls.__methods__.get(key)
    if not method:
        for supercls in cls.__superclasses__:
            id, method = supercls._get_method(key)
            if method is not None:
                break
    return id, method


def extract_parts(usage):
    """Extract individual components from a usage string"""
    opp = {'{': '}', '[': ']', '(': ')'}
    cur_word = []
    tokens = []
    stack = []
    for c in usage:
        if c.isspace() and not stack:
            if cur_word:
                tokens.append(''.join(cur_word))
                cur_word.clear()
        elif c in '{[(':
            stack.append(c)
            cur_word.append(c)
        elif c in '}])' and stack and c == opp[stack[-1]]:
            stack.pop()
            cur_word.append(c)
            if not stack and cur_word:
                tokens.append(''.join(cur_word))
                cur_word.clear()
        else:
            cur_word.append(c)
    if cur_word:
        tokens.append(''.join(cur_word))
    return tokens


def has_pattern():
    """Check whether the `pattern <https://github.com/clips/pattern>`_ package is installed.

    Returns
    -------
    bool
        Is `pattern` installed?

    """
    try:
        from pattern.en import parse
        return True
    except ImportError:
        return False


@staticmethod
def _validate_key(key):
    """Emit a warning or raise an exception if key is invalid. Returns key."""
    if '.' in key:
        from ..errors import InvalidKeyError
        raise InvalidKeyError("Keys may not contain dots ('.').")
    return key


def add_params(param_list_left, param_list_right):
    """Add two lists of parameters one by one

    :param param_list_left: list of numpy arrays
    :param param_list_right: list of numpy arrays
    :return: list of numpy arrays
    """
    res = []
    for x, y in zip(param_list_left, param_list_right):
        res.append(x + y)
    return res


@classmethod
def title_match(cls, title0, title1):
    """
        within reason, do the two titles match?
        """
    if not title0 or not title1:
        return False
    else:
        return cls._clean_title(title0) == cls._clean_title(title1)


def search(o, m: None):
    """ match given selector (dict with keys/values to match). """
    if not m:
        m = {}
    res = False
    for k, v in m.items():
        vv = o.get(k, None)
        if vv:
            if v == None:
                res = True
            elif v in str(vv):
                res = True
            else:
                res = False
                break
        else:
            res = False
            break
    return res


def do(*exprs):
    """Helper function for chaining expressions.

    The expressions have already been evaluated when this function is called, so this function just returns the last one.

    If the list of expressions is empty, it returns ``None``.
    """
    if len(exprs) > 0:
        return exprs[-1]
    else:
        return None


def wavedec2_keys(level):
    """Subband keys corresponding to a wavedec2 decomposition."""
    approx = ''
    coeffs = {}
    for lev in range(level):
        for k in ['a', 'h', 'v', 'd']:
            coeffs[approx + k] = None
        approx = 'a' * (lev + 1)
        if lev < level - 1:
            coeffs.pop(approx)
    return list(coeffs.keys())


def to_unicode_or_bust(obj, encoding='utf-8'):
    """from: http://farmdev.com/talks/unicode/"""
    if isinstance(obj, str):
        if not isinstance(obj, str):
            obj = str(obj, encoding)
    return obj


def keras_dropout(layer, rate):
    """keras dropout layer.
    """
    from keras import layers
    input_dim = len(layer.input.shape)
    if input_dim == 2:
        return layers.SpatialDropout1D(rate)
    elif input_dim == 3:
        return layers.SpatialDropout2D(rate)
    elif input_dim == 4:
        return layers.SpatialDropout3D(rate)
    else:
        return layers.Dropout(rate)


def add_extra_fields(d, record):
    """
    Put extra key/values found in record.__dict__ into d.

    :param d: dict for values
    :param record: The log record.
    """
    skip_list = ('args', 'asctime', 'created', 'exc_info', 'exc_text',
        'filename', 'funcName', 'id', 'levelname', 'levelno', 'lineno',
        'module', 'msecs', 'message', 'msg', 'name', 'pathname', 'process',
        'processName', 'relativeCreated', 'thread', 'threadName')
    for key, value in record.__dict__.items():
        if value is None:
            continue
        if key not in skip_list and not key.startswith('_'):
            d[key] = value
    return d


def predicateWidget():
    """ Return a snippet of HTML suitable for editing the predicate.

        o This method may be defined via DTMLFile or PageTemplateFile
          (the tool will call it appropriately, if it is DTML).

        o The snippet should arrange for values to be marshalled by
          ZPublisher as a ':record', with the ID of the predicate as the
          name of the record.
        """


@classmethod
def succeed(cls, result):
    """
        Returns a Future for which the result has been set to the given result.
        Similar to Twisted's `Deferred.succeed()`.
        """
    f = cls()
    f.set_result(result)
    return f


def Values2A(ibrav, values):
    """needs a doc string"""
    if ibrav in [0, 1, 2]:
        return [values[0], values[0], values[0], 0, 0, 0]
    elif ibrav in [3, 4]:
        return [values[0], values[0], values[1], values[0], 0, 0]
    elif ibrav in [5, 6]:
        return [values[0], values[0], values[1], 0, 0, 0]
    elif ibrav in [7, 8, 9, 10, 11, 12]:
        return [values[0], values[1], values[2], 0, 0, 0]
    elif ibrav in [13, 14, 15]:
        return [values[0], values[1], values[2], 0, values[3], 0]
    else:
        return list(values[:6])


def keys():
    """Return available properties
        """


def zerocopy_from_dgl_ndarray(input):
    """Zerocopy a dgl.ndarray.NDArray to framework-specific Tensor

    Parameters
    ----------
    input : dgl.ndarray.NDArray

    Returns
    -------
    Tensor
    """
    pass


def ndarray2GSLIB(array, data_file, col_name):
    """Convert 1D or 2D numpy ndarray to a GSLIB Geo-EAS file for use with
    GSLIB methods.

    :param array: input array
    :param data_file: file name
    :param col_name: column name
    :return: None
    """
    if array.ndim not in [1, 2]:
        raise ValueError('must use a 2D array')
    with open(data_file, 'w') as f:
        f.write(data_file + '\n')
        f.write('1 \n')
        f.write(col_name + '\n')
        if array.ndim == 2:
            ny, nx = array.shape
            for iy in range(ny):
                for ix in range(nx):
                    f.write(str(array[ny - 1 - iy, ix]) + '\n')
        elif array.ndim == 1:
            nx = len(array)
            for ix in range(0, nx):
                f.write(str(array[ix]) + '\n')


def get(name, context=None, **kws):
    """Find the named template for the given context.

        This search for a named template using a stacked strategy.  If the
        template has been registered for the given context in the template
        manager, that template is used.  If not, a file system based template
        is used as a fallback.  If nothing can be found, the empty string is
        returned.

        Use the ``ITemplateManager`` to set specific template locations.  The
        fallbacks all use the ``mailman:`` scheme to use in-tree defaults.

        :param name: The name of the template to find.
        :type name: str
        :param context: The context in which to find the template.  This can
            be either an IMailingList, an IDomain, or None for the global/site
            context.  The template will be searched in order from most
            specific to least specific, i.e. from list-id, to domain, to
            global.
        :type context: IMailingList, IDomain, None
        :param kws: Additional URL substitution variables.  Once a URL for the
            given name and context is identified, these are used to fill in
            placeholders in the URL before the template is retrieved.
            `list_id`, `list_name`, and `mail_host` will automatically be
            filled in if available depending on the `context`.  This
            dictionary is passed directly to the underlying
            ``ITemplatemanager.get()`` call.
        :type kws: dict
        :return: The found template or its fallback.
        :rtype: str
        """


def flatten(fields):
    """
    Return a list which is a single level of flattening of the original list.
    """
    flat = []
    for field in fields:
        if isinstance(field, (list, tuple)):
            flat.extend(field)
        else:
            flat.append(field)
    return flat


@classmethod
def from_existing_session(cls, session: object, driver_options: str=None
    ) ->'Core':
    """Creates a new Core object with the entered 'session' reused."""
    return cls(None, False, False, driver_options, None, session)


def check(password):
    """checks password if it is ok.

        returns False or an unicode/msgid why its wrong
        """


def delete_example_runner_state(app, doctree):
    """Close and remove the :class:`ExampleRunner` instance once the
    document has been read.
    """
    runner = getattr(doctree, 'click_example_runner', None)
    if runner is not None:
        runner.close()
        del doctree.click_example_runner


@classmethod
def from_items(cls, items, orientation, spacing):
    """ A classmethod that generates a list of abutment constraints
        given a sequence of items, an orientation, and default spacing.

        Parameters
        ----------
        items : sequence
            A valid sequence of constrainable objects. These inclue
            instances of Constrainable, LinearSymbolic, Spacer,
            and int.

        orientation : string
            Either 'vertical' or 'horizontal', which represents the
            orientation in which to abut the items.

        spacing : int
            The spacing to use between items if no spacing is explicitly
            provided by in the sequence of items.

        Returns
        -------
        result : list
            A list of AbutmentConstraint instances.

        Notes
        ------
        The order of abutment is left-to-right for horizontal direction
        and top-to-bottom for vertical direction.

        """
    orient = cls.orientation_map.get(orientation)
    if orient is None:
        msg = (
            "Valid orientations for abutment are 'vertical' or 'horizontal'. Got %r instead."
            )
        raise ValueError(msg % orientation)
    first_name, second_name = orient
    if orientation == 'vertical':
        items.reverse()
    return cls._make_cns(items, first_name, second_name, spacing)


def get_ruleset_path(rulesengine_db, name):
    """returns the path to a ruleset"""
    from src.praxxis.sqlite import connection
    from src.praxxis.util import error
    conn = connection.create_connection(rulesengine_db)
    cur = conn.cursor()
    get_ruleset_path = 'SELECT Path FROM "RulesEngine" WHERE Name = ?'
    cur.execute(get_ruleset_path, (name,))
    conn.commit()
    rows = cur.fetchone()
    conn.close()
    if rows is None:
        raise error.RulesetNotFoundError(name)
    return rows[0]


def get_ics_weekday(minerva_day):
    """Minerva days include 'M'onday 'T'uesday 'W'ednesday Thu'R'sday 'F'riday 'S'aturday and  S'U'nday """
    return {'M': 'MO', 'T': 'TU', 'W': 'WE', 'R': 'TH', 'F': 'FR', 'S':
        'SA', 'U': 'SU'}[minerva_day]


@staticmethod
def _get_wwn(controllerport):
    """Return the WWN value of the controller port.

        Usually the WWN key in the controller port is wwn or WWN, but there
        are cases where the backend returns wWW, so we have to check all the
        keys.
        """
    for key, value in controllerport.items():
        if key.lower() == 'wwn':
            return value
    return None


def p_mul_expr_4(p):
    """MultiplicativeExpr : MultiplicativeExpr MOD UnaryExpr"""
    p[0] = 'arith', 'mod', p[1], p[3]


def topics():
    """ Return all topics (list)
        """


def split_smiles(smiles: str) ->list:
    """Splits a SMILES string into individual tokens.

    This will split a SMILES string into tokens representing
    individual parts of the SMILES string. Each individual token
    will be one of the following,

    - A single atom (including hydrogens or charge if specified)
    - A ring connection number (single digit or multi-digit)
    - Another SMILES character

    Args:
        smiles: The input SMILES string.

    Returns:
        A list of tokens.
    """
    result = []
    while smiles != '':
        if smiles[:2] == 'Cl' or smiles[:2] == 'Br':
            token_length = 2
        elif smiles[0] == '%':
            token_length = 3
        elif smiles[0] == '[':
            token_length = smiles.index(']') + 1
        else:
            token_length = 1
        result.append(smiles[:token_length])
        smiles = smiles[token_length:]
    return result


def lod_clear_all():
    """Remove all levels of detail from this object

    """
    pass


def np_immutable(a):
    """Make a NumPy array immutable."""
    a.flags.writeable = False
    return a


def extend(a: dict, b: dict) ->dict:
    """Merge two dicts and return a new dict. Much like subclassing works."""
    res = a.copy()
    res.update(b)
    return res


@staticmethod
def discrete_to_indicators(x, discrete):
    """Change non-zero values of discrete attributes to 1."""
    if discrete.any():
        x = x.copy()
        for col, disc in enumerate(discrete):
            if disc:
                x[:, (col)].clip(0, 1, out=x[:, (col)])
    return x


def p_filter_expr_1(p):
    """FilterExpr : PrimaryExpr"""
    p[0] = p[1]


def get_host(environ):
    """Return the real host for the given WSGI environment.  This takes care
    of the `X-Forwarded-Host` header.

    :param environ: the WSGI environment to get the host of.
    """
    scheme = environ.get('wsgi.url_scheme')
    if 'HTTP_X_FORWARDED_HOST' in environ:
        result = environ['HTTP_X_FORWARDED_HOST']
    elif 'HTTP_HOST' in environ:
        result = environ['HTTP_HOST']
    else:
        result = environ['SERVER_NAME']
        if (scheme, str(environ['SERVER_PORT'])) not in (('https', '443'),
            ('http', '80')):
            result += ':' + environ['SERVER_PORT']
    if result.endswith(':80') and scheme == 'http':
        result = result[:-3]
    elif result.endswith(':443') and scheme == 'https':
        result = result[:-4]
    return result


def _get_sentences_with_word_count(sentences, word_count):
    """Get list of sentences. Total number of returned words close to specified `word_count`.

    Parameters
    ----------
    sentences : list of :class:`~gensim.summarization.syntactic_unit.SyntacticUnit`
        Given sentences.
    word_count : int or None
        Number of returned words. If None full most important sentences will be returned.

    Returns
    -------
    list of :class:`~gensim.summarization.syntactic_unit.SyntacticUnit`
        Most important sentences.

    """
    length = 0
    selected_sentences = []
    for sentence in sentences:
        words_in_sentence = len(sentence.text.split())
        if abs(word_count - length - words_in_sentence) > abs(word_count -
            length):
            return selected_sentences
        selected_sentences.append(sentence)
        length += words_in_sentence
    return selected_sentences


@classmethod
def user_exists(cls, *args, **kwargs):
    """
        Return True/False if a User instance exists with the given arguments.
        Arguments are directly passed to filter() manager method.
        """
    return cls.user_query().filter_by(*args, **kwargs).count() > 0


def itervalues(obj, **kwargs):
    """Use this only if compatibility with Python versions before 2.7 is
    required. Otherwise, prefer viewvalues().
    """
    func = getattr(obj, 'itervalues', None)
    if not func:
        func = obj.values
    return func(**kwargs)


@classmethod
def _check_model_type(cls, model):
    """
        Check model type to ensure it is operable. Raises an exception if the
        model is the wrong type or some other error is encountered. Derived
        classes should implement this method.

        Parameters
        ----------
        model
            model to be operated on

        Returns
        -------
        None
        """
    pass


def print_upper_triangular_matrix_as_complete(matrix):
    """Prints a CVRP data dict upper triangular matrix as a normal matrix

    Doesn't print headers.

    Arguments
    ---------
    matrix : dict
        Description

    """
    for i in sorted(matrix.keys()):
        for j in sorted(matrix.keys()):
            a, b = i, j
            if a > b:
                a, b = b, a
            print(matrix[a][b], end=' ')
        print()


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 on_error(ws, error):
    """
    Prints an error, if occurs.

    :param ws: WebSocketApp
    :param error: An error
    """
    print(error)


def status_command(api, command, **selections):
    """ Launch testbed status commands

    :param api: API Rest api object
    :param command: command that should be run
    :param **selections: other selections (site, archi, state)
    """
    assert command in ('sites', 'nodes', 'nodes-ids', 'experiments')
    if command == 'experiments':
        result = api.get_running_experiments()
    elif command == 'sites':
        result = api.get_sites_details()
    elif command == 'nodes':
        result = api.get_nodes(**selections)
    else:
        result = api.get_nodes(list_id=True, **selections)
    return result


def inferNamespacePrefix(aUri):
    """
    From a URI returns the last bit and simulates a namespace prefix when rendering the ontology.

    eg from <'http://www.w3.org/2008/05/skos#'>
        it returns the 'skos' string
    """
    stringa = aUri.__str__()
    try:
        prefix = stringa.replace('#', '').split('/')[-1]
    except:
        prefix = ''
    return prefix


def check(rank, default=None):
    """Check whether `rank` is greater than `default`."""
    return rank > default.upper() if default is not None else False


def __add_default_parameter(signature, args, kwargs):
    """
    Add default parameters present in the signature that are not already in :attr:`kwargs`

    :param signature:
    :param args:
    :param kwargs:
    :return:
    """
    for p in signature.parameters.values():
        if p.name not in kwargs and p.default is not p.empty:
            kwargs[p.name] = p.default


def list_children(ParentId=None, ChildType=None, NextToken=None, MaxResults
    =None):
    """
    Lists all of the OUs or accounts that are contained in the specified parent OU or root. This operation, along with  ListParents enables you to traverse the tree structure that makes up this root.
    See also: AWS API Documentation

    :example: response = client.list_children(
        ParentId='string',
        ChildType='ACCOUNT'|'ORGANIZATIONAL_UNIT',
        NextToken='string',
        MaxResults=123
    )

    :type ParentId: string
    :param ParentId: [REQUIRED]
            The unique identifier (ID) for the parent root or OU whose children you want to list.
            The regex pattern for a parent ID string requires one of the following:
            Root: a string that begins with 'r-' followed by from 4 to 32 lower-case letters or digits.
            Organizational unit (OU): a string that begins with 'ou-' followed by from 4 to 32 lower-case letters or digits (the ID of the root that the OU is in) followed by a second '-' dash and from 8 to 32 additional lower-case letters or digits.

    :type ChildType: string
    :param ChildType: [REQUIRED]
            Filters the output to include only the specified child type.

    :type NextToken: string
    :param NextToken: Use this parameter if you receive a NextToken response in a previous request that indicates that there is more output available. Set it to the value of the previous call's NextToken response to indicate where the output should continue from.

    :type MaxResults: integer
    :param MaxResults: (Optional) Use this to limit the number of results you want included in the response. If you do not include this parameter, it defaults to a value that is specific to the operation. If additional items exist beyond the maximum you specify, the NextToken response element is present and has a value (is not null). Include that value as the NextToken request parameter in the next call to the operation to get the next part of the results. Note that Organizations might return fewer results than the maximum even when there are more results available. You should check NextToken after every operation to ensure that you receive all of the results.

    :rtype: dict
    :return: {
        'Children': [
            {
                'Id': 'string',
                'Type': 'ACCOUNT'|'ORGANIZATIONAL_UNIT'
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    Account: a string that consists of exactly 12 digits.
    Organizational unit (OU): a string that begins with "ou-" followed by from 4 to 32 lower-case letters or digits (the ID of the root that contains the OU) followed by a second "-" dash and from 8 to 32 additional lower-case letters or digits.

    """
    pass


def _create_combined_set(words, startindex):
    """
    Combines a single string wrapped in parenthesis from a list of words.
    Example: ['feature1', 'or', '(feature2', 'and', 'feature3)'] -> '(feature2 and feature3)'
    :param words: List of words
    :param startindex: Index of starting parenthesis.
    :return: string
    """
    counter = 0
    for i, word in enumerate(words[startindex:]):
        if ')' in word and counter == 0:
            return ' '.join(words[startindex:startindex + i + 1]), i
        elif ')' in word and counter != 0:
            amount = word.count(')')
            counter -= amount
        if '(' in word:
            counter += word.count('(')
        if counter == 0:
            return ' '.join(words[startindex:startindex + i + 1]), i
    return None, 0


@classmethod
def fromFile(cls, memoryMapping, memdump):
    """
            Transform a MemoryMapping to a file-backed MemoryMapping using FileBackedMemoryMapping.

            memoryMapping is the MemoryMapping instance.
            memdump is used as memory_mapping content.

        """
    return cls(memdump, memoryMapping.start, memoryMapping.end,
        memoryMapping.permissions, memoryMapping.offset, memoryMapping.
        major_device, memoryMapping.minor_device, memoryMapping.inode,
        memoryMapping.pathname)


def computeConfusionMatrix(model, samples, responses):
    """computes the confusion matrix of the classifier (model)

    samples should be n samples by m variables"""
    classifications = {}
    predictions = model.predict(samples)
    for predicted, y in zip(predictions, responses):
        classifications[y, predicted] = classifications.get((y, predicted), 0
            ) + 1
    return classifications


def has_variable(obj, variable):
    """Tries to check if an object has a variable."""
    if hasattr(obj, 'has_variable'):
        return obj.has_variable(variable)
    return False


def extrude_vertices_move(MESH_OT_extrude_verts_indiv=None,
    TRANSFORM_OT_translate=None):
    """Extrude vertices and move result

    :param MESH_OT_extrude_verts_indiv: Extrude Only Vertices, Extrude individual vertices only
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def print_without_newline(argtext):
    """Print with no new line."""
    print(argtext, end='')


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 __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


@staticmethod
def get_compatable_state_types():
    """
        This is needed so the service framework knows which
        states this current state is compatable.
        return::['str'] A list of the compatable state, update types.
        """
    return ['delta_update_in']


def multi_tally(pddf):
    """This example function sums each row of a Pandas DataFrame, then increases
    the total count if the sum is greater than 25.

    Args:
        pddf (:obj: pd.DataFrame): Pandas DataFrame. laminar_examples.laminar_df
            may be used as an example. It contains 3 columns ['Col1', 'Col2', 'Col3'],
            each of which contains integer values.

    Returns:
        total (int): Number of rows in pddf that summed to greater than 25.

    """
    total = 0
    for i in range(len(pddf)):
        if sum(pddf.iloc[i]) > 25:
            total += 1
    return total


def stop_replication_task(ReplicationTaskArn=None):
    """
    Stops the replication task.
    See also: AWS API Documentation

    :example: response = client.stop_replication_task(
        ReplicationTaskArn='string'
    )

    :type ReplicationTaskArn: string
    :param ReplicationTaskArn: [REQUIRED]
            The Amazon Resource Number(ARN) of the replication task to be stopped.

    :rtype: dict
    :return: {
        'ReplicationTask': {
            'ReplicationTaskIdentifier': 'string',
            'SourceEndpointArn': 'string',
            'TargetEndpointArn': 'string',
            'ReplicationInstanceArn': 'string',
            'MigrationType': 'full-load'|'cdc'|'full-load-and-cdc',
            'TableMappings': 'string',
            'ReplicationTaskSettings': 'string',
            'Status': 'string',
            'LastFailureMessage': 'string',
            'StopReason': 'string',
            'ReplicationTaskCreationDate': datetime(2015, 1, 1),
            'ReplicationTaskStartDate': datetime(2015, 1, 1),
            'ReplicationTaskArn': 'string',
            'ReplicationTaskStats': {
                'FullLoadProgressPercent': 123,
                'ElapsedTimeMillis': 123,
                'TablesLoaded': 123,
                'TablesLoading': 123,
                'TablesQueued': 123,
                'TablesErrored': 123
            }
        }
    }

    """
    pass


def uniq(items):
    """Remove duplicates in given list with its order kept.

    >>> uniq([])
    []
    >>> uniq([1, 4, 5, 1, 2, 3, 5, 10])
    [1, 4, 5, 2, 3, 10]
    """
    acc = items[:1]
    for item in items[1:]:
        if item not in acc:
            acc += [item]
    return acc


@classmethod
def get_by_uuid(cls, context, uuid):
    """Find a volume target based on its UUID.

        :param cls: the :class:`VolumeTarget`
        :param context: security context
        :param uuid: the UUID of a volume target
        :returns: a :class:`VolumeTarget` object
        :raises: VolumeTargetNotFound if no volume target with this UUID exists
        """
    db_target = cls.dbapi.get_volume_target_by_uuid(uuid)
    target = cls._from_db_object(context, cls(), db_target)
    return target


def middle_segment(points):
    """
    Get middle line segment.
    """
    m = len(points) // 2
    assert m - 1 >= 0 and m < len(points)
    return points[m - 1], points[m]


@classmethod
def create(cls, pskc, value):
    """Construct an encryped value from a plaintext value."""
    if not isinstance(value, type(b'')):
        value = value.encode()
    cipher_value = pskc.encryption.encrypt_value(value)
    mac_value = None
    if pskc.mac.algorithm:
        mac_value = pskc.mac.generate_mac(cipher_value)
    return cls(cipher_value, mac_value, pskc.encryption.algorithm)


def get_types(parsed_package):
    """
    Get a list of all types defined in the parsed package.
    """
    types = (parsed_package.enumeration_types + parsed_package.record_types +
        parsed_package.array_types + parsed_package.subtypes)
    return types


def p_col(p):
    """col : scalar_col
           | scalar_step_col
           | attr_col
           | flag_col
    """
    p[0] = p[1]


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

    """
    pass


def list_jobs(MaxJobs=None, Marker=None, APIVersion=None):
    """
    This operation returns the jobs associated with the requester. AWS Import/Export lists the jobs in reverse chronological order based on the date of creation. For example if Job Test1 was created 2009Dec30 and Test2 was created 2010Feb05, the ListJobs operation would return Test2 followed by Test1.
    See also: AWS API Documentation

    :example: response = client.list_jobs(
        MaxJobs=123,
        Marker='string',
        APIVersion='string'
    )

    :type MaxJobs: integer
    :param MaxJobs: Sets the maximum number of jobs returned in the response. If there are additional jobs that were not returned because MaxJobs was exceeded, the response contains IsTruncatedtrue/IsTruncated. To return the additional jobs, see Marker.

    :type Marker: string
    :param Marker: Specifies the JOBID to start after when listing the jobs created with your account. AWS Import/Export lists your jobs in reverse chronological order. See MaxJobs.

    :type APIVersion: string
    :param APIVersion: Specifies the version of the client tool.

    :rtype: dict
    :return: {
        'Jobs': [
            {
                'JobId': 'string',
                'CreationDate': datetime(2015, 1, 1),
                'IsCanceled': True|False,
                'JobType': 'Import'|'Export'
            },
        ],
        'IsTruncated': True|False
    }

    :returns:
    (dict) -- Output structure for the ListJobs operation.
    Jobs (list) -- A list container for Jobs returned by the ListJobs operation.
    (dict) -- Representation of a job returned by the ListJobs operation.
    JobId (string) -- A unique identifier which refers to a particular job.
    CreationDate (datetime) -- Timestamp of the CreateJob request in ISO8601 date format. For example "2010-03-28T20:27:35Z".
    IsCanceled (boolean) -- Indicates whether the job was canceled.
    JobType (string) -- Specifies whether the job to initiate is an import or export job.

    IsTruncated (boolean) -- Indicates whether the list of jobs was truncated. If true, then call ListJobs again using the last JobId element as the marker.

    """
    pass


def validate_capabilities(ns):
    """ Extracts multiple space-separated capabilities """
    from azure.mgmt.cosmosdb.models import Capability
    if ns.capabilities is not None:
        capabilties_list = []
        for item in ns.capabilities:
            capabilties_list.append(Capability(name=item))
        ns.capabilities = capabilties_list


def _get_report_class_name(request, default=None):
    """Given a request, it returns the report class name"""
    return request.POST.get('report', request.GET.get('report', default))


def _logs_exist(fs, path):
    """Do ``fs.exists(path)``, and return ``None`` if it raises ``IOError``"""
    try:
        return fs.exists(path)
    except IOError:
        return None


def is_empty(value):
    """
    if value is None returns True.

    if value is empty iterable (for example, empty str or emptry list),
    returns true
    otherwise false

    Note: For not iterable values, behaivour is undefined.

    :param value:
    :return:
    """
    if value is None:
        return True
    if value:
        ret = False
    else:
        ret = True
    return ret


@staticmethod
def get_expressions(text):
    """Yield valid expressions from text."""
    for line in text.splitlines():
        line_text = line.strip()
        if not line_text or line_text.startswith('#'):
            continue
        expr_text = line_text.split('#', 1)[0].strip()
        yield expr_text


def clean(url: str) ->str:
    """
    Transforms the actual resource URL to something users can go fetch.

    This should be fixed in the server itself at some point.
    """
    return url.replace('/api/', '/')


@classmethod
def from_xml(cls, node):
    """
        Construct a Wire from an EAGLE XML ``wire`` node.
        """
    curve = node.attrib.get('curve')
    curve = curve and float(curve)
    return cls(start=(float(node.attrib['x1']), float(node.attrib['y1'])),
        end=(float(node.attrib['x2']), float(node.attrib['y2'])), width=
        float(node.attrib['width']), layer=int(node.attrib['layer']), curve
        =curve, cap=node.attrib.get('cap'))


@classmethod
def create_type_variants(cls, type_names, type_dict):
    """
        Create type variants for types with a cardinality field.
        The new type converters are based on the type converter with
        cardinality=1.

        .. code-block:: python

            # -- USE: parse_number() type converter function.
            new_types = CardinalityFieldTypeBuilder.create_type_variants(
                            ["Number?", "Number+"], dict(Number=parse_number))

        :param type_names: List of type names with cardinality field suffix.
        :param type_dict:  Type dictionary with named type converters.
        :return: Type dictionary with type converter variants.
        """
    type_variant_dict = {}
    for type_name in type_names:
        type_variant = cls.create_type_variant(type_name, type_dict)
        type_variant_dict[type_name] = type_variant
    return type_variant_dict


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

    The ".dev0" means dirty.

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


@classmethod
def get(cls, id_):
    """Get an instance of an entity by ID or slug.

        Args:
            id_ (str):
                ID or slug of a catalog entity.

        Raises:
            CatalogError: if there's a problem when connecting to the catalog or no entities are found.

        """
    return cls._entity_repo.get_by_id(id_)


@classmethod
def from_frame_point(cls, tcp_frame, cog_pt=None, **kwargs):
    """Create RapidToolData object from :class:`compas.Geometry.Primitive` objects.

        Parameters
        ----------
        tcp_frame : :class:`compas.geometry.Frame`
            Frame at tool center plane.
        cog_pt : :class:`compas.geometry.Point`, optional
            Point at tool center of gravity.
        name : :class:`str`, optional
        weight : :class:`float`, optional
            Tool weight in kg

        Returns
        -------
        :class:`RapidToolData`
        """
    tcp_coord = tcp_frame.point.data
    tcp_quaternion = tcp_frame.quaternion.wxyz
    if cog_pt:
        kwargs.update({'cog_coord': cog_pt.data})
    return cls(tcp_coord, tcp_quaternion, **kwargs)


def _apply_default_for_one_key(key, cfg, shared):
    """apply default to a config for a key

    Parameters
    ----------
    key : str
        A config key
    cfg : dict
        A config
    shared : dict
        A dict of shared objects.

    Returns
    -------
    function
        A config with default applied

    """
    ret = {}
    for default_cfg in shared['default_cfg_stack']:
        ret.update(default_cfg.get(key, {}))
    ret.update(cfg)
    return ret


def product(iterable):
    """Return product of sequence of numbers.

    Equivalent of functools.reduce(operator.mul, iterable, 1).

    >>> product([2**8, 2**30])
    274877906944
    >>> product([])
    1

    """
    prod = 1
    for i in iterable:
        prod *= i
    return prod


def displayArray(name, a, width=0):
    """
    Prints an array (any sequence of floats, really) to the screen.
    """
    print(name + ': ', end=' ')
    cnt = 0
    for i in a:
        print('%4.2f' % i, end=' ')
        if width > 0 and (cnt + 1) % width == 0:
            print('')
        cnt += 1


@staticmethod
def _normalize_cmd(command):
    """Normalize CLI commands to have a single trailing newline"""
    command = command.rstrip('\n')
    command += '\n'
    return command


@classmethod
def episode(cls, title, season, episode):
    """
        Returns information for an episode

        :param title: Either the slug (i.e. the-walking-dead) or TVDB ID
        :param season: The season number. Use 0 if you want the specials
        :param episode: The episode number
        """
    return cls._get('show/episode/summary', title, season, episode)


@classmethod
def axesNames(cls):
    """ The names of the axes that this inspector visualizes.
            See the parent class documentation for a more detailed explanation.

            Returns an empty tuple; the data under inspection is zero-dimensional.
        """
    return tuple()


def temp_ids(n=-1):
    """
    Create an iterator for temporary IDs for nodes, links and other entities
    that need them. You need to initialise the temporary id first and call the
    next element using the ``.next()`` function::

        temp_node_id = PluginLib.temp_ids()

        # Create a node
        # ...

        Node.id = temp_node_id.next()
    """
    while True:
        yield n
        n -= 1


def _rename_amino_acid(df):
    """ 3 letter to single letter amino-acid code"""
    STY = {'Ser': 'S', 'Thr': 'T', 'Tyr': 'Y'}
    amino_acid = STY.get(df['ORIGINAL'].iloc[0], float('NaN'))
    df['Amino.Acid'] = amino_acid
    return df


def find_var(variable, vars, ret_origin=False):
    """
    Find secrets variables in variables list from project.
    | Format for `vars` argument:

   ``{"variable_name": ["ALIAS_1", "ALIAS_2", ..., "ALIAS_N"]}``

   Alias list compared with secret variables name in gitlab and return true if variable was found.

    :param variable: Environment variable object.
    :type variable: :py:class:`gitlab.v4.objects.ProjectVariable`
    :param vars: Replaced vars config.
    :type vars: dict
    :param ret_origin: Return origin variable
    :type ret_origin: bool

    :returns:
        Variable name if variable was found.

        If variable does not found, returned ``False``
    """
    for var_name, names in vars.items():
        for name in names:
            if variable.key == name:
                return var_name if not ret_origin else name
    return False


def coordinate_index(x, xmin, xmax, dx):
    """
    Takes care of reversed coordinates, typically y with a negative value for dy.
    """
    if dx < 0:
        xi = ((xmax - x) / abs(dx)).astype(int)
    else:
        xi = ((x - xmin) / abs(dx)).astype(int)
    return xi


def delete_method(restApiId=None, resourceId=None, httpMethod=None):
    """
    Deletes an existing  Method resource.
    See also: AWS API Documentation

    :example: response = client.delete_method(
        restApiId='string',
        resourceId='string',
        httpMethod='string'
    )

    :type restApiId: string
    :param restApiId: [REQUIRED]
            The RestApi identifier for the Method resource.

    :type resourceId: string
    :param resourceId: [REQUIRED]
            The Resource identifier for the Method resource.

    :type httpMethod: string
    :param httpMethod: [REQUIRED]
            The HTTP verb of the Method resource.

    """
    pass


@classmethod
def parse(cls, console, data):
    """Initialize model

        :param data: JSON data to parse
        :param console: Console object from which API calls are made
        :return: Initializes sub-class
        """
    return cls(console, data)


@staticmethod
def set(config, key, value, sourceid='defaults'):
    """Sets a value in this config object *without* marking any source
        dirty, and with exact control of exactly where to set the
        value. This is mostly useful for low-level trickery with
        config objects.

        :param config: The configuration object to set values on
        :param key: The parameter name
        :param value: The new value
        :param sourceid: The identifier for the underlying source that the
                         value should be set on.
        """
    for source in config._sources:
        if source.identifier == sourceid:
            source.set(key, value)


def getText(nodelist):
    """DOM helper, for extracting text"""
    rc = ''
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc = rc + node.data
    return rc


@property
def cpu_mhz(cls):
    """The getter method for CPU clock.

        The returned clock rate is measured in MHz.

        """
    return cls.get_cpu_mhz()


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


@staticmethod
def transform_category_nans(df):
    """ONLY TRANSFORM: Convert np.NaNs to a category 'NaN'"""
    for column in df.select_dtypes(include=['category']).columns:
        if 'NaN' in df[column].cat.categories:
            df[column].fillna('NaN', inplace=True)


def _bkwds(inst, Error=AttributeError, **n_v_s):
    """(INTERNAL) Set applicable C{bool} attributes.
    """
    for n, v in n_v_s.items():
        b = getattr(inst, n, None)
        if b is None:
            t = n, v, inst.__class__.__name__
            raise Error('not applicable: %s=%r for %s' % t)
        if v in (False, True) and v != b:
            setattr(inst, '_' + n, v)


def editmode_toggle():
    """Toggle object’s editmode

    """
    pass


def reports_to_textblock():
    """Write the reports

    """
    pass


def rmdup(obj):
    """Return a list without duplicates."""
    new = []
    for i in obj:
        if i not in new:
            new.append(i)
    return type(obj)(new)


@classmethod
def is_init_default(cls, value):
    """Returns ``True`` if the ``value`` is the initial default."""
    return value is cls._DEFAULT


def reindex(batch=1000, skip=0):
    """ find all contentish objects (meaning all objects derived from one
            of the catalog mixin classes) and (re)indexes them """


def get_correctly_extended_latex_label(label, label_extension):
    """Function to obtain a correctly extended latex label.

    :param label: label to be extended
    :type label: str
    :param label_extension: extensions of the label
    :type label_extension: str
    :return: extended latex label
    :rtype: str
    """
    if '^{' in label and '^{' in label_extension:
        return label[:-1] + ',' + label_extension[2:]
    else:
        return label + label_extension


@classmethod
def read_json_file(cls, path):
    """
        Construct a VariantCollection from a JSON file.
        """
    with open(path, 'r') as f:
        json_string = f.read()
    return cls.from_json(json_string)


def eval_str(string):
    """Executes a string containing python code."""
    output = eval(string)
    return output


def smoothness(y, r=20, stepsize=1, domain=None, unsigned=False):
    """
    This fucntion calculates a smoothness measure on the input 1D data.
    The concept is similar to that decribed here: http://www.goldensoftware.com/variogramTutorial.pdf

    USAGE
    ---
    u,x = smoothness(t,y,r=4)

    INPUTS
    ---
    t,          Domain points of data set
    y,          Range of data set
    r=4,        Radius of which to consider variations (derivates)
    stepsize=1, The average will be considered every stepsize points. Increasing
                this from its default of 1 can be useful when processing large
                data sets; however, when stepsize is not 1, the length of the
                output will differ from that of the inputs.

    OUTPUTS
    ---
    u,       Sub-domain which is one-to-one with smoothness measure
    x,       Smoothness measure -- the data, y, is smooth when |x| is approx. 1
             NOTE that x=-1 is smooth and decreasing while x=1 is smooth and increasing

    """
    from numpy import arange, var, std, polyfit, poly1d, mean, diff, zeros_like, array
    from scipy.interpolate import InterpolatedUnivariateSpline as spline
    if domain is None:
        domain = list(range(0, len(y)))
    x, u = [], []
    for k in arange(0, len(y), stepsize):
        a = max(0, k - r)
        b = min(len(y), k + r) - 1
        D = (y[b] - y[a]) / (b - a)
        if unsigned:
            D = abs(D)
        d = abs(mean(diff(y[a:b])))
        x.append(D / d if d != 0 else 0)
        u.append((domain[a] + domain[b]) / 2)
    x = array(x)
    if stepsize > 1:
        x = spline(u, x, k=1)(domain)
    return x


def write_gene_list(output_file, genelist):
    """Save a list of genes to a file, one gene per line.

    Arguments:
    output_file -- path to which the output file should be written
    genelist -- iterable of genes that should be included in the output file

    """
    with open(output_file, 'w') as out_f:
        for gene in genelist:
            out_f.write(gene + '\n')


def getKeyForAPI(cls, siteStore, apiName):
    """
        Get the API key for the named API, if one exists.

        @param siteStore: The site store.
        @type siteStore: L{axiom.store.Store}

        @param apiName: The name of the API.
        @type apiName: C{unicode} (L{APIKey} constant)

        @rtype: L{APIKey} or C{NoneType}
        """
    return siteStore.findUnique(cls, cls.apiName == apiName, default=None)


def _uuid_set_high_bit(pvm_uuid):
    """Turns on the high bit of a uuid

    PowerVM uuids always set the byte 0, bit 0 to 0.
    So to convert it to an OpenStack uuid we may have to set the high bit.

    :param uuid: A PowerVM compliant uuid
    :returns: A standard format uuid string
    """
    return '%x%s' % (int(pvm_uuid[0], 16) | 8, pvm_uuid[1:])


def getAdapters(objects, provided):
    """Look for all matching adapters to a provided interface for objects

        Return an iterable of name-adapter pairs for adapters that
        provide the given interface.
        """


def third(items):
    """
    Gets the third item from a collection.
    """
    return items[2]


def extract_sol(scs_x, solmap):
    """ Extract a solution from the SCS output variable `x`.
    solmap is a dict mapping variable names to indices (slices) of x.
    """
    x_vals = {}
    for k in solmap:
        x_vals[k] = scs_x[solmap[k]]
        if len(x_vals[k]) == 1:
            x_vals[k] = x_vals[k][0]
    return x_vals


def powerlaw(x, amplitude=1, exponent=1.0):
    """Return the powerlaw function.

    x -> amplitude * x**exponent

    """
    return amplitude * x ** exponent


def string2list_of_integers(s, separator=', '):
    """Convers a string of integer separated by comma, into a list of integer"""
    arr = []
    if s != '':
        arrs = s.split(separator)
        for a in arrs:
            arr.append(int(a))
    return arr


def is_primitive(item):
    """
    Determines if the given item is a primitive value (either an int, float,
    str, bool, or None).

    Args:
        item (any): Any value
    Returns:
        bool: Whether the item is a primitive value.
    """
    return isinstance(item, (int, float, str, bool)) or item is None


@staticmethod
def flatten(l):
    """
        from http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html
        :param l:
        :return:
        """
    list_type = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], list):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return list_type(l)


def _check_img_lib():
    """Utility to search for imageio or PIL"""
    imageio = PIL = None
    try:
        import imageio
    except ImportError:
        try:
            import PIL.Image
        except ImportError:
            pass
    return imageio, PIL


def _fix_sequence(seq):
    """Returns string where terminal gaps are replaced with terminal CCA.

        Some of the sequence in the Genomic tRNA Database have gaps where the
        acceptor stem (terminal CCA) should be.  This function checks the
        number of terminal gaps and replaces with appropriate part of terminal
        CCA.
    """
    if seq.endswith('---'):
        seq = seq[:-3] + 'CCA'
    elif seq.endswith('--'):
        seq = seq[:-2] + 'CA'
    elif seq.endswith('-'):
        seq = seq[:-1] + 'A'
    return seq


def andify(seq, two_comma=False):
    """Join the elements of a sequence and return a string of the form
    "*x* and *y*" for a two-element list, or "*x*, *y*, and *z*" for
    three or more elements.  If *two_comma* is True, insert a comma
    before "and" even if the list is only two elements long ("*x*, and
    *y*")."""
    if len(seq) > 2:
        return ', '.join(seq[:-2] + [', and '.join(seq[-2:])])
    if two_comma:
        return ', and '.join(seq)
    return ' and '.join(seq)


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

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


def _build_bool_type(var, property_path=None):
    """ Builds schema definitions for boolean type values.

    :param var: The boolean type value
    :param List[str] property_path: The property path of the current type,
        defaults to None, optional
    :param property_path: [type], optional
    :return: The built schema definition
    :rtype: Dict[str, Any]
    """
    if not property_path:
        property_path = []
    return {'type': 'boolean'}


def zerocopy_to_dlpack(input):
    """Create a dlpack tensor that shares the input memory.

    Parameters
    ----------
    input : Tensor
        The input tensor

    Returns
    -------
    dlpack capsule
        A dlpack capsule that can be used by other framework.
    """
    pass


def setHook(hook):
    """ set the hook for the transaction manager;  this hook must be
            called whenever an indexing operation is added to the queue """


def lengths_offsets_split(value):
    """ Split the given comma separated values to multiple integer values"""
    values = []
    for item in value.split(','):
        item = int(item)
        values.append(item)
    return values


def create_token_lst(s, str_to_token):
    """create token list:
    'True or False' -> [True, lambda..., False]"""
    s = s.replace('(', ' ( ')
    s = s.replace(')', ' ) ')
    out = []
    for it in s.split():
        if it in ['not', 'and', 'or']:
            out.append(it)
        else:
            out.append(str_to_token[it])
    return out


def python_3000_not_equal(logical_line):
    """New code should always use != instead of <>.

    The older syntax is removed in Python 3.

    Okay: if a != 'no':
    W603: if a <> 'no':
    """
    pos = logical_line.find('<>')
    if pos > -1:
        yield pos, "W603 '<>' is deprecated, use '!='"


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 leafage(elts, fun_deps):
    """Get all leafs of DAG

    >>> graph = {2: [1]}
    >>> get_children = lambda n: graph.get(n, [])
    >>> list(leafage([], get_children))
    []
    >>> list(leafage([2, 1], get_children))
    [1]
    >>> sorted(leafage([2, 3], get_children))
    [1, 3]

    """
    done = set([])
    todo = set(elts)
    leafs = set([])
    while todo:
        e = todo.pop()
        done.add(e)
        deps = fun_deps(e)
        if len(deps) == 0:
            leafs.add(e)
        else:
            for d in deps:
                if d not in done:
                    todo.add(d)
    return leafs


def __extend_uri(prefixes, short):
    """
    Extend a prefixed uri with the help of a specific dictionary of prefixes
    :param prefixes: Dictionary of prefixes
    :param short: Prefixed uri to be extended
    :return:
    """
    for prefix in prefixes:
        if short.startswith(prefix):
            return short.replace(prefix + ':', prefixes[prefix])
    return short


@staticmethod
def _scale_ordered_unit_names(unit_names):
    """
            Swap the day_of_week and month order so that 'overflow' happens in the right order.
            :returns: unit names in ascending order of scale
        """
    unit_names[4], unit_names[5] = unit_names[5], unit_names[4]
    return unit_names


def valid_int(value):
    """
    Returns True if `value` is a valid integer (can be converted to an int).

    **Example usage**

    >>> valid_int('dimitri is not a valid integer')
    False
    >>> valid_int('-10')
    True
    """
    try:
        int(value)
        return True
    except ValueError:
        return False


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

    The ".dev0" means dirty.

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


def update_filler(pairs, where_key):
    """
    Manually aligning the bindings for UPDATE statements is annoying.
    Given a dictionary of {column: value} as well as the name of the column
    to be used as the WHERE, return the "SET ..." portion of the query and the
    bindings in the correct order.

    If the where_key needs to be reassigned also, let its value be a 2-tuple
    where [0] is the current value used for WHERE, and [1] is the new value
    used for SET.

    Example:
    pairs={'id': '1111', 'name': 'James', 'score': 20},
    where_key='id'
    ->
    returns ('SET name = ?, score = ? WHERE id == ?', ['James', 20, '1111'])

    Example:
    pairs={'filepath': ('/oldplace', '/newplace')},
    where_key='filepath'
    ->
    returns ('SET filepath = ? WHERE filepath == ?', ['/newplace', '/oldplace'])

    In context:
    (qmarks, bindings) = update_filler(data, where_key)
    query = 'UPDATE table %s' % qmarks
    cur.execute(query, bindings)
    """
    pairs = pairs.copy()
    where_value = pairs.pop(where_key)
    if isinstance(where_value, tuple):
        where_value, pairs[where_key] = where_value
    if isinstance(where_value, dict):
        where_value = where_value['old']
        pairs[where_key] = where_value['new']
    if len(pairs) == 0:
        raise ValueError('No pairs left after where_key.')
    qmarks = []
    bindings = []
    for key, value in pairs.items():
        qmarks.append('%s = ?' % key)
        bindings.append(value)
    bindings.append(where_value)
    setters = ', '.join(qmarks)
    qmarks = 'SET {setters} WHERE {where_key} == ?'
    qmarks = qmarks.format(setters=setters, where_key=where_key)
    return qmarks, bindings


@classmethod
def from_json(cls, data):
    """
        Instantiate YNAB object directly from raw JSON data.

        Parameters
        ----------
        data : dict

        Returns
        -------
        ynab : YNAB
        """
    instance = object.__new__(cls)
    instance._init_data(data)
    return instance


def sub(a, b):
    """ Subtract two values, ignoring None """
    if a is None:
        if b is None:
            return None
        else:
            return -1 * b
    elif b is None:
        return a
    return a - b


def get_end_time(starttime, num, span):
    """ Utility function
    """
    if not starttime or len(starttime) < 4:
        return ''
    m = int(starttime[2:])
    hour = int(starttime[:2]) + (m + int(num) * span) / 60
    minute = (m + int(num) * span) % 60
    return str(hour).zfill(2) + str(minute).zfill(2)


def pairwise(iterable):
    """s - > (s0, s1), (s1, s2), (s2, s3), ..."""
    a = iter(iterable)
    b = iter(iterable)
    next(b, None)
    return zip(a, b)


def getSearchSchema():
    """Return the schema describing the fields of the search form
        for this query.
        """


def bone_siblings(obj, bone):
    """ Returns a list of the siblings of the given bone.
        This requires that the bones has a parent.

    """
    parent = obj.data.bones[bone].parent
    if parent is None:
        return []
    bones = []
    for b in parent.children:
        if b.name != bone:
            bones += [b.name]
    return bones


def get_text():
    """Return post text content
        """


def module_is_namespace(mod):
    """Is the module object `mod` a PEP420 namespace module?"""
    return hasattr(mod, '__path__') and getattr(mod, '__file__', None) is None


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

    `broadcast_plus` is an alias to the function `broadcast_add`.

    Example::

       x = [[ 1.,  1.,  1.],
            [ 1.,  1.,  1.]]

       y = [[ 0.],
            [ 1.]]

       broadcast_add(x, y) = [[ 1.,  1.,  1.],
                              [ 2.,  2.,  2.]]

       broadcast_plus(x, y) = [[ 1.,  1.,  1.],
                               [ 2.,  2.,  2.]]

    Supported sparse operations:

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

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

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

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

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


@staticmethod
def disable_undo():
    """
        Disables undo functionality
        """
    return False


def render_row(num, columns, widths, column_colors=None):
    """
    Render the `num`th row of each column in `columns`.

    :param num: Which row to render.
    :type num: ``int``
    :param columns: The list of columns.
    :type columns: [[``str``]]
    :param widths: The widths of each column.
    :type widths: [``int``]
    :param column_colors: An optional list of coloring functions.
    :type column_colors: [``str`` -> ``str``] or ``NoneType``

    :return: The rendered row.
    :rtype: ``str``
    """
    row_str = '|'
    cell_strs = []
    for i, column in enumerate(columns):
        try:
            cell = column[num]
            spaces = ' ' * (widths[i] - len(cell))
            if column_colors is not None and column_colors[i] is not None:
                cell = column_colors[i](cell)
            cell_strs.append(' %s%s ' % (cell, spaces))
        except IndexError:
            cell_strs.append(' ' * (widths[i] + 2))
    return '|%s|' % '|'.join(cell_strs)


def addSubparser(subparsers, subcommand, description):
    """
    Add a subparser with subcommand to the subparsers object
    """
    parser = subparsers.add_parser(subcommand, description=description,
        help=description)
    return parser


def add_approximant_arg(parser, default=None, help=None):
    """Adds an approximant argument to the given parser.

    Parameters
    ----------
    parser : ArgumentParser
        The argument parser to add the argument to.
    default : {None, str}
        Specify a default for the approximant argument. Defaults to None.
    help : {None, str}
        Provide a custom help message. If None, will use a descriptive message
        on how to specify the approximant.
    """
    if help is None:
        help = str(
            "The approximant(s) to use. Multiple approximants to use in different regions may be provided. If multiple approximants are provided, every one but the last must be be followed by a conditional statement defining where that approximant should be used. Conditionals can be any boolean test understood by numpy. For example, 'Apprx:(mtotal > 4) & (mchirp <= 5)' would use approximant 'Apprx' where total mass is > 4 and chirp mass is <= 5. Conditionals are applied in order, with each successive one only applied to regions not covered by previous arguments. For example, `'TaylorF2:mtotal < 4' 'IMRPhenomD:mchirp < 3'` would result in IMRPhenomD being used where chirp mass is < 3 and total mass is >= 4. The last approximant given may use 'else' as the conditional or include no conditional. In either case, this will cause the last approximant to be used in any remaning regions after all the previous conditionals have been applied. For the full list of possible parameters to apply conditionals to, see WaveformArray.default_fields(). Math operations may also be used on parameters; syntax is python, with any operation recognized by numpy."
            )
    parser.add_argument('--approximant', nargs='+', type=str, default=
        default, metavar='APPRX[:COND]', help=help)


def setClean(dev, value):
    """ set to spot, clean, or max """
    if value == 'spot':
        dev.sendMsg('\x86')
    elif value == 'clean':
        dev.sendMsg('\x87')
    elif value == 'max':
        dev.sendMsg('\x88')


def parse_call(line):
    """
    Parses lines of the following form

        Line #|      Hits|         Time| Time per hit|      %|Source code
        ------+----------+-------------+-------------+-------+-----------
        (call)|      2528|     0.352177|   0.00013931|  0.01%|# to_html.py:74 get_html_filename

    Extracts a dict of (hits, time, time_per_hit, percentage, file_name, line_number, entry_point)

    :param line: string
    :return: tuple
    """
    columns = line.split('|')
    first, sep, second = columns[5].rpartition(':')
    line_number, sep, entry_point = second.partition(' ')
    file_name = first.strip('# ')
    return {'hits': int(columns[1]), 'time': float(columns[2]),
        'time_per_hit': float(columns[3]), 'percentage': float(columns[4][:
        -1]), 'file_name': file_name, 'line_number': int(line_number),
        'entry_point': entry_point}


@staticmethod
def defaultSymbol():
    """
        Returns the default symbol path for this node.

        :returns: symbol path (or resource).
        """
    return ':/symbols/multilayer_switch.svg'


def ModelMonster(model: str, parameters: dict={}, frequency: str='infer',
    prediction_interval: float=0.9, holiday_country: str='US',
    startTimeStamps=None, forecast_length: int=14, random_seed: int=2020,
    verbose: int=0):
    """Directs strings and parameters to appropriate model objects.

    Args:
        model (str): Name of Model Function
        parameters (dict): Dictionary of parameters to pass through to model
    """
    if model == 'ZeroesNaive':
        from autots.models.basics import ZeroesNaive
        return ZeroesNaive(frequency=frequency, prediction_interval=
            prediction_interval)
    if model == 'LastValueNaive':
        from autots.models.basics import LastValueNaive
        return LastValueNaive(frequency=frequency, prediction_interval=
            prediction_interval)
    if model == 'AverageValueNaive':
        from autots.models.basics import AverageValueNaive
        if parameters == {}:
            return AverageValueNaive(frequency=frequency,
                prediction_interval=prediction_interval)
        else:
            return AverageValueNaive(frequency=frequency,
                prediction_interval=prediction_interval, method=parameters[
                'method'])
    if model == 'GLS':
        from autots.models.statsmodels import GLS
        return GLS(frequency=frequency, prediction_interval=prediction_interval
            )
    if model == 'GLM':
        from autots.models.statsmodels import GLM
        if parameters == {}:
            model = GLM(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = GLM(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose, family=parameters
                ['family'])
        return model
    if model == 'ETS':
        from autots.models.statsmodels import ETS
        if parameters == {}:
            model = ETS(frequency=frequency, prediction_interval=
                prediction_interval, random_seed=random_seed, verbose=verbose)
        else:
            model = ETS(frequency=frequency, prediction_interval=
                prediction_interval, damped=parameters['damped'], trend=
                parameters['trend'], seasonal=parameters['seasonal'],
                seasonal_periods=parameters['seasonal_periods'],
                random_seed=random_seed, verbose=verbose)
        return model
    if model == 'ARIMA':
        from autots.models.statsmodels import ARIMA
        if parameters == {}:
            model = ARIMA(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = ARIMA(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country, p=
                parameters['p'], d=parameters['d'], q=parameters['q'],
                regression_type=parameters['regression_type'], random_seed=
                random_seed, verbose=verbose)
        return model
    if model == 'FBProphet':
        from autots.models.prophet import FBProphet
        if parameters == {}:
            model = FBProphet(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = FBProphet(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                holiday=parameters['holiday'], regression_type=parameters[
                'regression_type'], random_seed=random_seed, verbose=verbose)
        return model
    if model == 'RollingRegression':
        from autots.models.sklearn import RollingRegression
        if parameters == {}:
            model = RollingRegression(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, random_seed=random_seed, verbose=verbose)
        else:
            model = RollingRegression(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, holiday=parameters['holiday'],
                regression_type=parameters['regression_type'], random_seed=
                random_seed, verbose=verbose, regression_model=parameters[
                'regression_model'], mean_rolling_periods=parameters[
                'mean_rolling_periods'], std_rolling_periods=parameters[
                'std_rolling_periods'])
        return model
    if model == 'UnobservedComponents':
        from autots.models.statsmodels import UnobservedComponents
        if parameters == {}:
            model = UnobservedComponents(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, random_seed=random_seed, verbose=verbose)
        else:
            model = UnobservedComponents(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, regression_type=parameters[
                'regression_type'], random_seed=random_seed, verbose=
                verbose, level=parameters['level'], trend=parameters[
                'trend'], cycle=parameters['cycle'], damped_cycle=
                parameters['damped_cycle'], irregular=parameters[
                'irregular'], stochastic_trend=parameters[
                'stochastic_trend'], stochastic_level=parameters[
                'stochastic_level'], stochastic_cycle=parameters[
                'stochastic_cycle'])
        return model
    if model == 'DynamicFactor':
        from autots.models.statsmodels import DynamicFactor
        if parameters == {}:
            model = DynamicFactor(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = DynamicFactor(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                regression_type=parameters['regression_type'], random_seed=
                random_seed, verbose=verbose, k_factors=parameters[
                'k_factors'], factor_order=parameters['factor_order'])
        return model
    if model == 'VECM':
        from autots.models.statsmodels import VECM
        if parameters == {}:
            model = VECM(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = VECM(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                regression_type=parameters['regression_type'], random_seed=
                random_seed, verbose=verbose, deterministic=parameters[
                'deterministic'], k_ar_diff=parameters['k_ar_diff'])
        return model
    if model == 'VARMAX':
        from autots.models.statsmodels import VARMAX
        if parameters == {}:
            model = VARMAX(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose)
        else:
            model = VARMAX(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose, order=parameters[
                'order'], trend=parameters['trend'])
        return model
    if model == 'GluonTS':
        from autots.models.gluonts import GluonTS
        if parameters == {}:
            model = GluonTS(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose, forecast_length=
                forecast_length)
        else:
            model = GluonTS(frequency=frequency, prediction_interval=
                prediction_interval, holiday_country=holiday_country,
                random_seed=random_seed, verbose=verbose, gluon_model=
                parameters['gluon_model'], epochs=parameters['epochs'],
                learning_rate=parameters['learning_rate'], forecast_length=
                forecast_length)
        return model
    if model == 'TSFreshRegressor':
        from autots.models.tsfresh import TSFreshRegressor
        if parameters == {}:
            model = TSFreshRegressor(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, random_seed=random_seed, verbose=verbose)
        else:
            model = TSFreshRegressor(frequency=frequency,
                prediction_interval=prediction_interval, holiday_country=
                holiday_country, random_seed=random_seed, verbose=verbose)
        return model
    else:
        raise AttributeError("Model String '{}' not a recognized model type"
            .format(model))


@classmethod
def less_or_equal_constraint(cls, variables, upperbound):
    """Clauses encoding a "less than or equal to" constraint

        E.g. X1 + X2 + X3 + X4 <= 2

        (~X1 v ~X2 v ~X3)
        (~X1 v ~X2 v ~X4)
        (~X1 v ~X3 v ~X4)
        (~X2 v ~X3 v ~X4)

        Parameters
        ----------
        variables : list of variables
           variables in the constraint
        upperbound: int
           upper bound of the constraint

        Returns
        -------
            a list of clauses

        Examples
        --------
        >>> list(CNF.less_than_constraint(['a','b','c'],3)) == list(CNF.less_or_equal_constraint(['a','b','c'],2))
        True
        >>> list(CNF.less_or_equal_constraint(['a','b','c'],1))
        [[(False, 'a'), (False, 'b')], [(False, 'a'), (False, 'c')], [(False, 'b'), (False, 'c')]]
        >>> list(CNF.less_or_equal_constraint(['a','b'],0))
        [[(False, 'a')], [(False, 'b')]]
        >>> list(CNF.less_or_equal_constraint(['a','b','c'],-1))
        [[]]
        >>> list(CNF.less_or_equal_constraint(['a','b','c'],10))
        []
        """
    return cls._inequality_constraint_builder(variables, upperbound + 1,
        greater=False)


@classmethod
def from_list(cls, deployments):
    """Instantiate DeploymentDefinitions from a list."""
    results = []
    if not deployments:
        return []
    for i, deployment in enumerate(deployments):
        if not deployment.get('name'):
            deployment['name'] = 'deployment_{}'.format(str(i + 1))
        results.append(cls(deployment))
    return results


def detach_internet_gateway(DryRun=None, InternetGatewayId=None, VpcId=None):
    """
    Detaches an Internet gateway from a VPC, disabling connectivity between the Internet and the VPC. The VPC must not contain any running instances with Elastic IP addresses or public IPv4 addresses.
    See also: AWS API Documentation

    Examples
    This example detaches the specified Internet gateway from the specified VPC.
    Expected Output:

    :example: response = client.detach_internet_gateway(
        DryRun=True|False,
        InternetGatewayId='string',
        VpcId='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 InternetGatewayId: string
    :param InternetGatewayId: [REQUIRED]
            The ID of the Internet gateway.

    :type VpcId: string
    :param VpcId: [REQUIRED]
            The ID of the VPC.

    :return: response = client.detach_internet_gateway(
        InternetGatewayId='igw-c0a643a9',
        VpcId='vpc-a01106c2',
    )

    print(response)

    """
    pass