@staticmethod
def _get_extension_info(extension):
    """Parse extension information.

        :param extension: a dict of a Keystone extension response
        :returns: tuple - (alias, name)
        """
    alias = extension['alias']
    name = extension['name']
    return alias, name


def disable_keep_transform():
    """Set the influence of this constraint to zero while trying to maintain the object’s transformation. Other active constraints can still influence the final transformation

    """
    pass


def humansize(nbytes):
    """
    Copied from https://stackoverflow.com/questions/14996453/python-libraries-to-calculate-human-readable-filesize-from-bytes#14996816
    """
    suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    i = 0
    while nbytes >= 1024 and i < len(suffixes) - 1:
        nbytes /= 1024.0
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])


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

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

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

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

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

    """
    pass


@staticmethod
def _transaction_begin(transaction_id, **kwargs):
    """Start a new transaction.
        :param transaction_id: ID for this transaction in the transport layer.
        :param **kwargs: Further parameters for the transport layer.
        """
    raise NotImplementedError('Transport interface not implemented')


def fileSizeString(num, suffix='B', div=1000) ->str:
    """
    Returns a human-readable file size string.
    thanks to Fred Cirera
    http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
    :param num: number in bytes
    :param suffix: 'B' for bytes by default.
    :param div: divisor of num, 1000 by default.
    :return: the file size string
    """
    for unit in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z']:
        if abs(num) < div:
            return '{:3.1f}{}{}'.format(num, unit, suffix)
        num /= div
    return '{:.1f} {}{}'.format(num, unit, suffix)


def dot(a, b):
    """Returns the dot product of two 3D vectors"""
    return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]


def timetz64_unpack(data, ql_unpack=ql_unpack, mktimetuple64=mktimetuple64):
    """
	Given "long long" serialized time data, "ql", unpack it into a pair:

	    ((seconds, microseconds), timezone_offset)
	"""
    ts, tz = ql_unpack(data)
    return mktimetuple64(ts), tz


def _pnpoly(x, y, coords):
    """
    the algorithm to judge whether the point is located in polygon
    reference: https://www.ecse.rpi.edu/~wrf/Research/Short_Notes/pnpoly.html#Explanation
    """
    vert = [[0, 0]]
    for coord in coords:
        for node in coord:
            vert.append(node)
        vert.append(coord[0])
        vert.append([0, 0])
    inside = False
    i = 0
    j = len(vert) - 1
    while i < len(vert):
        if (vert[i][0] > y) != (vert[j][0] > y) and x < (vert[j][1] - vert[
            i][1]) * (y - vert[i][0]) / (vert[j][0] - vert[i][0]) + vert[i][1]:
            inside = not inside
        j = i
        i += 1
    return inside


def count_query(tablename, condition):
    """
    Function to process query for count process
    """
    if isinstance(tablename, str):
        pass
    else:
        raise ValueError('Tablename should be a String')
    if condition == None or isinstance(condition, str):
        pass
    else:
        raise ValueError('Condition can only be either None or String')
    if condition == None:
        query = 'select count(*) from ' + tablename
    else:
        query = 'select count(*) from ' + tablename + ' where ' + condition
    return query


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


@classmethod
def block_header(cls, block, height):
    """Return the block header bytes"""
    deserializer = cls.DESERIALIZER(block)
    return deserializer.read_header(cls.BASIC_HEADER_SIZE)


def restore_vals(tmp_params, params):
    """Restore values and stderrs of parameters from a temporary dictionary."""
    for para_key in params:
        params[para_key].value, params[para_key].stderr = tmp_params[para_key]


def query_func(question, default=False):
    """
    Ask a string question
    No input defaults to "no" which results in False
    """
    valid = {'yes': True, 'y': True, 'no': False, 'n': False}
    if default is True:
        prompt = ' [Y/n]'
    else:
        prompt = ' [y/N]'
    while True:
        print('%s %s' % (question, prompt))
        choice = input().lower()
        if choice == '':
            return default
        elif choice in valid:
            return valid[choice]
        else:
            print('Please respond with y/n')


def get_first_end(pipes_selection):
    """
    Find an end node of one of the pipelines to build with the pipes from
    *pipes_selection*.

    Look for a node which occurs only once amongst the ends of the pipes of
    *pipes_selection*. If this node is match to the label 'A' ('B') *reverse* is
    set to True (False).

    Parameters
    ----------
    pipes_selection:
        Dataframe of the selected pipes (same load as the first pipe).

    Returns
    -------
    int
        Index of the dataframe *pipes_selection* referring to the end node.
    bool
        True (False) if the node is at the 'A' ('B') end.
    """
    points = list(pipes_selection['pB']) + list(pipes_selection['pA'])
    for idx, pipe in pipes_selection.iterrows():
        countA, countB = 0, 0
        for point in points:
            if point == pipe['pA']:
                countA += 1
            if point == pipe['pB']:
                countB += 1
        if countA == 1:
            reverse = False
            break
        if countB == 1:
            reverse = True
            break
    return idx, reverse


@staticmethod
def from_axis_angle(axis, angle, degrees=False):
    """Why would I need this?"""
    raise NotImplementedError('Quaternion.from_axis_angle')


def dict_list_2_matrix(dict_list, columns):
    """
        >>> dict_list_2_matrix([{'a': 1, 'b': 2}, {'a': 3, 'b': 4}], ('a', 'b'))
        [[1, 2], [3, 4]]

    :param dict_list: 字典列表
    :param columns: 字典的键
    """
    k = len(columns)
    n = len(dict_list)
    result = [([None] * k) for i in range(n)]
    for i in range(n):
        row = dict_list[i]
        for j in range(k):
            col = columns[j]
            if col in row:
                result[i][j] = row[col]
            else:
                result[i][j] = None
    return result


@classmethod
def build(cls, *, uri, display_name=None, parameters=None, tag=None):
    """Build a new Header from kwargs."""
    self = object.__new__(cls)
    self._uri = uri
    self._display_name = display_name
    self._parameters = parameters if parameters else {}
    if tag:
        self._parameters['tag'] = tag
    self._validate()
    return self


def is_encrypted(password):
    """ Returns true if password string is encrypted. """
    return password.startswith('{') and password.endswith('}')


def register_target_with_maintenance_window(WindowId=None, ResourceType=
    None, Targets=None, OwnerInformation=None, ClientToken=None):
    """
    Registers a target with a Maintenance Window.
    See also: AWS API Documentation

    :example: response = client.register_target_with_maintenance_window(
        WindowId='string',
        ResourceType='INSTANCE',
        Targets=[
            {
                'Key': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        OwnerInformation='string',
        ClientToken='string'
    )

    :type WindowId: string
    :param WindowId: [REQUIRED]
            The ID of the Maintenance Window the target should be registered with.

    :type ResourceType: string
    :param ResourceType: [REQUIRED]
            The type of target being registered with the Maintenance Window.

    :type Targets: list
    :param Targets: [REQUIRED]
            The targets (either instances or tags). Instances are specified using Key=instanceids,Values=instanceid1,instanceid2. Tags are specified using Key=tag name,Values=tag value.
            (dict) --An array of search criteria that targets instances using a Key,Value combination that you specify. Targets is required if you don't provide one or more instance IDs in the call.
            Key (string) --User-defined criteria for sending commands that target instances that meet the criteria. Key can be tag:Amazon EC2 tagor InstanceIds. For more information about how to send commands that target instances using Key,Value parameters, see Executing a Command Using Systems Manager Run Command .
            Values (list) --User-defined criteria that maps to Key. For example, if you specified tag:ServerRole, you could specify value:WebServer to execute a command on instances that include Amazon EC2 tags of ServerRole,WebServer. For more information about how to send commands that target instances using Key,Value parameters, see Executing a Command Using Systems Manager Run Command .
            (string) --

    :type OwnerInformation: string
    :param OwnerInformation: User-provided value that will be included in any CloudWatch events raised while running tasks for these targets in this Maintenance Window.

    :type ClientToken: string
    :param ClientToken: User-provided idempotency token.
            This field is autopopulated if not provided.

    :rtype: dict
    :return: {
        'WindowTargetId': 'string'
    }

    """
    pass


@staticmethod
def in_out_quad(progress):
    """.. image:: images/anim_in_out_quad.png
        """
    p = progress * 2
    if p < 1:
        return 0.5 * p * p
    p -= 1.0
    return -0.5 * (p * (p - 2.0) - 1.0)


def generate_dataset(language, *yaml_files):
    """Creates a Snips NLU dataset from YAML definition files

    Check :meth:`.Intent.from_yaml` and :meth:`.Entity.from_yaml` for the
    format of the YAML files.

    Args:
        language (str): language of the dataset (iso code)
        *yaml_files: list of intent and entity definition files in YAML format.

    Returns:
        None. The json dataset output is printed out on stdout.
    """
    from snips_nlu.dataset import Dataset
    from snips_nlu.common.utils import unicode_string, json_string
    language = unicode_string(language)
    dataset = Dataset.from_yaml_files(language, list(yaml_files))
    print(json_string(dataset.json, indent=2, sort_keys=True))


def find_all(a_str, sub):
    """
    String finder iterator
    """
    start = 0
    while True:
        start = a_str.find(sub, start)
        if start == -1:
            return
        yield start
        start += len(sub)


@staticmethod
def to_rankine(romer):
    """ Convert romer to rankine """
    return (romer - 7.5) * 24 / 7 + 491.67


def partition_text(sent, max_length):
    """
    partitions a tokenized sent in chunks of max possible
    length that is less than `max_length`. `max_length` can
    be altered by a coroutine using generator.send()
    """
    acc, comax_length = '', None
    sent.reverse()
    while sent:
        next_word = sent.pop()
        if len(acc) + len(next_word) < (comax_length or max_length):
            acc += next_word + ' '
        else:
            comax_length = yield acc.strip()
            acc = next_word + ' '
    else:
        yield acc.strip()


def get_descriptor_output(descriptor, key, handler=None):
    """Get the descriptor output and handle incorrect UTF-8 encoding of subprocess logs.

    In case an process contains valid UTF-8 lines as well as invalid lines, we want to preserve
    the valid and remove the invalid ones.
    To do this we need to get each line and check for an UnicodeDecodeError.
    """
    line = 'stub'
    lines = ''
    while line != '':
        try:
            line = descriptor.readline()
            lines += line
        except UnicodeDecodeError:
            error_msg = 'Error while decoding output of process {}'.format(key)
            if handler:
                handler.logger.error('{} with command {}'.format(error_msg,
                    handler.queue[key]['command']))
            lines += error_msg + '\n'
    return lines.replace('\n', '\n    ')


def parseVariable(toks):
    """Called by the parser created by :func:`makeParser`. Parses a variable
    identifier, returning an integer ID.
    """
    return toks[1]


def fatal_request_error(err=None):
    """Give up retrying if the error code is in fatal range.

    Returns:
        bool: True if to giveup on backing off, False it to continue.
    """
    if not err or not err.response:
        return False
    if err.response.status_code == 403:
        return True
    return not 400 <= err.response.status_code <= 600


def __call__(tree):
    """Transform the given LXML tree.
        """


def decorate_menu_item(menu_item, colors):
    """ Return menu item decorated. """
    key_text = u'{lb}{inp_key}{rb}'.format(lb=colors['lowlight'](u'['), rb=
        colors['lowlight'](u']'), inp_key=colors['highlight'](menu_item.
        inp_key))
    if menu_item.text.startswith(menu_item.inp_key):
        return menu_item.text.replace(menu_item.inp_key, key_text, 1)
    return u'{key_text} {menu_text}'.format(key_text=key_text, menu_text=
        menu_item.text)


def in_progress(seq, msg='Progress: [%(processed)d / %(total)d]', length=
    None, close=True):
    """ Iterate over sequence, yielding item with progress widget displayed.
        This is useful if you need to precess sequence of items with some
        time consuming operations

        .. note::

            This works only in Jupyter Notebook

        .. note::

            This function requires *ipywidgets* package to be installed

        :param seq: sequence to iterate on.
        :param str msg: (optional) message template to display.
                        Following variables could be used in this template:
                            - processed
                            - total
                            - time_total
                            - time_per_item
        :param int length: (optional) if seq is generator, or it is not
                           possible to apply 'len(seq)' function to 'seq',
                           then this argument is required and it's value will
                           be used as total number of items in seq.

        Example example::

            import time
            for i in in_progress(range(10)):
                time.sleep(1)
    """
    from IPython.display import display
    from ipywidgets import IntProgress
    import time
    if length is None:
        length = len(seq)
    start_time = time.time()
    progress = IntProgress(value=0, min=0, max=length, description=msg % {
        'processed': 0, 'total': length, 'time_total': 0.0, 'time_per_item':
        0.0, 'time_remaining': 0.0})
    display(progress)
    for i, item in enumerate(seq, 1):
        progress.value = i
        yield item
        i_end_time = time.time()
        progress.description = msg % {'processed': i, 'total': length,
            'time_total': i_end_time - start_time, 'time_per_item': (
            i_end_time - start_time) / i, 'time_remaining': (i_end_time -
            start_time) / i * (length - i)}
    if close:
        progress.close()


def grab_publication_year(g):
    """Get publication year from proxychimp.Guts"""
    victim = g.pull_section('Publication')
    yr = []
    for p in victim:
        for ln in p:
            if 'Published_Date_or_Year' in ln:
                ln_split = ln.split(':')
                yr.append(int(ln_split[-1]))
    return yr


def _add_validation_res_full(table):
    """
    Utility that adds a new column to the table.
    Adds a new column with the 'full res' (i.e. seq_id + ins_code).

    :param table: pandas DataFrame object
    :return: returns a modified pandas DataFrame
    """
    if 'validation_resnum' in table and 'validation_icode' in table:
        table['validation_resnum_full'] = table['validation_resnum'] + table[
            'validation_icode'].str.replace('?', '')
    return table


@staticmethod
def p_memory_segment_memory_type(p):
    """memory_segment_memory_type : RAM
                                      | EEPROM
                                      | EPROM
                                      | ROM
                                      | REGISTER
                                      | FLASH"""
    p[0] = p[1]


def bv_concat(a, b):
    """
    Concatenation of two SMT2 expressions
    """
    return '(concat {} {})'.format(a, b)


@classmethod
def check_schema(cls, schema, namespaces=None):
    """
        Validates the given schema against the XSD meta-schema (:attr:`meta_schema`).

        :param schema: the schema instance that has to be validated.
        :param namespaces: is an optional mapping from namespace prefix to URI.

        :raises: :exc:`XMLSchemaValidationError` if the schema is invalid.
        """
    if not cls.meta_schema.maps.types:
        cls.meta_schema.maps.build()
    for error in cls.meta_schema.iter_errors(schema, namespaces=namespaces):
        raise error


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

        :param SsoChangePolicyDetails val:
        :rtype: EventDetails
        """
    return cls('sso_change_policy_details', val)


@classmethod
def from_unsupported_dataobj_in_rstr_list(cls, allowed):
    """
        Compile time error. DO in restriction can only be combined with None type.
        """
    return cls(
        "DataObject in restriction list '%s' only valid with type(None)." %
        allowed)


@staticmethod
def var_unset(session, name):
    """
        Unsets the given variable
        """
    name = name.strip()
    try:
        session.unset(name)
    except KeyError:
        session.write_line('Unknown variable: {0}', name)
        return False
    else:
        session.write_line('Variable {0} unset.', name)
    return None


def unroll_deg(deg):
    """ Return *deg* in the range [0, 360) """
    return deg % 360


@staticmethod
def output_calc_width(period, duty_cycle):
    """
		Calculate width value from period and duty cycle.
		:param period: Period
		:param duty_cycle: Duty Cycle (0 <= duty_cycle <= 100)
		:return: Width value
		"""
    assert 0 < duty_cycle < 100
    return int(float(period) * float(duty_cycle) / 100.0)


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

        :param LegalHoldsReleaseAHoldDetails val:
        :rtype: EventDetails
        """
    return cls('legal_holds_release_a_hold_details', val)


def true_if_all_false_filter(*value):
    """
    Returns true if all values have a non-'true-ish' value.

    Args:
        *value: list of values

    Returns: 'true' if all values have a non-'true-ish' value
    """
    for v in value:
        if v:
            return False
    return True


def primes(imax):
    """
    Returns prime numbers up to imax.

    Parameters
    ----------
    imax: int
        The number of primes to return. This should be less or equal to 10000.

    Returns
    -------
    result: list
        The list of prime numbers.
    """
    p = list(range(10000))
    result = []
    k = 0
    n = 2
    if imax > 10000:
        raise ValueError('imax should be <= 10000')
    while len(result) < imax:
        i = 0
        while i < k and n % p[i] != 0:
            i = i + 1
        if i == k:
            p[k] = n
            k = k + 1
            result.append(n)
            if k > 10000:
                break
        n = n + 1
    return result


def select_all_toggle(invert: bool=False):
    """Select or deselect all NLA-Strips

    :param invert: Invert
    :type invert: bool
    """
    pass


def render(*args, **kwargs):
    """Use the view configuration parameter 'IHTTPRenderer' to invoke the
        view plugin and apply IHTTPRenderer.render() method with ``request``,
        ``c``, ``args`` and ``kwargs``.
        """


def CDLTAKURI(df):
    """
    Takuri (Dragonfly Doji with very long lower shadow)
    """


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

        :param CameraUploadsPolicyChangedDetails val:
        :rtype: EventDetails
        """
    return cls('camera_uploads_policy_changed_details', val)


def is_aware(value):
    """
    Determines if a given datetime.datetime is aware.

    The logic is described in Python's docs:
    http://docs.python.org/library/datetime.html#datetime.tzinfo
    """
    return value.tzinfo is not None and value.tzinfo.utcoffset(value
        ) is not None


def get_google_images_search_url(term):
    """
    Returns the Google Images search URL for the specified term
    Note that no escaping or character cleansing is performed
    """
    return 'https://www.google.com/search?q={0}&tbm=isch'.format(term)


def stabilize_2d_rotation_add():
    """Add selected tracks to 2D rotation stabilization

    """
    pass


def el(tag_type, *content):
    """
    Returns a list of strings that represents an HTML element.

    If the first argument passed to *content is a dict, then the dict
    is unpacked into attribute pairs for the element.

    >>> el('div', {'class' : 'navbar'}, "This is my Navbar!")
    ['
', 'This is my Navbar!', '
']

    """
    result = []
    try:
        if isinstance(content[0], dict):
            attrs_dict, content = content[0], content[1:]
            attrs_pairs = []
            for key in attrs_dict:
                attrs_pairs.append('%s="%s"' % (key, attrs_dict[key]))
            attrs_string = ' '.join(attrs_pairs)
            open_tag = '<%s %s>' % (tag_type, attrs_string)
        else:
            open_tag = '<%s>' % tag_type
    except IndexError:
        open_tag = '<%s>' % tag_type
    close_tag = '</%s>' % tag_type
    result.append(open_tag)
    for item in content:
        result.append(item)
    result.append(close_tag)
    return result


def delete_instance(InstanceId=None, DeleteElasticIp=None, DeleteVolumes=None):
    """
    Deletes a specified instance, which terminates the associated Amazon EC2 instance. You must stop an instance before you can delete it.
    For more information, see Deleting Instances .
    See also: AWS API Documentation

    :example: response = client.delete_instance(
        InstanceId='string',
        DeleteElasticIp=True|False,
        DeleteVolumes=True|False
    )

    :type InstanceId: string
    :param InstanceId: [REQUIRED]
            The instance ID.

    :type DeleteElasticIp: boolean
    :param DeleteElasticIp: Whether to delete the instance Elastic IP address.

    :type DeleteVolumes: boolean
    :param DeleteVolumes: Whether to delete the instance's Amazon EBS volumes.

    """
    pass


def nanmean(x):
    """ Mean of array with NaN """
    import numpy as N
    sum = N.nansum(x)
    n = N.sum(~N.isnan(x))
    if n > 0:
        mean = sum / n
    else:
        mean = float('NaN')
    return mean


@classmethod
def from_file(cls, target, *args, **kwargs):
    """Create a new GpgInfo object from the given file.

        See GpgInfo.from_sequence.
        """
    with open(target, 'rb') as target_file:
        return cls.from_sequence(target_file, *args, **kwargs)


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


@classmethod
def ParseOptions(cls, options, configuration_object):
    """Parses and validates options.

    Args:
      options (argparse.Namespace): parser options.
      configuration_object (object): object to be configured by the argument
          helper.

    Raises:
      BadConfigObject: when the configuration object is of the wrong type.
      BadConfigOption: when a configuration parameter fails validation.
    """


def docstrings(code, to_double=True):
    """
	Converts between 3x' and 3x" as long as only one of them occurs in the file.
	"""
    single, double = "'''", '"""'
    if single in code and double in code:
        print('skipping docstrings because both %s and %s appear' % (single,
            double))
        return code
    if to_double:
        code = code.replace(single, double)
    else:
        code = code.replace(double, single)
    return code


def _parse_arg(s):
    """Parse a number or string."""
    try:
        return int(s)
    except ValueError:
        pass
    try:
        return float(s)
    except ValueError:
        pass
    return s


def check_consistency_with_rm(tx, source, target, typing_label):
    """Check consistency of typing after removeal of tagged nodes."""
    consistent = True
    query = 'MATCH (G:{})\n'.format(source) + "WHERE G.id = '{}'\n".format(
        source) + """OPTIONAL MATCH (h_i:{})
""".format(target
        ) + 'WHERE (G)<-[:{}*1..]-(h_i})-[:{}*1..]->(G)\n'.format(typing_label,
        typing_label)


@classmethod
def map_default_node(cls, node):
    """Maps a node to a dictionary"""
    return {'data': {'id': cls.get_id(node), 'label': cls.get_label(node),
        'type': list(node._labels)[0], 'name': node['name']}}


def receive_leave_group(group_state: 'GroupState'):
    """
    Received IGMP Leave packet regarding group GroupState
    """
    group_state.group_state_logger.debug(
        'NonQuerier CheckingMembership: receive_leave_group')
    return


def teardown_databases109(old_config, verbosity, parallel=0, keepdb=False):
    """
    Destroy all the non-mirror databases.
    """
    for connection, old_name, destroy in old_config:
        if destroy:
            if parallel > 1:
                for index in range(parallel):
                    connection.creation.destroy_test_db(number=index + 1,
                        verbosity=verbosity, keepdb=keepdb)
            connection.creation.destroy_test_db(old_name, verbosity, keepdb)


@staticmethod
@property
def interfaceInfo():
    """Information object of the interface for this ConnectionHandler
        """
    raise NotImplementedError


def commit():
    """Commit the current transaction."""


@classmethod
def and_(cls, constraints):
    """ Factory for a group AND """
    return cls._factory(constraints, 'AND')


def truncate(original: str, length: int) ->str:
    """
    Provide an elided version of the string for which the last three
    characters are dots if the original string does not fit within the
    specified length.

    Args:
        original: string to elide
        length: constrain the elided string to this
    """
    s = original[:length - 3] + '...' if len(original) > length else original
    return s


def validate(action, value_if_allowed, text):
    """
    This function allows only numbers to be enter in a Tk Entry.

    :param action: Type of action (1=insert, 0=delete, -1 for others)
    :type action: string
    :param value_if_allowed: value of the entry if the edit is allowed
    :type value_if_allowed: string
    :param text: the text string being inserted or deleted, if any
    :type text: string
    :return: Returns true if text entered is number else false
    :rtype: bool
    """
    if action == '1':
        if text in '0123456789':
            try:
                int(value_if_allowed)
                return True
            except ValueError:
                return False
        else:
            return False
    else:
        return True


def isStrange(pid):
    """Determine if the PID is that of an s/sbar"""
    return abs(pid) == 3


def is_datetime_naive(dt):
    """
    This method returns true if the datetime is naive else returns false
    """
    if dt.tzinfo is None:
        return True
    else:
        return False


def packbits_decode(encoded, out=None):
    """Decompress PackBits encoded byte string.

    >>> packbits_decode(b'\\x80\\x80')  # NOP
    b''
    >>> packbits_decode(b'\\x02123')
    b'123'
    >>> packbits_decode(
    ...   b'\\xfe\\xaa\\x02\\x80\\x00\\x2a\\xfd\\xaa\\x03\\x80\\x00\\x2a\\x22\\xf7\\xaa')[:-4]
    b'\\xaa\\xaa\\xaa\\x80\\x00*\\xaa\\xaa\\xaa\\xaa\\x80\\x00*"\\xaa\\xaa\\xaa\\xaa\\xaa\\xaa'

    """
    out = []
    out_extend = out.extend
    i = 0
    try:
        while True:
            n = ord(encoded[i:i + 1]) + 1
            i += 1
            if n > 129:
                out_extend(encoded[i:i + 1] * (258 - n))
                i += 1
            elif n < 129:
                out_extend(encoded[i:i + n])
                i += n
    except TypeError:
        pass
    return bytes(out)


def f_eq_zero(x, prec, ref=1.0):
    """checks whether x is zero with precision prec*(ref+1.) """
    return abs(x) <= prec * (abs(ref) + 1.0)


@staticmethod
def _get_opcode_value_from_flags(flags: int) ->int:
    """
        Retrieve the opcode value from flags.

        :param flags: an integer representing the flags of a dns message
        :return: value of the opcode field as int
        """
    return (flags & int.from_bytes(b'\x00\x00x\x00', 'big')) >> 11


def most_common(iterable):
    """
    >>> most_common([1, 2, 2, 3, 4, 4, 4, 4])
    4
    >>> most_common(list('Anthony'))
    'n'
    >>> most_common('Stephen')
    'e'

    Exceptionally quick! Benchmark at 12.1 us
    :param iterable:
    :return:
    """
    from collections import Counter
    data = Counter(iterable)
    return data.most_common(1)[0][0]


def provides_facts():
    """
    Returns a dictionary keyed on the facts provided by this module. The value
    of each key is the doc string describing the fact.
    """
    return {'switch_style':
        "A string which indicates the Ethernet switching syntax style supported by the device. Possible values are: 'BRIDGE_DOMAIN', 'VLAN', 'VLAN_L2NG', or 'NONE'."
        }


@classmethod
def update_attributes_map(klass):
    """
        Defines keys and default values for non-generic attributes.
        """
    return {}


def cursor3d():
    """Set the location of the 3D cursor

    """
    pass


@classmethod
def parse(cls, path, *parsers, **kw):
    """
        Read the text from the supplied path and parse it into a document
        using the supplied parsers.
        """
    encoding = kw.pop('encoding', 'utf-8')
    with open(path, encoding=encoding) as source:
        text = source.read()
    document = cls(text, path)
    for parser in parsers:
        for region in parser(document):
            document.add(region)
    return document


def handle_message(sender, message):
    """
    Handles message events from the AlarmDecoder.
    """
    print(sender, message.raw)


def CBA_calc(classes, table, TOP, P):
    """
    Calculate CBA (Class balance accuracy).

    :param classes: classes
    :type classes : list
    :param table: input matrix
    :type table : dict
    :param TOP: test outcome positive
    :type TOP : dict
    :param P: condition positive
    :type P : dict
    :return: CBA as float
    """
    try:
        result = 0
        class_number = len(classes)
        for i in classes:
            result += table[i][i] / max(TOP[i], P[i])
        return result / class_number
    except Exception:
        return 'None'


def scale_outline(ai_outline_list, ai_coef):
    """ apply the scale coefficient to a list of outlines
  """
    lx, kx, ly, ky = ai_coef
    r_outline_list = []
    for outline in ai_outline_list:
        outline_type = outline[0]
        if outline_type == 'graphic_lines' or outline_type == 'overlay_lines':
            lines = outline[1]
            new_lines = []
            for line in lines:
                new_line = []
                for i in range(len(line) / 2):
                    new_line.append(line[2 * i] * lx + kx)
                    new_line.append(line[2 * i + 1] * ly + ky)
                new_lines.append(tuple(new_line))
            r_outline_list.append((outline_type, tuple(new_lines), outline[
                2], outline[3]))
        elif outline_type == 'graphic_polygon' or outline_type == 'overlay_polygon':
            points = outline[1]
            new_points = []
            for i in range(len(points) / 2):
                new_points.append(points[2 * i] * lx + kx)
                new_points.append(points[2 * i + 1] * ly + ky)
            r_outline_list.append((outline_type, tuple(new_points), outline
                [2], outline[3], outline[4]))
    return r_outline_list


@classmethod
def mimetype(cls):
    """Return most common media type for format."""
    return cls.get_class().Mimetypes[0]


def check_df_len(df, criteria, num=5):
    """
    Verify that df has > than num genomes
    """
    if len(df) > num:
        return True
    else:
        print('Filtering based on {} resulted in less than 5 genomes.')
        return False


def _set_environment_parameters(user, password, account, environment):
    """Configure the environment parameters into global configuration.

    Set the user, password and account into globals configuration.
    These variables are going to be used as the default parameters for the environment.

    :param user: the user used for authentication.
    :param password: the password used for authentication.
    :param account: user's default account.
    :param environment: the environment that is going to be configured.
    """
    globals.environment_config[environment]['user'] = user
    globals.environment_config[environment]['password'] = password
    globals.environment_config[environment]['account'] = account


def _get_feature_names(estimator):
    """
    Attempt to extract feature names based on a given estimator
    """
    if hasattr(estimator, 'classes_'):
        return estimator.classes_
    elif hasattr(estimator, 'get_feature_names'):
        return estimator.get_feature_names()
    return None


@staticmethod
def _get_result_dict(code: int, message: str) ->dict:
    """
        Return dict like {'code': 0, 'message': 'OK}
        :param code:
        :param message:
        :return:
        """
    return {'code': code, 'message': message}


def annotate_base_config(obj, override_config, base_config):
    """
    Adds attributes prefixed with __base__<name> with values from the
    base configuration for every attribute that has been overriden.
    """
    for name in override_config.keys():
        value = getattr(base_config, name, None)
        if value:
            setattr(obj, '__base__' + name, value)


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 get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'mongo_indexes': {'index_updated': [('_updated', 1)],
        'index_name': [('name', 1)]}, 'schema': {'schema_version': {'type':
        'integer', 'default': 1}, 'imported_from': {'schema_version': 1,
        'title': 'Imported from', 'comment':
        'Item importation source (alignak-backend-import, ...)', 'type':
        'string', 'default': 'unknown'}, 'definition_order': {
        'schema_version': 1, 'title': 'Definition order', 'comment':
        'Priority level if several elements have the same name', 'type':
        'integer', 'default': 100}, 'name': {'schema_version': 1, 'title':
        'Services group name', 'comment': 'Unique services group name',
        'type': 'string', 'required': True, 'empty': False, 'unique': True},
        'alias': {'schema_version': 1, 'title': 'Alias', 'comment':
        'Element friendly name used by the Web User Interface.', 'type':
        'string', 'default': ''}, 'notes': {'schema_version': 1, 'title':
        'Notes', 'comment':
        'Element notes. Free text to store element information.', 'type':
        'string', 'default': ''}, 'notes_url': {'schema_version': 1,
        'title': 'Notes URL', 'comment':
        'Element notes URL. Displayed in the Web UI as some URL to be navigatesd. Note that a very specific text format must be used for this field, see the Web UI documentation.'
        , 'type': 'string', 'default': ''}, 'action_url': {'schema_version':
        1, 'title': 'Actions URL', 'comment':
        'Element actions URL. Displayed in the Web UI as some available actions. Note that a very specific text format must be used for this field, see the Web UI documentation.'
        , 'type': 'string', 'default': ''}, 'servicegroups': {
        'schema_version': 1, 'title': 'Groups', 'comment':
        'List of the groups of this group', 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'servicegroup',
        'embeddable': True}}, 'default': []}, 'services': {'schema_version':
        1, 'title': 'Members', 'comment':
        'List of the members of this group', 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'service',
        'embeddable': True}}, 'default': []}, '_level': {'schema_version':
        1, 'title': 'Level', 'comment': 'Level in the hierarchy', 'type':
        'integer', 'default': 0}, '_parent': {'schema_version': 1, 'title':
        'Parent', 'comment': 'Immediate parent in the hierarchy', 'type':
        'objectid', 'data_relation': {'resource': 'servicegroup',
        'embeddable': True}, 'nullable': True, 'default': None},
        '_tree_parents': {'schema_version': 1, 'title': 'Parents',
        'comment': 'List of parents in the hierarchy', 'type': 'list',
        'schema': {'type': 'objectid', 'data_relation': {'resource':
        'servicegroup', 'embeddable': True}}, 'default': []}, '_realm': {
        'schema_version': 1, 'title': 'Realm', 'comment':
        'Realm this element belongs to.', 'type': 'objectid',
        'data_relation': {'resource': 'realm', 'embeddable': True},
        'required': True}, '_sub_realm': {'schema_version': 1, 'title':
        'Sub-realms', 'comment':
        'Is this element visible in the sub-realms of its realm?', 'type':
        'boolean', 'default': True}, '_users_read': {'schema_version': 1,
        'type': 'list', 'schema': {'type': 'objectid', 'data_relation': {
        'resource': 'user', 'embeddable': True}}}, '_users_update': {
        'schema_version': 1, 'type': 'list', 'schema': {'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True}}},
        '_users_delete': {'schema_version': 1, 'type': 'list', 'schema': {
        'type': 'objectid', 'data_relation': {'resource': 'user',
        'embeddable': True}}}}, 'schema_deleted': {}}


def __repr__(A):
    """For `print` and `pprint`"""
    return A.to_str()


def extract_mark_posting(posting, config):
    """
    Extract mark from posting, if any.

    Args:
        posting: posting.
        config: A configuration string in JSON format given in source file.
    Returns:
        string of mark or False.
    """
    for alias in config['aliases_after']:
        if hasattr(posting, 'meta') and posting.meta and alias in posting.meta:
            return posting.meta[alias]
    return False


def has_ltsh_table(tt):
    """Tests for the presence of a LTSH table in a TrueType font."""
    return 'LTSH' in tt


def append_lines(lines, wrap, buf):
    """Append lines to the buffer. If the first line can be appended to the last
    line of the buf without exceeding wrap characters, the two lines are merged.
    Args:
        lines: an iterable of lines to append
        wrap:  maximum number of characters per line. 0 or negative wrap means
               no limit.
        buf:   an iterable of lines to append to"""
    if not lines:
        return
    if not buf or wrap > 0 and len(buf[-1]) + len(lines[0]) > wrap:
        buf += lines
    else:
        buf[-1] += lines[0]
        buf += lines[1:]


def workflow():
    """ Returns a :py:class:`hurry.workflow.workflow.Workflow` instance
        """


def _PerModeSmall36(x):
    """Takes Numeric Code and returns String API code

    Input Values: 1:"Totals", 2:"PerGame", 3:"Per36"

    Used in:

    """
    measure = {(1): 'Totals', (2): 'PerGame', (3): 'Per36'}
    try:
        return measure[x]
    except:
        raise ValueError('Please enter a number between 1 and ' + str(len(
            measure)))


@staticmethod
def open_file(title='Open File', start_directory=None, filters=None):
    """
        Function that shows open file DCC native dialog
        :param title: str
        :param start_directory: str
        :param filters: str
        :return: str
        """
    raise NotImplementedError('open_file() function is not implemented')


def model(settings) ->str:
    """
    Return path to model specified by settings.

    Parameters
    ----------
    settings : typing.Dict
        YAML parsed to dict

    Returns
    -------
    str:
        "/path/to/model"

    """
    return '"' + settings['model'] + '"'


def post_install(context):
    """Post install script"""


def run_length_decode(in_array):
    """A function to run length decode an int array.
    :param in_array: the input array of integers
    :return the decoded array"""
    switch = False
    out_array = []
    for item in in_array:
        if switch == False:
            this_item = item
            switch = True
        else:
            switch = False
            out_array.extend([this_item] * int(item))
    return out_array


@classmethod
def unpack_scalar(cls, dataset, data):
    """
        Given a dataset object and data in the appropriate format for
        the interface, return a simple scalar.
        """
    if len(data.data_vars) == 1 and len(data[dataset.vdims[0].name].shape
        ) == 0:
        return data[dataset.vdims[0].name].item()
    return data


def _isnumber(obj):
    """Test is object is a number (copied from pmisc module to avoid import loops)."""
    return obj is not None and not isinstance(obj, bool) and isinstance(obj,
        (int, float, complex))


def get_endpoint_path(api, response):
    """ Return the section of the URL from 'api/v2' to the end. """
    return response.request.url.split(api.api_prefix)[-1]


def gen_function_parens_adjust(mapping_key, node):
    """If we can avoid the outer parenthesis
    of a generator function, set the node key to
    'call_generator' and the caller will do the default
    action on that. Otherwise we do nothing.
    """
    if mapping_key.kind != 'CALL_FUNCTION_1':
        return
    args_node = node[-2]
    if args_node == 'pos_arg':
        assert args_node[0] == 'expr'
        n = args_node[0][0]
        if n == 'generator_exp':
            node.kind = 'call_generator'
        pass
    return


def from_one_file(file_location):
    """read a file piece by piece.
    Default chunk size 1024 * 16 bytes"""
    with open(file_location, 'rb') as entry:
        for chunk in iter(lambda : entry.read(1024 * 16), b''):
            yield chunk


def proc(request):
    """
    Place the ProctorGroups 'proc' object in every template context.

    This makes using Proctor test groups in templates very convenient.

    Dependent on the Proctor middleware.

        {{ proc.buttoncolortst.payload|default_if_none:"..." }}

        {% if proc.buttoncolortst.group == 'green' %}
    """
    return {'proc': request.proc} if hasattr(request, 'proc') else {}


def ballot_two(ranking):
    """Ballot for the voter's second most-liked candidate.

    Parameters
    ----------
    ranking : str
        A ranking.

    Returns
    -------
    str
        The second candidate.

    Examples
    --------
        >>> ballot_two('abc')
        'b'
    """
    return ranking[1]


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

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


@classmethod
def deserialize(cls, serializer, s_state):
    """
        Serializes the instance using the provided serializer.

        :type  serializer: :class:`SpiffWorkflow.serializer.base.Serializer`
        :param serializer: The serializer to use.
        :rtype:  object
        :returns: The serialized object.
        """
    return serializer.deserialize_operator(s_state)


def truncate_window_length(universe_dict):
    """Chopping the length of all of the DataFrames to ensure
    that they are all between the same dates.

    :param universe_dict:           The dictionary of time series
    :type  universe_dict:           dict

    :return:                        the dictionary of truncated time series
    :rtype:                         dict
    """
    start_date_arr = []
    end_date_arr = []
    for df_name in universe_dict:
        start_date_arr.append(universe_dict[df_name].index[0])
        end_date_arr.append(universe_dict[df_name].index[-1])
    for df_name in universe_dict:
        df = universe_dict[df_name]
        universe_dict[df_name] = df.loc[(df.index <= min(end_date_arr)) & (
            df.index >= max(start_date_arr))]
    return universe_dict


def copyfileobj(fsrc, fdst, total, length=16 * 1024):
    """Copy data from file-like object fsrc to file-like object fdst
	This is like shutil.copyfileobj but with a progressbar.
	"""
    from tqdm import tqdm
    with tqdm(unit='bytes', total=total, unit_scale=True) as pbar:
        while 1:
            buf = fsrc.read(length)
            if not buf:
                break
            fdst.write(buf)
            pbar.update(len(buf))


def _deref(ref):
    """Remove workflows prefix."""
    assert ref.startswith('workflows/')
    return ref[len('workflows/'):]


def getIpv4(addr):
    """ Get IPv4 address via parameter addr """
    return '.'.join(map(str, addr))


def overlay(image1, image2):
    """
    Superimposes two images on top of each other using the Overlay algorithm

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_overlay(image2.im))


def describe_load_balancer_policies(LoadBalancerName=None, PolicyNames=None):
    """
    Describes the specified policies.
    If you specify a load balancer name, the action returns the descriptions of all policies created for the load balancer. If you specify a policy name associated with your load balancer, the action returns the description of that policy. If you don't specify a load balancer name, the action returns descriptions of the specified sample policies, or descriptions of all sample policies. The names of the sample policies have the ELBSample- prefix.
    See also: AWS API Documentation

    Examples
    This example describes the specified policy associated with the specified load balancer.
    Expected Output:

    :example: response = client.describe_load_balancer_policies(
        LoadBalancerName='string',
        PolicyNames=[
            'string',
        ]
    )

    :type LoadBalancerName: string
    :param LoadBalancerName: The name of the load balancer.

    :type PolicyNames: list
    :param PolicyNames: The names of the policies.
            (string) --

    :rtype: dict
    :return: {
        'PolicyDescriptions': [
            {
                'PolicyName': 'string',
                'PolicyTypeName': 'string',
                'PolicyAttributeDescriptions': [
                    {
                        'AttributeName': 'string',
                        'AttributeValue': 'string'
                    },
                ]
            },
        ]
    }

    """
    pass


def __len__():
    """Returns the length of the data.
        """


def insetRect(rect, dx, dy):
    """Inset the rectangle by dx, dy on all sides."""
    xMin, yMin, xMax, yMax = rect
    return xMin + dx, yMin + dy, xMax - dx, yMax - dy


def spec_updater(specs, new):
    """
    Add element to the new dictionary to the specs dictionary.
    Update value if the key already exist.

    Parameters
    ----------
    specs: specification that will be modified
    new: dictionary of new specification
    """
    for key, spec in specs.items():
        if new.get(key) is not None:
            spec.update(new[key])


def get_quantum_numbers():
    """Return a set of iterators over the quantum numbers for the
        basis."""


def move_slide(presentation, old_index, new_index):
    """Move a slide's index number."""
    xml_slides = presentation.slides._sldIdLst
    slides = list(xml_slides)
    xml_slides.remove(slides[old_index])
    xml_slides.insert(new_index, slides[old_index])


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 += f"-{pieces['distance']:d}-g{pieces['short']}"
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def functionParams(args, vars):
    """
    Build a dictionary of var/value from :param: args.
    Parameters can be either named or unnamed. In the latter case, their
    name is taken fron :param: vars.
    """
    params = {}
    index = 1
    for var in vars:
        value = args.get(var)
        if value is None:
            value = args.get(str(index))
            if value is None:
                value = ''
            else:
                index += 1
        params[var] = value
    return params


def _named_children_with_duplicates(module):
    """Version of torch.nn.Module.named_children() that includes duplicate modules"""
    for name, module in module._modules.items():
        if module is not None:
            yield name, module


@staticmethod
def add_to_queue_file(root_name, file_name):
    """
        Add item to queue_file.

        Arguments:
        root_name - Name to add
        file_name - File to append to

        Return:
        Name removed from the queue.
        """
    is_present = False
    try:
        with open(file_name, 'r') as read:
            is_present = bool(root_name in read.read())
    except FileNotFoundError:
        pass
    if not is_present:
        with open(file_name, 'a') as append:
            append.write('{0}\n'.format(root_name))
    else:
        pass


def time_to_seconds(time):
    """Convert a datetime.time to seconds since midnight"""
    if time is None:
        return None
    return 3600 * time.hour + 60 * time.minute + time.second


def jd2tjc(jd):
    """
    Compute the time in Julian centuries since 2000.0.

    Args:
      jd (double):  Julian day (days).

    Returns:
      double:  tjc: Time in Julian centuries since 2000.0 (UT).

    """
    return (jd - 2451545.0) / 36525


def move_language_preference(apps, schema_editor):
    """Move language from parameters to User model."""
    UserParameter = apps.get_model('lib', 'UserParameter')
    for uparam in UserParameter.objects.filter(name='core.LANG'):
        uparam.user.language = uparam.value
        uparam.user.save()
        uparam.delete()


def check_con(con):
    """Raise a connection error if this connection is down.
    """
    if not con:
        return False
    event = con.api('status')
    return bool(con.connected()) and bool(event)


def find_next_path_down(current_path, path_to_reduce, separator):
    """
    Manipulate ``path_to_reduce`` so that it only contains one more level of
    detail than ``current_path``.

    :param current_path: The path used to determine the current level
    :type current_path: :class:`basestring`
    :param path_to_reduce: The path to find the next level down
    :type path_to_reduce: :class:`basestring`
    :param separator: The string used to separate the parts of path
    :type separator: :class:`basestring`
    :return: The path one level deeper than that of ``current_path``
    :rtype: :class:`unicode`

    """
    current_level = current_path.count(separator)
    next_level = current_level + 1
    return u'%s%s' % (separator.join(path_to_reduce.split(separator,
        next_level)[:next_level]), separator)


def dbh_checklist_4_chf(path, contenttype, extension, roottag, nsurl):
    """ Generic Checklist Handler - Returns checlist for Checklist Files """
    if (extension.lower() == 'chf' or extension.lower() == 'plf'
        ) and nsurl.startswith('http://limatix.org'):
        return 'db_limatix_qautils_viewer'
    else:
        return False


def convert_energy(Energy, Input_unit, Output_unit):
    """Description: ocnverts energy from Input_unit to Output_unit.
    Input  :- Energy to be converted
    		- Input unit. Can be:
    		'erg'   - ergs
    		'J'     - Jouls
    		'Hz'    - Frequency [1/s]
    		'A','Ang'- Wavelength [Ang]
    		'cm'    - Wavelength [cm]
    		'nm'    - Wavelength [nm]
    		'm'     - Wavelength [m]
    		'eV'    - Electron volts [h nu/q]
    		'keV'   - kilo Electron volts [h nu/q]
    		'MeV'   - Mega Electron volts [h nu/q]
    		'GeV'   - Giga Electron volts [h nu/q]
    		'T'     - Temperature [K]
    		'me'    - Electron mass [E/m_e]
    		'mp'    - Proton mass [E/m_p]
    		'cal'   - calorie (4.184 J)
    		'Btu'   - (1.055x10^3 J)
    		'kWh'   - kilowatt-hour (3.6x10^6 J)
    		'TNT'   - one ton of TNT (4.2x10^9 J)
    		'gr'    - Energy equivalent of 1 gram of matter (9x10^13 J)
    		- requested output unit. One of the above.
    Output :- Energy in output system
     Tested : ?
         By : Maayane T. Soumagnac Nov 2016
        URL :
     Example:
     Reliable:  """
    Erg2Erg = 1.0
    Erg2J = 1e-07
    Erg2eV = 624150000000.0
    Erg2me = 1221400.0
    Erg2mp = 665.214577
    Erg2cal = Erg2J / 4.184
    Erg2Btu = Erg2J / 1055.0
    Erg2kWh = Erg2J / 3600000.0
    Erg2TNT = Erg2J / 4200000000.0
    relation = 'inv'
    if Input_unit.lower() == 'erg':
        ConvFactor = Erg2Erg
    elif Input_unit.lower() == 'j':
        ConvFactor = Erg2J
    """
    elif Input_unit.lower()=='cm':
        relation='inv'
        ConvFactor=Erg2A*1e-8
    elif Input_unit.lower()=='nm':
        relation='inv'
        ConvFactor=Erg2A*1e-4
    #elif Input_unit.lower()=='m':
    #    relation='inv'
    #    ConvFactor=Erg2A*1e-10
    elif Input_unit.lower()=='ev':
        ConvFactor = Erg2eV
    elif Input_unit.lower()=='kev':
        ConvFactor = Erg2eV*1e-3
    elif Input_unit.lower()=='mev':
        ConvFactor = Erg2eV*1e-6
    elif Input_unit.lower()=='gev':
        ConvFactor = Erg2eV* 1e-9
    #elif Input_unit.lower()=='t':
    #    ConvFactor = Erg2T
    elif Input_unit.lower()=='me':
        ConvFactor = Erg2me
    elif Input_unit.lower()=='mp':
        ConvFactor = Erg2mp
    elif Input_unit.lower()=='cal':
        ConvFactor = Erg2cal
    elif Input_unit.lower()=='btu':
        ConvFactor = Erg2Btu
    elif Input_unit.lower()=='kwh':
        ConvFactor = Erg2kWh
    elif Input_unit.lower()=='tnt':
        ConvFactor = Erg2TNT
    #elif Input_unit =='gr':
    #    ConvFactor = Erg2gr
    else: print 'error: unknown InUnit option'
    """
    if relation == 'lin':
        ErgE = Energy * ConvFactor
    elif relation == 'inv':
        ErgE = Energy / ConvFactor
    else:
        print('unknown relation')
    relation = 'lin'
    if Output_unit.lower() == 'erg':
        ConvFactor = Erg2Erg
    elif Output_unit.lower() == 'j':
        ConvFactor = Erg2J
    """
    elif Output_unit.lower()== 'ev':
        ConvFactor = Erg2eV
    elif Output_unit.lower()== 'kev':
        ConvFactor = Erg2eV*1e-3
    elif Output_unit.lower()== 'mev':
        ConvFactor = Erg2eV*1e-6
    elif Output_unit.lower()== 'gev':
        ConvFactor = Erg2eV*1e-9
    #elif Output_unit.lower()== 't':
    #    ConvFactor = Erg2T
    elif Output_unit.lower()== 'me':
        ConvFactor = Erg2me
    elif Output_unit.lower()== 'mp':
        ConvFactor = Erg2mp
    elif Output_unit.lower()== 'cal':
        ConvFactor = Erg2cal
    elif Output_unit.lower()== 'btu':
        ConvFactor = Erg2Btu
    elif Output_unit.lower()== 'kwh':
        ConvFactor = Erg2kWh
    elif Output_unit.lower()== 'tnt':
        ConvFactor = Erg2TNT
    #elif Output_unit.lower()== 'gr':
    #    ConvFactor = Erg2gr
    else: print 'Unknown InUnit Option'
"""
    if relation == 'lin':
        new_energy = ErgE * ConvFactor
    elif relation == 'inv':
        new_energy = ErgE / ConvFactor
    else:
        print('unknown relation')
    return new_energy


def square(x):
    """Returns ``{'y': x * x}``."""
    return {'y': x * x}


def twice_nll(pars, data, pdf):
    """
    Twice the negative Log-Likelihood.

    Args:
        data (`tensor`): the data
        pdf (~pyhf.pdf.Model): The statistical model adhering to the schema model.json

    Returns:
        Twice the negative log likelihood.

    """
    return -2 * pdf.logpdf(pars, data)


def gpencil_brush_preset_add(name: str='', remove_name: bool=False,
    remove_active: bool=False):
    """Add or remove grease pencil brush preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_name: remove_name
    :type remove_name: bool
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def describe_activations(Filters=None, MaxResults=None, NextToken=None):
    """
    Details about the activation, including: the date and time the activation was created, the expiration date, the IAM role assigned to the instances in the activation, and the number of instances activated by this registration.
    See also: AWS API Documentation

    :example: response = client.describe_activations(
        Filters=[
            {
                'FilterKey': 'ActivationIds'|'DefaultInstanceName'|'IamRole',
                'FilterValues': [
                    'string',
                ]
            },
        ],
        MaxResults=123,
        NextToken='string'
    )

    :type Filters: list
    :param Filters: A filter to view information about your activations.
            (dict) --Filter for the DescribeActivation API.
            FilterKey (string) --The name of the filter.
            FilterValues (list) --The filter values.
            (string) --

    :type MaxResults: integer
    :param MaxResults: The maximum number of items to return for this call. The call also returns a token that you can specify in a subsequent call to get the next set of results.

    :type NextToken: string
    :param NextToken: A token to start the list. Use this token to get the next set of results.

    :rtype: dict
    :return: {
        'ActivationList': [
            {
                'ActivationId': 'string',
                'Description': 'string',
                'DefaultInstanceName': 'string',
                'IamRole': 'string',
                'RegistrationLimit': 123,
                'RegistrationsCount': 123,
                'ExpirationDate': datetime(2015, 1, 1),
                'Expired': True|False,
                'CreatedDate': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


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


def restart_app_server(EnvironmentId=None, EnvironmentName=None):
    """
    Causes the environment to restart the application container server running on each Amazon EC2 instance.
    See also: AWS API Documentation

    Examples
    The following operation restarts application servers on all instances in an environment named my-env:
    Expected Output:

    :example: response = client.restart_app_server(
        EnvironmentId='string',
        EnvironmentName='string'
    )

    :type EnvironmentId: string
    :param EnvironmentId: The ID of the environment to restart the server for.
            Condition: You must specify either this or an EnvironmentName, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :type EnvironmentName: string
    :param EnvironmentName: The name of the environment to restart the server for.
            Condition: You must specify either this or an EnvironmentId, or both. If you do not specify either, AWS Elastic Beanstalk returns MissingRequiredParameter error.

    :return: response = client.restart_app_server(
        EnvironmentName='my-env',
    )

    print(response)

    """
    pass


@classmethod
def set_config(mcs, config_path):
    """Set config which should be used in within Config singleton.

        :param config_path: a path to configuration that should be used
        :type config_path: str
        """
    assert mcs._instance is None
    mcs._config = config_path


@staticmethod
def dedupe_events_row_set(events_row_set):
    """
        dedupes list of list while preserving order
        used to dedupe events rowSets pbp response because some games have duplicate events
        """
    deduped_events_row_set = []
    for sublist in events_row_set:
        if sublist not in deduped_events_row_set:
            deduped_events_row_set.append(sublist)
    return deduped_events_row_set


def match_items(lines, content_old):
    """Create items for mangled lines.

    This function tries to match the lines in ``lines`` with the items (source
    file references and line numbers) in ``content_old``. The
    ``mangle_docstrings`` function changes the actual docstrings, but doesn't
    keep track of where each line came from. The manging does many operations
    on the original lines, which are hard to track afterwards.

    Many of the line changes come from deleting or inserting blank lines. This
    function tries to match lines by ignoring blank lines. All other changes
    (such as inserting figures or changes in the references) are completely
    ignored, so the generated line numbers will be off if ``mangle_docstrings``
    does anything non-trivial.

    This is a best-effort function and the real fix would be to make
    ``mangle_docstrings`` actually keep track of the ``items`` together with
    the ``lines``.

    Examples
    --------
    >>> lines = ['', 'A', '', 'B', '   ', '', 'C', 'D']
    >>> lines_old = ['a', '', '', 'b', '', 'c']
    >>> items_old = [('file1.py', 0), ('file1.py', 1), ('file1.py', 2),
    ...              ('file2.py', 0), ('file2.py', 1), ('file2.py', 2)]
    >>> content_old = ViewList(lines_old, items=items_old)
    >>> match_items(lines, content_old) # doctest: +NORMALIZE_WHITESPACE
    [('file1.py', 0), ('file1.py', 0), ('file2.py', 0), ('file2.py', 0),
     ('file2.py', 2), ('file2.py', 2), ('file2.py', 2), ('file2.py', 2)]
    >>> # first 2 ``lines`` are matched to 'a', second 2 to 'b', rest to 'c'
    >>> # actual content is completely ignored.

    Notes
    -----
    The algorithm tries to match any line in ``lines`` with one in
    ``lines_old``.  It skips over all empty lines in ``lines_old`` and assigns
    this line number to all lines in ``lines``, unless a non-empty line is
    found in ``lines`` in which case it goes to the next line in ``lines_old``.

    """
    items_new = []
    lines_old = content_old.data
    items_old = content_old.items
    j = 0
    for i, line in enumerate(lines):
        while j < len(lines_old) - 1 and not lines_old[j].strip():
            j += 1
        items_new.append(items_old[j])
        if line.strip() and j < len(lines_old) - 1:
            j += 1
    assert len(items_new) == len(lines)
    return items_new


def choose(n, k):
    """
    A fast way to calculate binomial coefficients C(n, k). It is 10 times faster
    than scipy.mis.comb for exact answers.

    :param n: Index of binomial coefficient.
    :type n: `int`
    :param k: Index of binomial coefficient.
    :type k: `int`
    """
    if 0 <= k <= n:
        ntok = 1
        ktok = 1
        for t in range(1, min(k, n - k) + 1):
            ntok *= n
            ktok *= t
            n -= 1
        return ntok // ktok
    else:
        return 0


@classmethod
def response_payload(cls, result, request_id):
    """JSON v2 response payload."""
    return {'jsonrpc': '2.0', 'result': result, 'id': request_id}


def create_dic(udic):
    """
    Create a glue dictionary from a universal dictionary
    """
    return udic


@classmethod
def from_json(cls, data):
    """
        Accept internal annotated format

        """
    return cls(**data['__value__'])


@classmethod
def get_icon(klass):
    """
        Default getter function - returns the `icon` property
        """
    return klass.icon


@classmethod
def _infer_num_arguments(cls, type_signature: str) ->int:
    """
        Takes a type signature and infers the number of arguments the corresponding function takes.
        Examples:
            e -> 0
            <r,e> -> 1
            <e,<e,t>> -> 2
            <b,<<b,#1>,<#1,b>>> -> 3
        """
    if not '<' in type_signature:
        return 0
    type_signature = type_signature[1:-1]
    num_brackets = 0
    char_index = 0
    for char in type_signature:
        if char == '<':
            num_brackets += 1
        elif char == '>':
            num_brackets -= 1
        elif char == ',':
            if num_brackets == 0:
                break
        char_index += 1
    return_type = type_signature[char_index + 1:]
    return 1 + cls._infer_num_arguments(return_type)


@classmethod
def _hash_key_attribute(cls):
    """
        Returns the attribute class for the hash key
        """
    for attr_cls in cls._get_attributes().values():
        if attr_cls.is_hash_key:
            return attr_cls


@classmethod
def from_nlp(cls, nlp, **cfg):
    """Factory to add to Language.factories via entry point."""
    return cls(nlp.vocab, **cfg)


def move_custom_slides_to_topics(apps, schema_editor):
    """
    Move all custom slides to new topic model.
    """
    ContentType = apps.get_model('contenttypes', 'ContentType')
    CustomSlide = apps.get_model('core', 'CustomSlide')
    Item = apps.get_model('agenda', 'Item')
    Topic = apps.get_model('topics', 'Topic')
    content_type_custom_slide = ContentType.objects.get_for_model(CustomSlide)
    content_type_topic = ContentType.objects.get_for_model(Topic)
    for custom_slide in CustomSlide.objects.all():
        topic = Topic.objects.create(title=custom_slide.title, text=
            custom_slide.text)
        topic.attachments.add(*custom_slide.attachments.all())
        item = Item.objects.get(object_id=custom_slide.pk, content_type=
            content_type_custom_slide)
        item.object_id = topic.pk
        item.content_type = content_type_topic
        item.save(skip_autoupdate=True)
    CustomSlide.objects.all().delete()
    content_type_custom_slide.delete()


def show_one_level(open: bool=True):
    """Expand/collapse all entries by one level

    :param open: Open, Expand all entries one level deep
    :type open: bool
    """
    pass


def api_full_name(api_name, api_version, organization_name):
    """Canonical full name for an API; used to generate output directories and
    package name"""
    if api_version:
        return '-'.join([organization_name, api_name, api_version])
    else:
        return '-'.join([organization_name, api_name])


def check_flush(hand):
    """Check whether the hand has a flush; returns a boolean."""
    if len(hand) == len(hand.by_suit(hand[0].suit)):
        return True
    return False


@staticmethod
def _max_form(f, colname):
    """
        Assumes dataframe with hierarchical columns with first index equal to the
        use and second index equal to the attribute.

        e.g. f.columns equal to::

            mixedoffice   building_cost
                          building_revenue
                          building_size
                          max_profit
                          max_profit_far
                          total_cost
            industrial    building_cost
                          building_revenue
                          building_size
                          max_profit
                          max_profit_far
                          total_cost
        """
    df = f.stack(level=0)[[colname]].stack().unstack(level=1).reset_index(level
        =1, drop=True)
    return df.idxmax(axis=1)


def _create_attributes_dictionary(arguments, parser):
    """
    Convert the attributes string (of the form 'attr1=val1,attr2=val2') into a dictionary of key-value pairs
    """
    if arguments.attributes is not None:
        dict_pairs = arguments.attributes.split(',')
        attributes = {}
        for pair in dict_pairs:
            try:
                key, value = pair.split('=')
                if not (key and value):
                    raise ValueError
                attributes[key] = value
            except ValueError:
                parser.error(
                    "Invalid attribute: expected key-value pair in the format 'key=value', got '%s'"
                     % pair)
        arguments.attributes = attributes


def encode_multipart(fields, files, boundary=None):
    """Prepare a multipart HTTP request.

    *fields* is a sequence of (name: str, value: str) elements for regular
    form fields, *files* is a sequence of (name: str, filename: str, value:
    bytes) elements for data to be uploaded as files.

    Returns (content_type: bytes, body: bytes) ready for http.client.HTTP.
    """
    if boundary is None:
        boundary = b'--------------GHSKFJDLGDS7543FJKLFHRE75642756743254'
    elif not isinstance(boundary, bytes):
        raise TypeError('boundary must be bytes, not %r' % type(boundary))
    l = []
    for key, values in fields:
        if not isinstance(values, (tuple, list)):
            values = [values]
        for value in values:
            l.extend((b'--' + boundary, (
                'Content-Disposition: form-data; name="%s"' % key).encode(
                'utf-8'), b'', value.encode('utf-8')))
    for key, filename, value in files:
        l.extend((b'--' + boundary, (
            'Content-Disposition: form-data; name="%s"; filename="%s"' % (
            key, filename)).encode('utf-8'), b'', value))
    l.append(b'--' + boundary + b'--')
    l.append(b'')
    body = b'\r\n'.join(l)
    content_type = b'multipart/form-data; boundary=' + boundary
    return content_type, body


def format_args(worker, args, kwargs):
    """Format args for various languages.

    Args:
        worker: The global worker instance.
        args: The arguments for cross language.
        kwargs: The keyword arguments for cross language.

    Returns:
        List of args and kwargs (if supported).
    """
    if not worker.load_code_from_local:
        raise ValueError(
            'Cross language feature needs --load-code-from-local to be set.')
    if kwargs:
        raise TypeError(
            'Cross language remote functions does not support kwargs.')
    return args


def objectToProcessing(request):
    """Mark the current user as having refused permission to process"""
    NotImplemented


@staticmethod
def _parse_module_name(program_param):
    """Given a module name or a script name, return the module name.

        Args:
            program_param (str): Module or script name.

        Returns:
            str: Module name.

        """
    if program_param and program_param.endswith('.py'):
        return program_param[:-3]
    return program_param


def Clift_Gauvin(Re):
    """Calculates drag coefficient of a smooth sphere using the method in
    [1]_ as described in [2]_.

    .. math::
        C_D = \\frac{24}{Re}(1 + 0.152Re^{0.677}) + \\frac{0.417}
        {1 + 5070Re^{-0.94}}

    Parameters
    ----------
    Re : float
        Reynolds number of the sphere, [-]

    Returns
    -------
    Cd : float
        Drag coefficient [-]

    Notes
    -----
    Range is Re <= 2E5

    Examples
    --------
    >>> Clift_Gauvin(200.)
    0.7905400398000133

    References
    ----------
    .. [1] R. Clift, W.H. Gauvin, The motion of particles in turbulent gas
       streams, Proc. Chemeca, 70, 1970, pp. 14-28.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    Cd = 24.0 / Re * (1 + 0.152 * Re ** 0.677) + 0.417 / (1 + 5070 * Re **
        -0.94)
    return Cd


def isocalendar():
    """Return a 3-tuple, (ISO year, ISO week number, ISO weekday).

        The same as self.date().isocalendar().
        """


def _flatten_elements(elm_def):
    """ Combine element with its base elements. """
    while 'base' in elm_def:
        base_elm = elm_def['base']
        elm_def.pop('base')
        elm_def['paths'] = elm_def.get('paths', []) + base_elm.get('paths', [])
        elm_def['labels'] = elm_def.get('labels', []) + base_elm.get('labels',
            [])
        elm_def['shapes'] = elm_def.get('shapes', []) + base_elm.get('shapes',
            [])
        d = base_elm.get('anchors', {}).copy()
        d.update(elm_def.get('anchors', {}))
        elm_def['anchors'] = d
        for i in base_elm:
            if i not in ['paths', 'labels', 'shapes', 'anchors'
                ] and i not in elm_def:
                elm_def[i] = base_elm[i]
    return elm_def


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


def set_hooks(app, hook_setters=None):
    """Set hooks on a Flask application

    Example: Adding a hook

    .. doctest::
        >>> from flask import Flask, request, current_app

        >>> app = Flask(__name__)

        >>> def set_log_request_hook(app):
        ...     @app.before_request
        ...     def log_request():
        ...         current_app.logger.debug(request)

        >>> my_hook_setters = [set_log_request_hook]

        >>> set_hooks(app, my_hook_setters)

    :param app: Flask application
    :type app: :class:`flask.Flask`
    :param hook_setters: Hooks to set on the application.
        Expects a list of functions that takes a :class:`flask.Flask` as argument
    :type hook_setters: list
    """
    hook_setters = hook_setters or []
    for set_hook in hook_setters:
        set_hook(app)


def convert_range(old_value, old_min, old_max, new_min, new_max):
    """Method to convert values between two ranges.

    Parameters
    ----------
    old_value : object
        Old value(s) to convert. May be a single number, vector or tensor.
    old_min : float
        Minimum old value.
    old_max : float
        Maximum old value.
    new_min : float
        Minimum new value.
    new_max : float
        Maximum new value.

    Returns
    -------
    object
        New value(s).
    """
    return (old_value - old_min) * (new_max - new_min) / (old_max - old_min
        ) + new_min


def _to_url_params(data, glue='.', separator=','):
    """
    Converts data dictionary to url parameters
    """
    params = {}
    for key, value in data.items():
        if isinstance(value, bool):
            params[key] = 1 if value else 0
        elif isinstance(value, list):
            params[key] = separator.join(map(str, value))
        elif isinstance(value, dict):
            for subkey, subvalue in value.items():
                if isinstance(subvalue, list):
                    params[glue.join((key, subkey))] = separator.join(map(
                        str, subvalue))
                else:
                    params[glue.join((key, subkey))] = subvalue
        else:
            params[key] = value
    return params


def add_ros_arguments(parser):
    """
    Arguments relevant for a ros system.

    :param argparse.ArgumentParser parser:
    """
    group = parser.add_argument_group(title='ros arguments')
    group.add_argument('--rosdistro', action='store', default=None, help=
        'manually specify the ros release to install/update')


def reverse_key(key):
    """
    Tenant aware function to reverse a cache key.

    Required for django-redis REVERSE_KEY_FUNCTION setting.
    """
    return key.split(':', 3)[3]


@classmethod
def add_op2_data(cls, data, comment=''):
    """
        Adds a FORCE2/MOMENT2 card from the OP2

        Parameters
        ----------
        data : List[varies]
            a list of fields defined in OP2 format
        comment : str; default=''
            a comment for the card

        """
    sid = data[0]
    node = data[1]
    mag = data[2]
    g1 = data[3]
    g2 = data[4]
    g3 = data[5]
    g4 = data[6]
    return cls(sid, node, mag, g1, g2, g3, g4, comment=comment)


def _check_rows(rows, check, in_range=True, return_test='any'):
    """Check all rows to be in/out of a certain range and provide testing on
    return values based on provided conditions

    Parameters
    ----------
    rows : pd.DataFrame
        data rows
    check : dict
        dictionary with possible values of 'up', 'lo', and 'year'
    in_range : bool, optional
        check if values are inside or outside of provided range
    return_test : str, optional
        possible values:
            - 'any': default, return scenarios where check passes for any entry
            - 'all': test if all values match checks, if not, return empty set
    """
    valid_checks = set(['up', 'lo', 'year'])
    if not set(check.keys()).issubset(valid_checks):
        msg = 'Unknown checking type: {}'
        raise ValueError(msg.format(check.keys() - valid_checks))
    if 'year' not in rows:
        rows = rows.copy()
        rows['year'] = rows['time'].apply(lambda x: x.year)
    where_idx = set(rows.index[rows['year'] == check['year']]
        ) if 'year' in check else set(rows.index)
    rows = rows.loc[list(where_idx)]
    up_op = rows['value'].__le__ if in_range else rows['value'].__gt__
    lo_op = rows['value'].__ge__ if in_range else rows['value'].__lt__
    check_idx = []
    for bd, op in [('up', up_op), ('lo', lo_op)]:
        if bd in check:
            check_idx.append(set(rows.index[op(check[bd])]))
    if return_test is 'any':
        ret = where_idx & set.union(*check_idx)
    elif return_test == 'all':
        ret = where_idx if where_idx == set.intersection(*check_idx) else set()
    else:
        raise ValueError('Unknown return test: {}'.format(return_test))
    return ret


def khatri_rao(*args, **kwargs):
    """Computes the Khatri-Rao product of the input matrices.

    Given a collection of :math:`n` input matrices,

    .. math::
       A_1 \\in \\mathbb{R}^{M_1 \\times M}, \\ldots, A_n \\in \\mathbb{R}^{M_n \\times N},

    the (column-wise) Khatri-Rao product is defined as the matrix,

    .. math::
       X = A_1 \\otimes \\cdots \\otimes A_n \\in \\mathbb{R}^{(M_1 \\cdots M_n) \\times N},

    where the :math:`k` th column is equal to the column-wise outer product
    :math:`{A_1}_k \\otimes \\cdots \\otimes {A_n}_k` where :math:`{A_i}_k` is the kth
    column of the ith matrix.

    Example::

      >>> A = mx.nd.array([[1, -1],
      >>>                  [2, -3]])
      >>> B = mx.nd.array([[1, 4],
      >>>                  [2, 5],
      >>>                  [3, 6]])
      >>> C = mx.nd.khatri_rao(A, B)
      >>> print(C.asnumpy())
      [[  1.  -4.]
       [  2.  -5.]
       [  3.  -6.]
       [  2. -12.]
       [  4. -15.]
       [  6. -18.]]

    Defined in src/operator/contrib/krprod.cc:L108
    This function support variable length of positional input.

    Parameters
    ----------
    args : Symbol[]
        Positional input matrices

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

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


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 main():
    """The main function for when invoked from an UI bundle."""
    from .cli import main
    main(prog_name='lektor')


@classmethod
def copy(cls, txout):
    """Deep copy of TxOutput"""
    return cls(txout.amount, txout.script_pubkey)


def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in range(0, len(l), n):
        yield l[i:i + n]


def strip_trailing_semicolons(source, function):
    """
    Give the source of a cell, filter out lines that contain a specified
    function call and end in a semicolon.
    """
    filtered = []
    for line in source.splitlines():
        if line.endswith(f'{function}();'):
            filtered.append(line[:-1])
        else:
            filtered.append(line)
    return '\n'.join(filtered)


def right_pad(string: str, count: int) ->str:
    """
    Add spaces to the end of a string.

    :param string: The string to pad.
    :param count: The number of characters to which the given string should be padded.
    """
    if not string:
        raise ValueError(f'Parameter string is required.')
    if not isinstance(string, str):
        raise TypeError(
            f'Parameter string must be a string. Received {type(string)}')
    if count < 0:
        raise ValueError(f'Parameter count must be positive. Received {count}')
    return string + ' ' * (count - len(string))


def trace(__self, __message, *args, **kwargs):
    """Log ``message.format(*args, **kwargs)`` with severity ``'TRACE'``."""
    __self._log('TRACE', None, False, __self._options, __message, args, kwargs)


def rfc_6901_replace(path):
    """Implements rfc 6901 escape code replacement."""
    return path.replace('~1', '/').replace('~0', '~')


def dummy_tokenizer(doc):
    """
    A pass through method for pre-tokenized documents. Use it as preprocessor,
    and tokenizer for the tfidf/count vectorizer. (to replace lambda x:x)
    :param doc:
    :return:
    """
    return doc


def _get_sysfs_netdev_path(pci_addr, pf_interface):
    """Get the sysfs path based on the PCI address of the device.

    Assumes a networking device - will not check for the existence of the path.
    """
    if pf_interface:
        return '/sys/bus/pci/devices/%s/physfn/net' % pci_addr
    return '/sys/bus/pci/devices/%s/net' % pci_addr


def monthly_to_annual(monthly_data):
    """Converts monthly data to annual"""
    import pandas as pd
    import numpy as np
    monthly = monthly_data.values
    years = int(monthly_data.shape[1] / 12)
    start = 0
    end = 11
    for year in range(years):
        to_year = monthly[:, start:end].sum(axis=1)
        if year == 0:
            annual = np.array(to_year)
        else:
            annual = np.vstack([annual, to_year])
        start += 12
        end += 12
    annual = pd.DataFrame(annual).transpose()
    annual.index = monthly_data.index
    return annual


def get_by_course_id(frame, course_ids):
    """Finds and reeturns a course or list of courses from the results
    frame"""
    if type(course_ids) is not list:
        course_ids = list(course_ids)
    return frame[frame['course_id'].isin(course_ids)]


def _str_format(x):
    """
    Reformat NaN and floating point numbers for CSV output.
    """
    if isinstance(x, float):
        return '{:.0f}'.format(x)
    return str(x)


def pts_to_verts(xvec, yvec):
    """
    Convert points to vertices, i.e., convert from 2 1D arrays (or list) of     x- and y-coordinates to a list-of-lists of [x,y] pairs
    """
    verts = []
    for count in range(len(xvec)):
        verts.append([xvec[count], yvec[count]])
    return verts


def switch_toggle(fritz, args):
    """Command that toggles the device switch state."""
    fritz.set_switch_state_toggle(args.ain)


def true_if_equal_filter(*value):
    """
    Returns 'true' if all values are equal, otherwise 'false'.
    """
    first = True
    eq = None
    for v in value:
        if first:
            eq = v
            first = False
            continue
        if eq != v:
            return False
    return True


def checkio(array):
    """
        sums even-indexes elements and multiply at the last
    """
    if not array:
        return 0
    return sum(array[::2]) * array[-1]


def get_default_inits(kind='dpm', depends_on={}, learn=False, ssdelay=False,
    gbase=False):
    """ if user does not provide inits dict when initializing Model instance,
    grab default dictionary of init params reasonably suited for Model kind
    """
    inits = {'a': 0.42, 'v': 1.25, 'tr': 0.2}
    pdep = list(depends_on)
    if 'dpm' in kind:
        inits['ssv'] = -1.3
    elif 'race' in kind:
        inits['ssv'] = 1.3
    if 'x' in kind and 'xb' not in list(inits):
        inits['xb'] = 1.5
    if 'si' in pdep:
        inits['si'] = 0.01
    if ssdelay:
        inits['sso'] = 0.08
    if gbase:
        inits['z'] = 0.1
    if learn:
        inits['BX'] = 0.02
        inits['AX'] = 0.15
        inits['PX'] = 0.0015
    return inits


@classmethod
def d(cls, n):
    """The fundamental factor D (lowercase delta here) in B_n."""
    if n not in cls._d:
        cls._d[n] = cls.CanonicalFactor([n - 1] + list(range(0, n - 1)))
    return cls._d[n]


def select_interior_faces():
    """Select faces where all edges have more than 2 face users

    """
    pass


def get_device_status(device_key):
    """
    Get current device status.

    :param device_key: Device identifier
    :type device_key: str
    :returns: status
    :rtype: DeviceStatus
    """
    pass


def parse_size(size):
    """Parse a size specification, i.e. an int with a K, M, G suffix.

    >>> parse_size("1000")
    1000
    >>> parse_size("100K")
    102400
    >>> parse_size("1M")
    1048576
    >>> parse_size("5 g")
    5368709120
    >>> parse_size("")
    Traceback (most recent call last):
    ...
    ValueError
    >>> parse_size("test M")
    Traceback (most recent call last):
    ...
    ValueError: test M
    """
    SUFFIXES = {'K': 1024, 'M': 1024 * 1024, 'G': 1024 * 1024 * 1024}
    if not size:
        raise ValueError(size)
    s = size.strip()
    suffix = s[-1]
    try:
        mult = SUFFIXES[suffix.upper()]
        s = s[:-1]
    except KeyError:
        mult = 1
    try:
        return int(s.strip()) * mult
    except ValueError:
        raise ValueError(size)


@classmethod
def from_dict(cls, connection, data):
    """Returns a metric object from a dictionary item,
        which is usually from librato's API"""
    obj = cls(connection, data['name'])
    obj.display_name = data['display_name'] if 'display_name' in data else None
    obj.events = data['events'] if 'events' in data else None
    obj.query = data['query'] if 'query' in data else {}
    return obj


def getInterpolationType(value):
    """
    Returns one of ['lin-lin', 'log-lin', 'lin-log', 'log-log'] following
    the convention:
                  0 or 2, linear in x and y         -> returns lin-lin
                  3, logarithmic in x, linear in y  -> returns log-lin
                  4, linear in x, logarithmic in y  -> returns lin-log
                  5, logarithmic in x and y         -> returns log-log
    """
    if value in [0, 2]:
        return 'lin-lin'
    if value == 3:
        return 'log-lin'
    if value == 4:
        return 'lin-log'
    if value == 5:
        return 'log-log'
    raise ValueError('Invalid interpolation flag')


def clear():
    """
	Deletes all stored variables
	"""
    with open('var_list.silas', 'r+') as var_list:
        var_list.truncate(0)
        var_list.close


@staticmethod
def remove(*args, **kwargs):
    """A stub to be implemented by child class."""
    raise NotImplementedError(
        '[ERROR] Cannot call method on file.Node. It is an abstract class.')


def tidy_split(df, column, sep='|', keep=False):
    """
    Split the values of a column and expand so the new DataFrame has one split
    value per row.
    modified from https://github.com/cognoma/genes/blob/721204091a96e55de6dcad165d6d8265e67e2a48/2.process.py#L61-L95

    Params
    ------
    df : pandas.DataFrame
        dataframe with the column to split and expand
    column : str
        the column to split and expand
    sep : str
        the string used to split the column's values
    keep : bool
        whether to retain the presplit value as it's own row

    Returns
    -------
    pandas.DataFrame
        Returns a dataframe with the same columns as `df`.
    """
    indexes = list()
    new_values = list()
    for i, presplit in enumerate(df[column].astype(str)):
        values = presplit.split(sep)
        if keep and len(values) > 1:
            indexes.append(i)
            new_values.append(presplit)
        for value in values:
            indexes.append(i)
            new_values.append(value)
    new_df = df.iloc[(indexes), :].copy()
    new_df[column] = new_values
    return new_df


@staticmethod
def findValueInRDF(prop, prefixPath, ns, tag):
    """Find a value in RDF : first as an element then as an attribute."""
    path = prefixPath + '/' + ns + tag
    value = prop.find(path)
    if value is not None:
        return value.text
    value = prop.find(prefixPath).attrib.get(ns + tag, None)
    if value and value is not None:
        return value
    return None


def value_has_changed_for_fields(instance, fields):
    """
        Did any field values change since the last time they were saved?
        """
    if not instance.pk:
        return True
    old_values = instance.__class__._default_manager.filter(pk=instance.pk
        ).values().get()
    for f in fields:
        if not getattr(instance, f) == old_values[f]:
            return True
    return False


def dtype(input):
    """Return the data type of the tensor.

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

    Returns
    -------
    data type
        It should be one of the values in the data type dict.
    """
    pass


def filter_low_text_tweets(doc_term_matrix, term_no):
    """Return index of tweets that should be involved """
    included_tweet_ids = []
    for i in range(0, doc_term_matrix.shape[0]):
        if doc_term_matrix[i].sum() > term_no:
            included_tweet_ids.append(i)
    return included_tweet_ids


def __call__(obj):
    """Post process to obj

        :param fileobj:
        :rtype: unkown
        :return obj: post processed object
        """


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 uid2user(uid):
    """ eg: user = uid2user(54321)
        get username based on uidnumber, return uidNumber if fails
    """
    try:
        import pwd
        return pwd.getpwuid(uid).pw_name
    except:
        return str(uid)


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 mean(a):
    """
    Return the average of the elements of array a.
    """
    return sum(a) / float(len(a))


def freq_to_ppm(f, water_hz=0.0, water_ppm=4.7, hz_per_ppm=127.68):
    """
    Convert a set of numbers from frequenxy in hertz to chemical shift in ppm
    """
    return water_ppm - (f - water_hz) / hz_per_ppm


@staticmethod
def to_dataframe(products):
    """Return the products from a query response as a Pandas DataFrame
        with the values in their appropriate Python types.
        """
    try:
        import pandas as pd
    except ImportError:
        raise ImportError(
            'to_dataframe requires the optional dependency Pandas.')
    return pd.DataFrame.from_dict(products, orient='index')


def annotate_row(context, row, number, line, data):
    """Return the XHTML markup for the table cell that contains the
        annotation data.

        `context` is the context corresponding to the content being annotated,
        `row` is the tr Element being built, `number` is the line number being
        processed and `line` is the line's actual content.
        `data` is whatever additional data the `get_annotation_data` method
        decided to provide.
        """


@classmethod
def declare_core(cls, core):
    """ Add new core in the declared cores

        ::

            RegistryManager.declare_core('Core name')

            -----------------------------------------

            @Declarations.register(Declarations.Core)
            class ``Core name``:
                ...

        .. warning::

            The core must be declared in the application, not in the bloks
            The declaration must be done before the loading of the bloks

        :param core: core name
        """
    if core not in cls.declared_cores:
        cls.declared_cores.append(core)


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 += f".post{pieces['distance']:d}"
            if pieces['dirty']:
                rendered += '.dev0'
    else:
        rendered = f"0.post{pieces['distance']:d}"
        if pieces['dirty']:
            rendered += '.dev0'
    return rendered


def lessThanEqualTo(t):
    """Compare this DateTime object to another DateTime object OR
        a floating point number such as that which is returned by the
        python time module. Returns true if the object represents a
        date/time less than or equal to the specified DateTime or time
        module style time.  Revised to give more correct results
        through comparison of long integer milliseconds."""


def hash_password(plaintext_password=''):
    """
    Create a password hash from a given string for protecting a worksheet
    only. This will not work for encrypting a workbook.

    This method is based on the algorithm provided by
    Daniel Rentz of OpenOffice and the PEAR package
    Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>.
    See also http://blogs.msdn.com/b/ericwhite/archive/2008/02/23/the-legacy-hashing-algorithm-in-open-xml.aspx
    """
    password = 0
    for idx, char in enumerate(plaintext_password, 1):
        value = ord(char) << idx
        rotated_bits = value >> 15
        value &= 32767
        password ^= value | rotated_bits
    password ^= len(plaintext_password)
    password ^= 52811
    return str(hex(password)).upper()[2:]


def clean_line(description):
    """Formats catapult-server custom tags into readable strings.

    Args:
        description (str): Line to format.

    Returns:
        str: Formatted line.
    """
    return description.replace('\\c', 'Set to').replace('\\a ', '').replace(
        '\\note', '*Note*:').replace('std::', '').replace('\n', '')


def zero_one_loss_calc(TP, POP):
    """
    Calculate zero-one loss.

    :param TP: true Positive
    :type TP : dict
    :param POP: population
    :type POP : int
    :return: zero_one loss as integer
    """
    try:
        length = POP
        return length - sum(TP.values())
    except Exception:
        return 'None'


def p_specification(t):
    """specification : definition_list"""


def jsbool(x: bool) ->str:
    """Convert Python bool to Javascript bool."""
    return repr(x).lower()


def decrypt_AES(cipher, package, iv):
    """
    Decrypts an AES package using a specific cipher and iv
    :param cipher: String. Key for decryption.
    :param package: String. The base64 encoded data to be decrypted.
    :param iv: String. 16 characters. Used to randomize the data for repeated
        cipher usage by changing this value. Can be sent plaintext.
    """
    from Crypto.Cipher import AES
    from base64 import b64decode
    cipher_obj = AES.new(cipher, AES.MODE_CBC, iv)
    return cipher_obj.decrypt(b64decode(package))