@staticmethod
def contentextract(txt):
    """
        Extract times values from a parsec log file output and return a
        dictionary of data.

        :param txt: Content text from a parsec output run.
        :return: dict with extracted values.
        """
    roitime = ''
    realtime = ''
    usertime = ''
    systime = ''
    for l in txt.split('\n'):
        if l.strip().startswith('[PARSEC] Benchmarks to run:'):
            benchmark = l.strip().split(':')[1]
            if benchmark.startswith('parsec'):
                benchmark = benchmark.strip().split('.')[1]
            else:
                benchmark = benchmark.strip()
        elif l.strip().startswith('[PARSEC] Unpacking benchmark input'):
            inputsize = l.strip().split("'")[1]
        elif l.strip().startswith('[PARSEC] No archive for input'):
            inputsize = l.strip().split("'")[1]
        elif l.strip().startswith('[HOOKS] Total time spent in ROI'):
            roitime = l.strip().split(':')[-1]
        elif l.strip().startswith('real'):
            realtime = l.strip().split('\t')[-1]
        elif l.strip().startswith('user'):
            usertime = l.strip().split('\t')[-1]
        elif l.strip().startswith('sys'):
            systime = l.strip().split('\t')[-1]
    if roitime:
        roitime = float(roitime.strip()[:-1])
    else:
        roitime = None
    if realtime:
        realtime = 60 * float(realtime.strip().split('m')[0]) + float(realtime
            .strip().split('m')[1][:-1])
    else:
        realtime = None
    if usertime:
        usertime = 60 * float(usertime.strip().split('m')[0]) + float(usertime
            .strip().split('m')[1][:-1])
    else:
        usertime = None
    if systime:
        systime = 60 * float(systime.strip().split('m')[0]) + float(systime
            .strip().split('m')[1][:-1])
    else:
        systime = None
    return {'benchmark': benchmark, 'input': inputsize, 'roitime': roitime,
        'realtime': realtime, 'usertime': usertime, 'systime': systime}


def wrap(text, width, prefix=''):
    """
    Simple word-wrapping thing. Might be worth considering a
    dependency on 'textwrap' if this gets longer than a few lines ;)
    """
    words = text.split()
    lines = []
    while len(words):
        line = prefix
        while len(words) and len(line) < width:
            word = words.pop(0)
            line += ' ' + word
        lines.append(line)
    return '\n'.join(lines)


def decode_response(client_message, to_object=None):
    """ Decode response from client message"""
    parameters = dict(response=None)
    parameters['response'] = client_message.read_bool()
    return parameters


def send(event, data, patient):
    """Send an update about event with data for patient.
        """


def check_notwanted(zelf, *args, **kwargs):
    """ whether an thing is not desired. """
    not_want = args[0]
    for key, value in not_want.items():
        if key == 'format':
            continue
        if key not in zelf:
            continue
        if value in zelf[key]:
            return True
    return False


def approximate_matches(list1, list2, epsilon=0.01):
    """
    Takes two list of tuples and searches for matches of tuples first value
    within the supplied epsilon. Emits tuples with the tuples second values
    where found. if a value in one dist does not match the other list, it is
    emitted alone.
    :param list1: first list of tuples
    :type list1: list
    :param list2: second list of tuples
    :type list2: list
    :param epsilon: maximum difference in
    :type epsilon: float
    :return: second values of tuples
    :rtype: generator
    """
    list1.sort()
    list2.sort()
    list1_index = 0
    list2_index = 0
    while list1_index < len(list1) or list2_index < len(list2):
        if list1_index == len(list1):
            yield 0, list2[list2_index][1]
            list2_index += 1
            continue
        if list2_index == len(list2):
            yield list1[list1_index][1], 0
            list1_index += 1
            continue
        list1_element = list1[list1_index][0]
        list2_element = list2[list2_index][0]
        difference = abs(list1_element - list2_element)
        if difference < epsilon:
            yield list1[list1_index][1], list2[list2_index][1]
            list1_index += 1
            list2_index += 1
        elif list1_element < list2_element:
            yield list1[list1_index][1], 0
            list1_index += 1
        elif list2_element < list1_element:
            yield 0, list2[list2_index][1]
            list2_index += 1
        else:
            raise AssertionError('Unexpected else taken')


def count_receive(link_counters):
    """Find the receive count in the counters returned by a CommunicationLink."""
    for processor in link_counters.values():
        if 'receive' in processor:
            return processor['receive']


def _isnamedtuple(obj):
    """Named tuples are identified via duck typing:
    http://www.gossamer-threads.com/lists/python/dev/1142178
    """
    return isinstance(obj, tuple) and hasattr(obj, '_fields')


@classmethod
def load_cache(cls, calendar_str: str):
    """Load a scheme calendar YAML file with cache.

        >>> %timeit Calendar.load_cache('bacs')
            969 ns ± 10.8 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
        """
    with cls._cache as cache:
        if not calendar_str in cache:
            cache[calendar_str] = cls.load(calendar_str)
        return cache[calendar_str]


def get_creator():
    """Return post creator name.
        """


def calculateKey(cls, target):
    """Calculate the reference key for this reference

        Currently this is a two-tuple of the id()'s of the
        target object and the target function respectively.
        """
    return id(target.__self__), id(target.__func__)


def FIB(n):
    """
    Fibonacci series up to n
    Returns: list of ints = jhta.FIB(n)
    """
    fib_list = []
    a, b = 0, 1
    while a < n:
        fib_list.append(a)
        a, b = b, a + b
    return fib_list


def describe_identity(IdentityId=None):
    """
    Returns metadata related to the given identity, including when the identity was created and any associated linked logins.
    You must use AWS Developer credentials to call this API.
    See also: AWS API Documentation

    :example: response = client.describe_identity(
        IdentityId='string'
    )

    :type IdentityId: string
    :param IdentityId: [REQUIRED]
            A unique identifier in the format REGION:GUID.

    :rtype: dict
    :return: {
        'IdentityId': 'string',
        'Logins': [
            'string',
        ],
        'CreationDate': datetime(2015, 1, 1),
        'LastModifiedDate': datetime(2015, 1, 1)
    }

    """
    pass


def __call__(task, request, retval, runtime):
    """Handle the execution result."""


def diff_central(x, y):
    """
    Applies the central finite difference scheme

    Parameters
    ----------
    x: array
        independent variable
    y: array
        dependent variable

    Returns
    -------
    dydx: array
        the dependent variable differentiated
    """
    x0 = x[:-2]
    x1 = x[1:-1]
    x2 = x[2:]
    y0 = y[:-2]
    y1 = y[1:-1]
    y2 = y[2:]
    f = (x2 - x1) / (x2 - x0)
    return (1 - f) * (y2 - y1) / (x2 - x1) + f * (y1 - y0) / (x1 - x0)


def isVisible():
    """Return True if the VR pane is visible."""
    pass


def revs(rev):
    """Normalize revision range.

    Takes a revision string representing one revision or a range of them
    and returns a pair (startrev, endrev).

    For example, the revision 43 starts at r42 and ends at r43:

      >>> revs('43')
      (42, '43')

    Sometimes it is convenient to copy and paste revision numbers
    from svn log output

      >>> revs('r43')
      (42, '43')

    Revision ranges are also supported:

      >>> revs('42-21252')
      (41, 21252)
      >>> revs('42-HEAD')
      (41, 'HEAD')

    SVN-compatible revision ranges also work

      >>> revs('41:21252')
      (41, 21252)
      >>> revs('41:HEAD')
      (41, 'HEAD')

    Even reverse diffs that undo certain revisions are supported
    correctly:

      >>> revs('42:41') # undo r42
      (42, 41)

    But not with the "simple rev" syntax

      >>> revs('42-41')
      Traceback (most recent call last):
        ...
      ValueError: empty range (42-41)

    """
    if rev.startswith('r'):
        rev = rev[1:]
    if '-' in rev:
        rev, endrev = rev.split('-')
        rev = int(rev) - 1
        if endrev != 'HEAD':
            endrev = int(endrev)
            if rev >= endrev:
                raise ValueError('empty range (%s-%s)' % (rev + 1, endrev))
    elif ':' in rev:
        rev, endrev = rev.split(':')
        rev = int(rev)
        if not endrev == 'HEAD':
            endrev = int(endrev)
    else:
        endrev = rev
        rev = int(rev) - 1
    return rev, endrev


def clamp_tensor(tensor, minimum, maximum):
    """
    Supports sparse and dense tensors.
    Returns a tensor with values clamped between the provided minimum and maximum,
    without modifying the original tensor.
    """
    if tensor.is_sparse:
        coalesced_tensor = tensor.coalesce()
        coalesced_tensor._values().clamp_(minimum, maximum)
        return coalesced_tensor
    else:
        return tensor.clamp(minimum, maximum)


@classmethod
def from_raw(cls, buf):
    """Create a new :py:class:`Index` object from an existing APKINDEX.

        :param buf:
            The buffer to read from (whether file, BytesIO, etc).

        :returns:
            A :py:class:`Index` object with the details from the APKINDEX.
        """
    idx = cls(packages=list())
    idx._fill_from_index_file(buf)
    return idx


def empty(histogram, flow=False):
    """Check to see if a histogram is empty, optionally with flow bins"""
    return histogram._empty(flow)


def new():
    """Add new paint curve

    """
    pass


def DTMLValidate(accessed=None, container=None, name=None, value=None, md=None
    ):
    """Validate access.
        * THIS EXISTS FOR DTML COMPATIBILITY *

        Arguments:

        accessed -- the object that was being accessed

        container -- the object the value was found in

        name -- The name used to access the value

        value -- The value retrieved though the access.

        md -- multidict for DTML (ignored)

        The arguments may be provided as keyword arguments. Some of these
        arguments may be ommitted, however, the policy may reject access
        in some cases when arguments are ommitted.  It is best to provide
        all the values possible.

        """


def get_column_types(df):
    """
    Returns a tuple (wvl_cols, meta_cols), given a dataframe.

    Notes
    -----
    Wavelength column is defined as columns with a numerical name (i.e. decimal).
    Everything else is considered metadata column.
    """
    isdigit = df.columns.map(str).str.replace('.', '').str.isdigit()
    wvl_cols = df.columns[isdigit].sort_values()
    meta_cols = df.columns.difference(wvl_cols)
    return wvl_cols, meta_cols


@classmethod
def get_morph_name(cls):
    """
        Get the name for polymorphic relations.
        """
    if not cls.__morph_name__:
        return cls._register.inverse[cls]
    return cls.__morph_name__


@staticmethod
def identify_tests(code, settings):
    """Identifies all block and inline test formats"""
    block_tests = list(filter(lambda s: s['block_comments'], settings.tests))
    inline_tests = list(filter(lambda s: s['inline_comments'], settings.tests))
    return block_tests, inline_tests


def getFileDialogTitle(msg, title):
    """
    Create nicely-formatted string based on arguments msg and title
    :param msg: the msg to be displayed
    :param title: the window title
    :return: None
    """
    if msg and title:
        return '%s - %s' % (title, msg)
    if msg and not title:
        return str(msg)
    if title and not msg:
        return str(title)
    return None


def pyplot_draw_point_cloud(points, output_filename):
    """ points is a Nx3 numpy array """
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    ax.scatter(points[:, (0)], points[:, (1)], points[:, (2)])
    ax.set_xlabel('x')
    ax.set_ylabel('y')
    ax.set_zlabel('z')


def ct_lt_u32(val_a, val_b):
    """
    Returns 1 if val_a < val_b, 0 otherwise. Constant time.

    :type val_a: int
    :type val_b: int
    :param val_a: an unsigned integer representable as a 32 bit value
    :param val_b: an unsigned integer representable as a 32 bit value
    :rtype: int
    """
    val_a &= 4294967295
    val_b &= 4294967295
    return (val_a ^ (val_a ^ val_b | val_a - val_b & 4294967295 ^ val_b)) >> 31


@staticmethod
def __filter_nodes(node_weights, return_positive_weights=True):
    """
        Filters out nodes with positive or negative weights and
        takes the absolute.

        :param node_weights: dict
        :param return_positive_weights: bool, if True returns nodes with
                                              positive weights,
                                              if False negative weights
        :return:
        """
    new_node_weights = {}
    for n, nv in node_weights.items():
        if nv > 0 and return_positive_weights:
            new_node_weights[n] = nv
        elif nv < 0 and not return_positive_weights:
            new_node_weights[n] = -nv
    return new_node_weights


def iterable(value):
    """
    If the value is not iterable, we convert it to an iterable containing
      that only value.
    :param x:
    :return:
    """
    try:
        return iter(value)
    except TypeError:
        return value,


def print_usage_error(err):
    """Print an error about incorrect usage."""
    print('USAGE ERROR: %s' % err.message)
    if err.suggestion is not None:
        print('Suggestion: %s' % err.suggestion)


def match_choice(c, norm, normI, normT, m, chm, rho, beta):
    """
    Checks match criterion
    Compute choice equation
    Discovers best choice

    :param norm: minimum of input and templates
    :param normI: norm of input

    :return: returns category choice location
    """
    m[c] = norm / normI
    if m[c] < rho:
        chm[c] = 0
    else:
        chm[c] = norm / (beta + normT)
    return chm.argmax(axis=0)


def patch_func(replacement, target_mod, func_name):
    """
    Patch func_name in target_mod with replacement

    Important - original must be resolved by name to avoid
    patching an already patched function.
    """
    original = getattr(target_mod, func_name)
    vars(replacement).setdefault('unpatched', original)
    setattr(target_mod, func_name, replacement)


def p_input(p):
    """input : maybe_nline statement
             | input statement """
    if p[1] is None:
        p[0] = p[2]
    else:
        so_far = p[1][1]
        new_statements = p[2][1]
        p[0] = ['STATEMENTS', p[1][1] + p[2][1]]


def dump_al():
    """Dump OpenAL info."""
    try:
        from pyglet.media.drivers import openal
    except:
        print('OpenAL not available.')
        return
    print('Library:', openal.lib_openal._lib)
    driver = openal.create_audio_driver()
    print('Version: {}.{}'.format(*driver.get_version()))
    print('Extensions:')
    for extension in driver.get_extensions():
        print('  ', extension)


def sumlogdiag(A=None, out=None, name=None, **kwargs):
    """Computes the sum of the logarithms of the diagonal elements of a square matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* must be square with positive diagonal entries. We sum the natural
    logarithms of the diagonal elements, the result has shape (1,).

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

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

    Examples::

       Single matrix reduction
       A = [[1.0, 1.0], [1.0, 7.0]]
       sumlogdiag(A) = [1.9459]

       Batch matrix reduction
       A = [[[1.0, 1.0], [1.0, 7.0]], [[3.0, 0], [0, 17.0]]]
       sumlogdiag(A) = [1.9459, 3.9318]

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

    Parameters
    ----------
    A : NDArray
        Tensor of square matrices

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def flatten(items):
    """Removes one level of nesting from items.

    items can be any sequence, but flatten always returns a list.

    This function is ported from PyCogent (http://www.pycogent.org). PyCogent
    is a GPL project, but we obtained permission from the authors of this
    function to port it to the BIOM Format project (and keep it under BIOM's
    BSD license).
    """
    result = []
    for i in items:
        try:
            result.extend(i)
        except:
            result.append(i)
    return result


def mip_col_val(me, xid):
    """mip_col_val with transparent index mapping."""
    xid = me._colmap.map(xid) if xid else xid
    if xid > 0:
        return me._mip_col_val(xid)


def delete_expression(DomainName=None, ExpressionName=None):
    """
    Removes an `` Expression`` from the search domain. For more information, see Configuring Expressions in the Amazon CloudSearch Developer Guide .
    See also: AWS API Documentation

    :example: response = client.delete_expression(
        DomainName='string',
        ExpressionName='string'
    )

    :type DomainName: string
    :param DomainName: [REQUIRED]
            A string that represents the name of a domain. Domain names are unique across the domains owned by an account within an AWS region. Domain names start with a letter or number and can contain the following characters: a-z (lowercase), 0-9, and - (hyphen).

    :type ExpressionName: string
    :param ExpressionName: [REQUIRED]
            The name of the `` Expression`` to delete.

    :rtype: dict
    :return: {
        'Expression': {
            'Options': {
                'ExpressionName': 'string',
                'ExpressionValue': 'string'
            },
            'Status': {
                'CreationDate': datetime(2015, 1, 1),
                'UpdateDate': datetime(2015, 1, 1),
                'UpdateVersion': 123,
                'State': 'RequiresIndexDocuments'|'Processing'|'Active'|'FailedToValidate',
                'PendingDeletion': True|False
            }
        }
    }

    :returns:
    RequiresIndexDocuments : the option's latest value will not be deployed until  IndexDocuments has been called and indexing is complete.
    Processing : the option's latest value is in the process of being activated.
    Active : the option's latest value is completely deployed.
    FailedToValidate : the option value is not compatible with the domain's data and cannot be used to index the data. You must either modify the option value or update or remove the incompatible documents.

    """
    pass


@staticmethod
def set_to_print(signal):
    """Set the signal to print everything to the console.

        Args:
            signal (object): Generally a Signal object, but it can be anything. All of the Signal.API methods will print
                to the console.
        """
    signal.connecting = lambda : print('Connecting!')
    signal.connected = lambda : print('Connected!')
    signal.disconnecting = lambda : print('Disconnecting!')
    signal.disconnected = lambda : print('Disconnected!')
    signal.system_time_updated = lambda s: print('System Time:', s)
    signal.serial_number_updated = lambda s: print('Serial Number:', s)
    signal.signal_quality_updated = lambda s: print('Signal Quality (0-5):', s)
    signal.check_ring_updated = lambda t, s: print('Telephone Ring Indicator:',
        t, 'SBD Ring Indicator:', s)
    signal.message_received = lambda s: print('Message Received:', s)
    signal.message_receive_failed = lambda l, c, ck, cc: print(
        'Message Failed!', 'Length:', l, 'Content:', c, 'Checksum:', ck,
        'Calc Checksum:', cc)
    signal.message_transferred = lambda s: print('Message Transferred:', s)
    signal.message_transfer_failed = lambda s: print('Message Transfer Failed:'
        , s)
    signal.notification = lambda et, m, a: print('Notification:', et, m,
        repr(a))
    signal.command_finished = lambda cmd, v, c: print('Command Finished:',
        cmd, v, c)


def __call__(name, module):
    """Create an object with the given name in the given (dynamic) module.

        This will only be called once for each name. __module__ is the module
        that the object will live in, and name is the name of the object
        itself. That is,  the full dotted name of the generated object will be
        "{0}.{1}".format(module.__name__, name).

        This function should return a new object, or return None, in which
        case the dynamic module will generate an AttributeError. There is
        no need to mess with sys.modules or modify the 'module' object.
        """


def patternCode(node):
    """ Change pattern definition to pattern expr code:
		~ Append possible transforms.
		~ Flag it as recursive if ever.
		~ (Original format expr is already given in call).
		Note: This will be used for single pattern generation. """
    format, transform = node
    node.isRecursive = transform.isRecursive
    node.isName = format.tag == 'name'
    format, transform = format.value, transform.value
    node.format, node.transform = format, transform
    node.value = '%s%s' % (format, transform)


@conf
def cxx_add_flags(conf):
    """
	Adds CXXFLAGS / CPPFLAGS from os.environ to conf.env
	"""
    conf.add_os_flags('CPPFLAGS', dup=False)
    conf.add_os_flags('CXXFLAGS', dup=False)


def _rename(content):
    """Remove garbage from compound and reaction ids.

    Parameters
    ----------
    content : str

    Returns
    -------
    content : str
    """
    return content.replace('', '').replace('', '').replace('', ''
        ).replace('', '').replace('', '').replace('', ''
        ).replace('', '').replace('', '').replace('', ''
        ).replace('', '').replace('&', '').replace(';', '').replace('|',
        '')


def addrmap_expired(name):
    """
        An address has expired from the address map.
        """


def skin_radii_equalize():
    """Make skin radii of selected vertices equal on each axis

    """
    pass


def posixpath(path):
    """
    Replace backslashes with slashes and nothing else.
    """
    return path.replace('\\', '/')


@staticmethod
def second_order_score(y, mean, scale, shape, skewness):
    """ GAS Normal Update term potentially using second-order information - native Python function

        Parameters
        ----------
        y : float
            datapoint for the time series

        mean : float
            location parameter for the Normal distribution

        scale : float
            scale parameter for the Normal distribution

        shape : float
            tail thickness parameter for the Normal distribution

        skewness : float
            skewness parameter for the Normal distribution

        Returns
        ----------
        - Adjusted score of the Normal family
        """
    return y - mean


def V_Manning(Rh, S, n):
    """Predicts the average velocity of a flow across an open channel of
    hydraulic radius Rh and slope S, given the Manning roughness coefficient
    n.

    Flow rate is given by:

    .. math::
        V = \\frac{1}{n} R_h^{2/3} S^{0.5}

    Parameters
    ----------
    Rh : float
        Hydraulic radius of the channel, Flow Area/Wetted perimeter [m]
    S : float
        Slope of the channel, m/m [-]
    n : float
        Manning roughness coefficient [s/m^(1/3)]

    Returns
    -------
    V : float
        Average velocity of the channel [m/s]

    Notes
    -----
    This is equation is often given in imperial units multiplied by 1.49.

    Examples
    --------
    Example is from [2]_, matches.

    >>> V_Manning(0.2859, 0.005236, 0.03)
    1.0467781958118971

    References
    ----------
    .. [1] Blevins, Robert D. Applied Fluid Dynamics Handbook. New York, N.Y.:
       Van Nostrand Reinhold Co., 1984.
    .. [2] Cengel, Yunus, and John Cimbala. Fluid Mechanics: Fundamentals and
       Applications. Boston: McGraw Hill Higher Education, 2006.
    """
    return Rh ** (2 / 3.0) * S ** 0.5 / n


def bytes_str(num):
    """
    Converts bytes to a human readable format. For example: ::

        print_bytes(12345) returns '12.06 KB'
        print_bytes(123456789) returns '117.74 MB'

    Parameters
    ----------
    num : `int`
        The size in bytes.

    Raises
    ------
    ValueError
        num must be int >= 0
    """
    if not isinstance(num, int) or num < 0:
        raise ValueError('num must be int >= 0')
    for x in ['bytes', 'KB', 'MB', 'GB']:
        if num < 1024.0:
            return '{0:3.2f} {1:s}'.format(num, x)
        num /= 1024.0
    return '{0:3.2f} {1:s}'.format(num, 'TB')


def get_text_artifacts(text):
    """
    Get artifacts for the given file.

    Parameters
    ----------
    path : str
        File content to analyze

    Returns
    -------
    artifacts : dict
        Dictionary of file artifacts which should be
        considered while processing imports.
    """
    artifacts = {'sep': '\n'}
    lines = text.splitlines(True)
    if len(lines) > 1 and lines[0][-2:] == '\r\n':
        artifacts['sep'] = '\r\n'
    return artifacts


def add_push_parser(sub_parser):
    """
    Adds a sub-parser for the "push" sub-command to the parser provided.

    :param sub_parser: the parser to add to
    :type sub_parser: <class 'argparse.ArgumentParser'>
    """
    push_parser = sub_parser.add_parser('push', help='Push file to remote')
    push_parser.add_argument('remote', help='remote to push')
    push_parser.add_argument('-k', '--key', help=
        'key of file to push (from .surround/config.yaml)')


def _improve_answer_span(doc_tokens, input_start, input_end, tokenizer,
    orig_answer_text):
    """Returns tokenized answer spans that better match the annotated answer."""
    tok_answer_text = ' '.join(tokenizer.tokenize(orig_answer_text))
    for new_start in range(input_start, input_end + 1):
        for new_end in range(input_end, new_start - 1, -1):
            text_span = ' '.join(doc_tokens[new_start:new_end + 1])
            if text_span == tok_answer_text:
                return new_start, new_end
    return input_start, input_end


def p_branch_with_dot(p):
    """branch : OPEN DOT chain CLOSE"""
    p[0] = [('BRANCH', [('DOT',)] + p[3])]


def calculate_z_in_NAP(df, z_id):
    """
    Assign z_in with respect to NAP to each layer of a DataFrame.

    :param df: Original DataFrame.
    :param z_id: Elevation with respect to the NAP of my field.
    :return:  DataFrame with z_in_NAP column.
    """
    return df.assign(z_in_NAP=z_id - df['z_in'])


def handle_ends(index1, s, index2, t):
    """Updates intersection parameters if it is on the end of an edge.

    .. note::

       This is a helper used only by :meth:`.Triangle.intersect`.

    Does nothing if the intersection happens in the middle of two
    edges.

    If the intersection occurs at the end of the first curve,
    moves it to the beginning of the next edge. Similar for the
    second curve.

    This function is used as a pre-processing step before passing
    an intersection to :func:`classify_intersection`. There, only
    corners that **begin** an edge are considered, since that
    function is trying to determine which edge to **move forward** on.

    Args:
        index1 (int): The index (among 0, 1, 2) of the first edge in the
            intersection.
        s (float): The parameter along the first curve of the intersection.
        index2 (int): The index (among 0, 1, 2) of the second edge in the
            intersection.
        t (float): The parameter along the second curve of the intersection.

    Returns:
        Tuple[bool, bool, Tuple[int, float, int, float]]: A triple of:

        * flag indicating if the intersection is at the end of an edge
        * flag indicating if the intersection is a "corner"
        * 4-tuple of the "updated" values ``(index1, s, index2, t)``
    """
    edge_end = False
    if s == 1.0:
        s = 0.0
        index1 = (index1 + 1) % 3
        edge_end = True
    if t == 1.0:
        t = 0.0
        index2 = (index2 + 1) % 3
        edge_end = True
    is_corner = s == 0.0 or t == 0.0
    return edge_end, is_corner, (index1, s, index2, t)


def p_fields_multi(p):
    """fields : LBRACKET expr RBRACKET fields"""
    p[0] = [p[2]] + p[4]


def get_schema():
    """Schema structure of this resource

    :return: schema dictionary
    :rtype: dict
    """
    return {'schema': {'schema_version': {'type': 'integer', 'default': 1},
        'host': {'schema_version': 1, 'title': 'Host', 'comment':
        'The host concerned by the acknowledge.', 'type': 'objectid',
        'data_relation': {'resource': 'host', 'embeddable': True},
        'required': True}, 'service': {'schema_version': 1, 'title':
        'Service', 'comment': 'The service concerned by the acknowledge.',
        'type': 'objectid', 'data_relation': {'resource': 'service',
        'embeddable': True}, 'required': True, 'nullable': True}, 'user': {
        'schema_version': 1, 'title': 'User', 'comment':
        'The user concerned by the acknowledge.', 'type': 'objectid',
        'data_relation': {'resource': 'user', 'embeddable': True},
        'required': True}, 'comment': {'schema_version': 1, 'title':
        'Comment', 'comment':
        'The comment of the acknowledge action. Free text.', 'type':
        'string', 'default': ''}, 'processed': {'schema_version': 1,
        'title': 'Processed', 'comment':
        'The action has been set on the host/service by Alignak and it can be considered as effective if processed is True'
        , 'type': 'boolean', 'default': False}, '_realm': {'schema_version':
        1, 'title': 'Realm', 'comment':
        'Realm this element belongs to. Note that this property will always be forced to the value of the concerned host realm.'
        , 'type': 'objectid', 'data_relation': {'resource': 'realm',
        'embeddable': 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}}}}, 'schema_deleted': {}}


def dt_monthname(dt):
    """Return abbreviated month name for datetime.
    """
    return dt.strftime('%b')


def describe_job_queues(jobQueues=None, maxResults=None, nextToken=None):
    """
    Describes one or more of your job queues.
    See also: AWS API Documentation

    Examples
    This example describes the HighPriority job queue.
    Expected Output:

    :example: response = client.describe_job_queues(
        jobQueues=[
            'string',
        ],
        maxResults=123,
        nextToken='string'
    )

    :type jobQueues: list
    :param jobQueues: A list of up to 100 queue names or full queue Amazon Resource Name (ARN) entries.
            (string) --

    :type maxResults: integer
    :param maxResults: The maximum number of results returned by DescribeJobQueues in paginated output. When this parameter is used, DescribeJobQueues only returns maxResults results in a single page along with a nextToken response element. The remaining results of the initial request can be seen by sending another DescribeJobQueues request with the returned nextToken value. This value can be between 1 and 100. If this parameter is not used, then DescribeJobQueues returns up to 100 results and a nextToken value if applicable.

    :type nextToken: string
    :param nextToken: The nextToken value returned from a previous paginated DescribeJobQueues request where maxResults was used and the results exceeded the value of that parameter. Pagination continues from the end of the previous results that returned the nextToken value. This value is null when there are no more results to return.
            Note
            This token should be treated as an opaque identifier that is only used to retrieve the next items in a list and not for other programmatic purposes.

    :rtype: dict
    :return: {
        'jobQueues': [
            {
                'jobQueueName': 'string',
                'jobQueueArn': 'string',
                'state': 'ENABLED'|'DISABLED',
                'status': 'CREATING'|'UPDATING'|'DELETING'|'DELETED'|'VALID'|'INVALID',
                'statusReason': 'string',
                'priority': 123,
                'computeEnvironmentOrder': [
                    {
                        'order': 123,
                        'computeEnvironment': 'string'
                    },
                ]
            },
        ],
        'nextToken': 'string'
    }

    """
    pass


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

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


def groupnames():
    """Return iterable of all groupnames"""


def makePRFfile(data, MEMtype):
    """ makes Dysnomia .prf control file from Dysnomia GUI controls

    :param dict data: GSAS-II phase data
    :param int MEMtype: 1 for neutron data with negative scattering lengths
                        0 otherwise
    :returns str: name of Dysnomia control file
    """
    generalData = data['General']
    pName = generalData['Name'].replace(' ', '_')
    DysData = data['Dysnomia']
    prfName = pName + '.prf'
    prf = open(prfName, 'w')
    prf.write('$PREFERENCES\n')
    prf.write(pName + '.mem\n')
    prf.write(pName + '.out\n')
    prf.write(pName + '.pgrid\n')
    prf.write(pName + '.fba\n')
    prf.write(pName + '_eps.raw\n')
    prf.write('%d\n' % MEMtype)
    if DysData['DenStart'] == 'uniform':
        prf.write('0\n')
    else:
        prf.write('1\n')
    if DysData['Optimize'] == 'ZSPA':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.write('1\n')
    if DysData['Lagrange'][0] == 'user':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.write('%.4f %d\n' % (DysData['Lagrange'][1], DysData['wt pwr']))
    prf.write('%.3f\n' % DysData['Lagrange'][2])
    prf.write('%.2f\n' % DysData['E_factor'])
    prf.write('1\n')
    prf.write('0\n')
    prf.write('%d\n' % DysData['Ncyc'])
    prf.write('1\n')
    prf.write('1 0 0 0 0 0 0 0\n')
    if DysData['prior'] == 'uniform':
        prf.write('0\n')
    else:
        prf.write('1\n')
    prf.close()
    return prfName


def _non_present_values_to_zero(test_data):
    """
    Adds keys to the test data of one dataframe, if key was not present in that one but in one of the other datasets.

    :param test_data:
    :return:
    """
    for dataset1 in test_data:
        for dataset2 in test_data:
            for key in dataset1.keys():
                if key not in dataset2:
                    dataset2[key] = 0
    return test_data


def same_signature(a, b):
    """Check whether a arginfo and b arginfo are the same signature.

    Actual names of arguments may differ. Default arguments may be
    different.
    """
    a_args = set(a.args)
    b_args = set(b.args)
    return len(a_args) == len(b_args
        ) and a.varargs == b.varargs and a.varkw == b.varkw


def ReserveRate():
    """Valuation Reserve Rate per Sum Assured"""
    return None


def fix_column_name(val):
    """
    Fixes column names so that they are compatible with Numpy on
    Python 2.  Raises a ValueError exception if the column name
    contains Unicode characters, which can not reasonably be used as a
    column name.
    """
    if val is not None:
        try:
            val = str(val)
        except UnicodeEncodeError:
            raise
    return val


def distro_uri(distro_name):
    """
    Get distro URI of main ROS distribution files.

    :param distro_name: name of distro, e.g. 'diamondback'
    :returns: the SVN/HTTP URL of the specified distro.  This function should only be used
      with the main distros.
    """
    return (
        'http://svn.code.sf.net/p/ros-dry-releases/code/trunk/distros/%s.rosdistro'
         % distro_name)


def _plot_window(value, params):
    """Deal with horizontal shift of the viewport."""
    max_times = len(params['times']) - params['duration']
    if value > max_times:
        value = len(params['times']) - params['duration']
    if value < 0:
        value = 0
    if params['t_start'] != value:
        params['t_start'] = value
        params['hsel_patch'].set_x(value)
        params['plot_update_proj_callback'](params)


def get_units(filename: str, extension: str='.csv') ->tuple:
    """ Read the units from the raw signal file.

    :param filename: name of raw signal file, including path
    :param extension: extension of raw files (default '.csv')
    :rtype: tuple
    """
    with open(filename, 'r') as f:
        f.readline()
        u = f.readline()
        if extension == '.csv':
            units = u.replace('\n', '').split(',')
        else:
            units = u.replace('\r', '').split('\t')
    return units


def make_dupli_face():
    """Convert objects into dupli-face instanced

    """
    pass


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

        :param SfExternalInviteWarnDetails val:
        :rtype: EventDetails
        """
    return cls('sf_external_invite_warn_details', val)


def dynamic_topology_toggle():
    """Dynamic topology alters the mesh topology while sculpting

    """
    pass


def parse_model_table_file(path, f):
    """Parse a file as a list of model reactions

    Yields reactions IDs. Path can be given as a string or a context.
    """
    for line in f:
        line, _, comment = line.partition('#')
        line = line.strip()
        if line == '':
            continue
        yield line


def plus_or_dot(pieces):
    """Return a + if we don't already have one, else return a ."""
    if '+' in pieces.get('closest-tag', ''):
        return '.'
    return '+'


@classmethod
def from_csv(cls, connection, path, casout=None, **kwargs):
    """
        Create a CASTable from a CSV file

        Parameters
        ----------
        connection : :class:`CAS`
            The CAS connection to read the data into.
        path : string or file-like object
            The path, URL, or file-like object to get the data from.
        casout : string or :class:`CASTable`, optional
            The output table specification.  This includes the following parameters.
                name : string, optional
                    Name of the output CAS table.
                caslib : string, optional
                    CASLib for the output CAS table.
                label : string, optional
                    The label to apply to the output CAS table.
                promote : boolean, optional
                    If True, the output CAS table will be visible in all sessions.
                replace : boolean, optional
                    If True, the output CAS table will replace any existing CAS.
                    table with the same name.
        **kwargs : keyword arguments
            Keyword arguments to pass to :func:`pandas.read_csv`.

        See Also
        --------
        :meth:`CAS.read_csv`
        :func:`pandas.read_csv`

        Returns
        -------
        :class:`CASTable`

        """
    kwargs = kwargs.copy()
    kwargs.setdefault('index_col', 0)
    kwargs.setdefault('parse_dates', True)
    return connection.read_csv(path, casout=casout, **kwargs)


def rebuild_proxy():
    """Rebuild all selected proxies and timecode indices using the job system

    """
    pass


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

        :param WriteError val:
        :rtype: SaveCopyReferenceError
        """
    return cls('path', val)


def check_orientation(orientation):
    """
    Check the orientation argument (used by other package functions).

    Parameters
    ----------
    orientation : 'portrait' or 'landscape'
        the desired orientation of the output image

    Returns
    -------
    str

    Raises
    ------
    ValueError : invalid orientation argument provided

    """
    if orientation not in ['landscape', 'portrait', 'l', 'p']:
        raise ValueError('orientation must be landscape or portrait')
    if orientation == 'l':
        return 'landscape'
    elif orientation == 'p':
        return 'portrait'
    return orientation


def generic_find_fk_constraint_name(table, columns, referenced, insp):
    """Utility to find a foreign-key constraint name in alembic migrations"""
    for fk in insp.get_foreign_keys(table):
        if fk['referred_table'] == referenced and set(fk['referred_columns']
            ) == columns:
            return fk['name']


def maybeFlatten(items):
    """
    Iterate through top-level lists
    Flatten, only if the element is also a list

    [[1,2],3,[[4,5]]] -> [1,2,3,[4,5]]
    """
    new_list = []
    for elem in items:
        if isinstance(elem, list):
            new_list.extend(elem)
        else:
            new_list.append(elem)
    return new_list


def dnsamp2(x):
    """Downsamples by a factor 2 a 2D numpy array"""
    return x[::2, ::2]


def suspended():
    """
    A token value meaning that L{SiphonPendingValues} was suspended.
    """


def update_sql_injection_match_set(SqlInjectionMatchSetId=None, ChangeToken
    =None, Updates=None):
    """
    Inserts or deletes  SqlInjectionMatchTuple objects (filters) in a  SqlInjectionMatchSet . For each SqlInjectionMatchTuple object, you specify the following values:
    You use SqlInjectionMatchSet objects to specify which CloudFront requests you want to allow, block, or count. For example, if you're receiving requests that contain snippets of SQL code in the query string and you want to block the requests, you can create a SqlInjectionMatchSet with the applicable settings, and then configure AWS WAF to block the requests.
    To create and configure a SqlInjectionMatchSet , perform the following steps:
    For more information about how to use the AWS WAF API to allow or block HTTP requests, see the AWS WAF Developer Guide .
    See also: AWS API Documentation

    Examples
    The following example deletes a SqlInjectionMatchTuple object (filters) in a SQL injection match set with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5.
    Expected Output:

    :example: response = client.update_sql_injection_match_set(
        SqlInjectionMatchSetId='string',
        ChangeToken='string',
        Updates=[
            {
                'Action': 'INSERT'|'DELETE',
                'SqlInjectionMatchTuple': {
                    'FieldToMatch': {
                        'Type': 'URI'|'QUERY_STRING'|'HEADER'|'METHOD'|'BODY',
                        'Data': 'string'
                    },
                    'TextTransformation': 'NONE'|'COMPRESS_WHITE_SPACE'|'HTML_ENTITY_DECODE'|'LOWERCASE'|'CMD_LINE'|'URL_DECODE'
                }
            },
        ]
    )

    :type SqlInjectionMatchSetId: string
    :param SqlInjectionMatchSetId: [REQUIRED]
            The SqlInjectionMatchSetId of the SqlInjectionMatchSet that you want to update. SqlInjectionMatchSetId is returned by CreateSqlInjectionMatchSet and by ListSqlInjectionMatchSets .

    :type ChangeToken: string
    :param ChangeToken: [REQUIRED]
            The value returned by the most recent call to GetChangeToken .

    :type Updates: list
    :param Updates: [REQUIRED]
            An array of SqlInjectionMatchSetUpdate objects that you want to insert into or delete from a SqlInjectionMatchSet . For more information, see the applicable data types:
            SqlInjectionMatchSetUpdate : Contains Action and SqlInjectionMatchTuple
            SqlInjectionMatchTuple : Contains FieldToMatch and TextTransformation
            FieldToMatch : Contains Data and Type
            (dict) --Specifies the part of a web request that you want to inspect for snippets of malicious SQL code and indicates whether you want to add the specification to a SqlInjectionMatchSet or delete it from a SqlInjectionMatchSet .
            Action (string) -- [REQUIRED]Specify INSERT to add a SqlInjectionMatchSetUpdate to a SqlInjectionMatchSet . Use DELETE to remove a SqlInjectionMatchSetUpdate from a SqlInjectionMatchSet .
            SqlInjectionMatchTuple (dict) -- [REQUIRED]Specifies the part of a web request that you want AWS WAF to inspect for snippets of malicious SQL code and, if you want AWS WAF to inspect a header, the name of the header.
            FieldToMatch (dict) -- [REQUIRED]Specifies where in a web request to look for snippets of malicious SQL code.
            Type (string) -- [REQUIRED]The part of the web request that you want AWS WAF to search for a specified string. Parts of a request that you can search include the following:
            HEADER : A specified request header, for example, the value of the User-Agent or Referer header. If you choose HEADER for the type, specify the name of the header in Data .
            METHOD : The HTTP method, which indicated the type of operation that the request is asking the origin to perform. Amazon CloudFront supports the following methods: DELETE , GET , HEAD , OPTIONS , PATCH , POST , and PUT .
            QUERY_STRING : A query string, which is the part of a URL that appears after a ? character, if any.
            URI : The part of a web request that identifies a resource, for example, /images/daily-ad.jpg .
            BODY : The part of a request that contains any additional data that you want to send to your web server as the HTTP request body, such as data from a form. The request body immediately follows the request headers. Note that only the first 8192 bytes of the request body are forwarded to AWS WAF for inspection. To allow or block requests based on the length of the body, you can create a size constraint set. For more information, see CreateSizeConstraintSet .
            Data (string) --When the value of Type is HEADER , enter the name of the header that you want AWS WAF to search, for example, User-Agent or Referer . If the value of Type is any other value, omit Data .
            The name of the header is not case sensitive.
            TextTransformation (string) -- [REQUIRED]Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass AWS WAF. If you specify a transformation, AWS WAF performs the transformation on FieldToMatch before inspecting a request for a match.
            CMD_LINE
            When you're concerned that attackers are injecting an operating system commandline command and using unusual formatting to disguise some or all of the command, use this option to perform the following transformations:
            Delete the following characters: ' ' ^
            Delete spaces before the following characters: / (
            Replace the following characters with a space: , ;
            Replace multiple spaces with one space
            Convert uppercase letters (A-Z) to lowercase (a-z)
            COMPRESS_WHITE_SPACE
            Use this option to replace the following characters with a space character (decimal 32):
            f, formfeed, decimal 12
            t, tab, decimal 9
            n, newline, decimal 10
            r, carriage return, decimal 13
            v, vertical tab, decimal 11
            non-breaking space, decimal 160
            COMPRESS_WHITE_SPACE also replaces multiple spaces with one space.HTML_ENTITY_DECODE
            Use this option to replace HTML-encoded characters with unencoded characters. HTML_ENTITY_DECODE performs the following operations:
            Replaces (ampersand)quot; with '
            Replaces (ampersand)nbsp; with a non-breaking space, decimal 160
            Replaces (ampersand)lt; with a 'less than' symbol
            Replaces (ampersand)gt; with ````
            Replaces characters that are represented in hexadecimal format, (ampersand)#xhhhh; , with the corresponding characters
            Replaces characters that are represented in decimal format, (ampersand)#nnnn; , with the corresponding characters
            LOWERCASE
            Use this option to convert uppercase letters (A-Z) to lowercase (a-z).
            URL_DECODE
            Use this option to decode a URL-encoded value.
            NONE
            Specify NONE if you don't want to perform any text transformations.

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

    :returns:
    Submit a  CreateSqlInjectionMatchSet request.
    Use  GetChangeToken to get the change token that you provide in the ChangeToken parameter of an  UpdateIPSet request.
    Submit an UpdateSqlInjectionMatchSet request to specify the parts of web requests that you want AWS WAF to inspect for snippets of SQL code.

    """
    pass


@staticmethod
def get_show_name(uri):
    """Get show name from uri"""
    tokens = uri.split('_')
    channel = tokens[0]
    show = tokens[1]
    return channel + '_' + show


def epicyclic_gearing_3d_construction(c):
    """ construct the 3D-assembly-configurations of the epicyclic_gearing
  """
    epicyclic_gearing_3dconf1 = []
    epicyclic_gearing_3dconf1.append(('annulus_fig', 0.0, 0.0, 0.0, 0.0, c[
        'gear_profile_height'], 'i', 'xy', 0.0, 0.0, 0.0))
    epicyclic_gearing_3dconf1.append(('sun_fig', 0.0, 0.0, 0.0, 0.0, c[
        'gear_profile_height'], 'i', 'xy', 0.0, 0.0, 0.0))
    for i in range(c['planet_nb']):
        fig_id = 'planet_{:d}_fig'.format(i)
        epicyclic_gearing_3dconf1.append((fig_id, 0.0, 0.0, 0.0, 0.0, c[
            'gear_profile_height'], 'i', 'xy', 0.0, 0.0, 0.0))
    epicyclic_gearing_3dconf1.append(('front_planet_carrier_fig', 0.0, 0.0,
        0.0, 0.0, c['gear_profile_height'], 'i', 'xy', 0.0, 0.0, 7.0 * c[
        'gear_profile_height']))
    epicyclic_gearing_3dconf1.append(('rear_planet_carrier_fig', 0.0, 0.0,
        0.0, 0.0, c['gear_profile_height'], 'i', 'xy', 0.0, 0.0, -5.0 * c[
        'gear_profile_height']))
    for i in range(c['planet_nb']):
        fig_id = 'middle_planet_carrier_{:d}_fig'.format(i)
        epicyclic_gearing_3dconf1.append((fig_id, 0.0, 0.0, 0.0, 0.0, c[
            'gear_profile_height'], 'i', 'xy', 0.0, 0.0, 5.0 * c[
            'gear_profile_height']))
    r_assembly = {}
    r_slice = {}
    r_assembly['epicyclic_gearing_3dconf1'] = epicyclic_gearing_3dconf1
    hr = c['holder_radius']
    hh = c['gear_profile_height'] / 2.0
    r_slice['epicyclic_gearing_3dconf1'] = 2 * hr, 2 * hr, c[
        'gear_profile_height'], -hr, -hr, 0.0, [hh], [], []
    return r_assembly, r_slice


def prunecontainers(blocks, keep):
    """Prune unwanted containers.

    The blocks must have a 'type' field, i.e., they should have been
    run through findliteralblocks first.
    """
    pruned = []
    i = 0
    while i + 1 < len(blocks):
        if blocks[i][b'type'] == b'paragraph' and blocks[i][b'lines'][0
            ].startswith(b'.. container::'):
            indent = blocks[i][b'indent']
            adjustment = blocks[i + 1][b'indent'] - indent
            containertype = blocks[i][b'lines'][0][15:]
            prune = True
            for c in keep:
                if c in containertype.split(b'.'):
                    prune = False
            if prune:
                pruned.append(containertype)
            del blocks[i]
            j = i
            i -= 1
            while j < len(blocks) and blocks[j][b'indent'] > indent:
                if prune:
                    del blocks[j]
                else:
                    blocks[j][b'indent'] -= adjustment
                    j += 1
        i += 1
    return blocks, pruned


def _preprocess_line(raw_line):
    """Replaces tabs with spaces and removes trailing end of line markers.

    >>> _preprocess_line('foo \\r\\n\\n')
    'foo '

    """
    return raw_line.expandtabs(4).rstrip('\r\n')


def R_to_r(R):
    """
        Description: A function to scale down the autocorrelation function to a correlation function

        Input:
            :param R: Autocorrelation function of the signal
        Output:
            :return r: correlation function of the signal
            :rtype: ndarray

    """
    r = R / R[0]
    return r


def pop_unsupported_fields(instance_dict, model):
    """Pops unsupported fields from a dict that is to be used in get_or_create.

    Provides forward compatibility, so when Asana API includes a new field, things do not break
    until the model gains support for it. Known unsupported fields should be explicitly popped
    before reaching here.
    """
    supported_fields = []
    for field in model._meta.get_fields():
        if field.is_relation:
            if not field.many_to_many:
                supported_fields.append(field.name)
                if hasattr(field, 'attname'):
                    supported_fields.append(field.attname)
        else:
            supported_fields.append(field.name)
    unsupported_fields = instance_dict.keys() - supported_fields
    for field in unsupported_fields:
        instance_dict.pop(field)


def update_application_resource_lifecycle(ApplicationName=None,
    ResourceLifecycleConfig=None):
    """
    Modifies lifecycle settings for an application.
    See also: AWS API Documentation

    :example: response = client.update_application_resource_lifecycle(
        ApplicationName='string',
        ResourceLifecycleConfig={
            'ServiceRole': 'string',
            'VersionLifecycleConfig': {
                'MaxCountRule': {
                    'Enabled': True|False,
                    'MaxCount': 123,
                    'DeleteSourceFromS3': True|False
                },
                'MaxAgeRule': {
                    'Enabled': True|False,
                    'MaxAgeInDays': 123,
                    'DeleteSourceFromS3': True|False
                }
            }
        }
    )

    :type ApplicationName: string
    :param ApplicationName: [REQUIRED]
            The name of the application.

    :type ResourceLifecycleConfig: dict
    :param ResourceLifecycleConfig: [REQUIRED]
            The lifecycle configuration.
            ServiceRole (string) --The ARN of an IAM service role that Elastic Beanstalk has permission to assume.
            VersionLifecycleConfig (dict) --The application version lifecycle configuration.
            MaxCountRule (dict) --Specify a max count rule to restrict the number of application versions that are retained for an application.
            Enabled (boolean) -- [REQUIRED]Specify true to apply the rule, or false to disable it.
            MaxCount (integer) --Specify the maximum number of application versions to retain.
            DeleteSourceFromS3 (boolean) --Set to true to delete a version's source bundle from Amazon S3 when Elastic Beanstalk deletes the application version.
            MaxAgeRule (dict) --Specify a max age rule to restrict the length of time that application versions are retained for an application.
            Enabled (boolean) -- [REQUIRED]Specify true to apply the rule, or false to disable it.
            MaxAgeInDays (integer) --Specify the number of days to retain an application versions.
            DeleteSourceFromS3 (boolean) --Set to true to delete a version's source bundle from Amazon S3 when Elastic Beanstalk deletes the application version.

    :rtype: dict
    :return: {
        'ApplicationName': 'string',
        'ResourceLifecycleConfig': {
            'ServiceRole': 'string',
            'VersionLifecycleConfig': {
                'MaxCountRule': {
                    'Enabled': True|False,
                    'MaxCount': 123,
                    'DeleteSourceFromS3': True|False
                },
                'MaxAgeRule': {
                    'Enabled': True|False,
                    'MaxAgeInDays': 123,
                    'DeleteSourceFromS3': True|False
                }
            }
        }
    }

    """
    pass


def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
    0, ymax: int=0, extend: bool=True):
    """Select strips using border selection

    :param gesture_mode: Gesture Mode
    :type gesture_mode: int
    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def label_adapter(obj, request):
    """
    Adapter for rendering a :class:`skosprovider.skos.Label` to json.

    :param skosprovider.skos.Label obj: The label to be rendered.
    :rtype: :class:`dict`
    """
    return {'label': obj.label, 'type': obj.type, 'language': obj.language}


@staticmethod
def _is_in_result_dict(result_dict, dict_key, default_value):
    """
        Global function to check for the presence of an entry in a dictionary
        and give it a default value.
        :param result_dict: result_dict dictionary
        :param dict_key: entry (string)
        :param default_value:
        :return:
        """
    if dict_key not in result_dict or not result_dict[dict_key]:
        result_dict[dict_key] = default_value
    return result_dict[dict_key]


@staticmethod
def __normalize_neighbors(neighbors_weight_dict):
    """
        Normalizes the weights of the neighbors to the total weight
        of all neighbors.

        :param neighbors_weight_dict: dict, keys: node_pub_keys,
                                            values: weights
        :return: dict, keys: node_pub_keys, values: normalized weights
        """
    total_weight = 0
    normalized_dict = {}
    for n, nv in neighbors_weight_dict.items():
        total_weight += nv
    for n, nv in neighbors_weight_dict.items():
        normalized_dict[n] = float(nv) / total_weight
    return normalized_dict


def _GenerateCRCTable():
    """Generate a CRC-32 table.

        ZIP encryption uses the CRC32 one-byte primitive for scrambling some
        internal keys. We noticed that a direct implementation is faster than
        relying on binascii.crc32().
        """
    poly = 3988292384
    table = [0] * 256
    for i in range(256):
        crc = i
        for j in range(8):
            if crc & 1:
                crc = crc >> 1 & 2147483647 ^ poly
            else:
                crc = crc >> 1 & 2147483647
        table[i] = crc
    return table


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


def all_in(l1, l2):
    """Check if all element in l1 are in l2"""
    s1 = set(l1)
    s2 = set(l2)
    if s1.difference(s2):
        return False
    else:
        return True


def check_table(table):
    """
    Ensure the table is valid for converting to grid table.

    * The table must a list of lists
    * Each row must contain the same number of columns
    * The table must not be empty

    Parameters
    ----------
    table : list of lists of str
        The list of rows of strings to convert to a grid table

    Returns
    -------
    message : str
        If no problems are found, this message is empty, otherwise it
        tries to describe the problem that was found.
    """
    if not type(table) is list:
        return 'Table must be a list of lists'
    if len(table) == 0:
        return 'Table must contain at least one row and one column'
    for i in range(len(table)):
        if not type(table[i]) is list:
            return 'Table must be a list of lists'
        if not len(table[i]) == len(table[0]):
            """Each row must have the same number of columns"""
    return ''


@classmethod
def is_valid_object(cls, data):
    """
        Returns whether the data is a valid object for the class
        """
    return data['object'] == cls.stripe_class.OBJECT_NAME


@classmethod
def fromkeys(cls, iterable, value=None):
    """OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S
        and values equal to v (which defaults to None).

        """
    d = cls()
    for key in iterable:
        d[key] = value
    return d


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

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


@classmethod
def required_capabilities(cls):
    """Return a list of capabilities that we require the client to have."""
    return []


def _number_width(n):
    """Calculate the width in characters required to print a number

    For example, -1024 takes 5 characters. -0.034 takes 6 characters.
    """
    return len(str(n))


def describe_data_sources(FilterVariable=None, EQ=None, GT=None, LT=None,
    GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None,
    Limit=None):
    """
    Returns a list of DataSource that match the search criteria in the request.
    See also: AWS API Documentation

    :example: response = client.describe_data_sources(
        FilterVariable='CreatedAt'|'LastUpdatedAt'|'Status'|'Name'|'DataLocationS3'|'IAMUser',
        EQ='string',
        GT='string',
        LT='string',
        GE='string',
        LE='string',
        NE='string',
        Prefix='string',
        SortOrder='asc'|'dsc',
        NextToken='string',
        Limit=123
    )

    :type FilterVariable: string
    :param FilterVariable: Use one of the following variables to filter a list of DataSource :
            CreatedAt - Sets the search criteria to DataSource creation dates.
            Status - Sets the search criteria to DataSource statuses.
            Name - Sets the search criteria to the contents of DataSource **** Name .
            DataUri - Sets the search criteria to the URI of data files used to create the DataSource . The URI can identify either a file or an Amazon Simple Storage Service (Amazon S3) bucket or directory.
            IAMUser - Sets the search criteria to the user account that invoked the DataSource creation.

    :type EQ: string
    :param EQ: The equal to operator. The DataSource results will have FilterVariable values that exactly match the value specified with EQ .

    :type GT: string
    :param GT: The greater than operator. The DataSource results will have FilterVariable values that are greater than the value specified with GT .

    :type LT: string
    :param LT: The less than operator. The DataSource results will have FilterVariable values that are less than the value specified with LT .

    :type GE: string
    :param GE: The greater than or equal to operator. The DataSource results will have FilterVariable values that are greater than or equal to the value specified with GE .

    :type LE: string
    :param LE: The less than or equal to operator. The DataSource results will have FilterVariable values that are less than or equal to the value specified with LE .

    :type NE: string
    :param NE: The not equal to operator. The DataSource results will have FilterVariable values not equal to the value specified with NE .

    :type Prefix: string
    :param Prefix: A string that is found at the beginning of a variable, such as Name or Id .
            For example, a DataSource could have the Name 2014-09-09-HolidayGiftMailer . To search for this DataSource , select Name for the FilterVariable and any of the following strings for the Prefix :
            2014-09
            2014-09-09
            2014-09-09-Holiday

    :type SortOrder: string
    :param SortOrder: A two-value parameter that determines the sequence of the resulting list of DataSource .
            asc - Arranges the list in ascending order (A-Z, 0-9).
            dsc - Arranges the list in descending order (Z-A, 9-0).
            Results are sorted by FilterVariable .

    :type NextToken: string
    :param NextToken: The ID of the page in the paginated results.

    :type Limit: integer
    :param Limit: The maximum number of DataSource to include in the result.

    :rtype: dict
    :return: {
        'Results': [
            {
                'DataSourceId': 'string',
                'DataLocationS3': 'string',
                'DataRearrangement': 'string',
                'CreatedByIamUser': 'string',
                'CreatedAt': datetime(2015, 1, 1),
                'LastUpdatedAt': datetime(2015, 1, 1),
                'DataSizeInBytes': 123,
                'NumberOfFiles': 123,
                'Name': 'string',
                'Status': 'PENDING'|'INPROGRESS'|'FAILED'|'COMPLETED'|'DELETED',
                'Message': 'string',
                'RedshiftMetadata': {
                    'RedshiftDatabase': {
                        'DatabaseName': 'string',
                        'ClusterIdentifier': 'string'
                    },
                    'DatabaseUserName': 'string',
                    'SelectSqlQuery': 'string'
                },
                'RDSMetadata': {
                    'Database': {
                        'InstanceIdentifier': 'string',
                        'DatabaseName': 'string'
                    },
                    'DatabaseUserName': 'string',
                    'SelectSqlQuery': 'string',
                    'ResourceRole': 'string',
                    'ServiceRole': 'string',
                    'DataPipelineId': 'string'
                },
                'RoleARN': 'string',
                'ComputeStatistics': True|False,
                'ComputeTime': 123,
                'FinishedAt': datetime(2015, 1, 1),
                'StartedAt': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    :returns:
    PENDING - Amazon Machine Learning (Amazon ML) submitted a request to create a DataSource .
    INPROGRESS - The creation process is underway.
    FAILED - The request to create a DataSource did not run to completion. It is not usable.
    COMPLETED - The creation process completed successfully.
    DELETED - The DataSource is marked as deleted. It is not usable.

    """
    pass


def marc_clean_subfields(field, inplace=True):
    """
    Given a pymarc.field.Field, return a list of subfields, without empty
    values or perform modification in place.
    """
    cleaned_subfields = []
    it = iter(field.subfields)
    for code, value in zip(it, it):
        if not value:
            continue
        cleaned_subfields.append(code)
        cleaned_subfields.append(value)
    if inplace:
        field.subfields = cleaned_subfields
    else:
        return cleaned_subfields


@classmethod
def first_or_create(cls, **attributes):
    """
        Get the first record matching the attributes or create it.

        :param attributes: The instance attributes
        :type attributes: dict

        :return: The new instance
        :rtype: Model
        """
    instance = cls().new_query_without_scopes().where(attributes).first()
    if instance is not None:
        return instance
    return cls.create(**attributes)


def tabulate_locations(since, until):
    """Determines which animals are in which nests by date.

    In principle, it would be best to do this by using the database to
    generate a summary for day 0, then march through the subsequent days and
    use new events to generate new summaries. However, in practice it's not
    trivial to update this structure, so we're taking the lazy but probably
    more inefficient route of querying the database for each day. Consider
    the other option if it becomes too slow.

    """
    from birds.models import Animal, Event, Location, ADULT_ANIMAL_NAME
    from datetime import timedelta
    from collections import defaultdict, Counter
    repdate = since
    nests = Location.objects.filter(nest=True).order_by('name')
    dates = []
    data = {}
    while repdate <= until:
        locations = defaultdict(list)
        alive = Animal.living.exists(repdate)
        for event in Event.latest.filter(date__lte=repdate, animal__in=alive):
            if event.location.nest:
                locations[event.location].append(event.animal)
        data[repdate] = locations
        dates.append(repdate)
        repdate += timedelta(days=1)
    nest_data = []
    for nest in nests:
        days = []
        for date in dates:
            animals = data[date].get(nest, [])
            locdata = {'animals': defaultdict(list), 'counts': Counter()}
            for animal in animals:
                age_group = animal.age_group(date)
                locdata['animals'][age_group].append(animal)
                if age_group != ADULT_ANIMAL_NAME:
                    locdata['counts'][age_group] += 1
            days.append(locdata)
        nest_data.append({'location': nest, 'days': days})
    return dates, nest_data


def describe_stack_resources(StackName=None, LogicalResourceId=None,
    PhysicalResourceId=None):
    """
    Returns AWS resource descriptions for running and deleted stacks. If StackName is specified, all the associated resources that are part of the stack are returned. If PhysicalResourceId is specified, the associated resources of the stack that the resource belongs to are returned.
    For deleted stacks, DescribeStackResources returns resource information for up to 90 days after the stack has been deleted.
    You must specify either StackName or PhysicalResourceId , but not both. In addition, you can specify LogicalResourceId to filter the returned result. For more information about resources, the LogicalResourceId and PhysicalResourceId , go to the AWS CloudFormation User Guide .
    See also: AWS API Documentation

    :example: response = client.describe_stack_resources(
        StackName='string',
        LogicalResourceId='string',
        PhysicalResourceId='string'
    )

    :type StackName: string
    :param StackName: The name or the unique stack ID that is associated with the stack, which are not always interchangeable:
            Running stacks: You can specify either the stack's name or its unique stack ID.
            Deleted stacks: You must specify the unique stack ID.
            Default: There is no default value.
            Required: Conditional. If you do not specify StackName , you must specify PhysicalResourceId .

    :type LogicalResourceId: string
    :param LogicalResourceId: The logical name of the resource as specified in the template.
            Default: There is no default value.

    :type PhysicalResourceId: string
    :param PhysicalResourceId: The name or unique identifier that corresponds to a physical instance ID of a resource supported by AWS CloudFormation.
            For example, for an Amazon Elastic Compute Cloud (EC2) instance, PhysicalResourceId corresponds to the InstanceId . You can pass the EC2 InstanceId to DescribeStackResources to find which stack the instance belongs to and what other resources are part of the stack.
            Required: Conditional. If you do not specify PhysicalResourceId , you must specify StackName .
            Default: There is no default value.

    :rtype: dict
    :return: {
        'StackResources': [
            {
                'StackName': 'string',
                'StackId': 'string',
                'LogicalResourceId': 'string',
                'PhysicalResourceId': 'string',
                'ResourceType': 'string',
                'Timestamp': datetime(2015, 1, 1),
                'ResourceStatus': 'CREATE_IN_PROGRESS'|'CREATE_FAILED'|'CREATE_COMPLETE'|'DELETE_IN_PROGRESS'|'DELETE_FAILED'|'DELETE_COMPLETE'|'DELETE_SKIPPED'|'UPDATE_IN_PROGRESS'|'UPDATE_FAILED'|'UPDATE_COMPLETE',
                'ResourceStatusReason': 'string',
                'Description': 'string'
            },
        ]
    }

    """
    pass


@classmethod
def custom(cls, name, image_uri, instance_type, volume_size_in_gb, source=
    None, rule_to_invoke=None, container_local_output_path=None,
    s3_output_path=None, other_trials_s3_input_paths=None, rule_parameters=
    None, collections_to_save=None):
    """Initialize a ``Rule`` instance for a custom rule. The Rule
        analyzes tensors emitted during the training of a model and
        monitors conditions that are critical for the success of a
        training job.

        Args:
            name (str): The name of the debugger rule.
            image_uri (str): The URI of the image to be used by the debugger rule.
            instance_type (str): Type of EC2 instance to use, for example,
                'ml.c4.xlarge'.
            volume_size_in_gb (int): Size in GB of the EBS volume
                to use for storing data.
            source (str): A source file containing a rule to invoke. If provided,
                you must also provide rule_to_invoke. This can either be an S3 uri or
                a local path.
            rule_to_invoke (str): The name of the rule to invoke within the source.
                If provided, you must also provide source.
            container_local_output_path (str): The path in the container.
            s3_output_path (str): The location in S3 to store the output.
            other_trials_s3_input_paths ([str]): S3 input paths for other trials.
            rule_parameters (dict): A dictionary of parameters for the rule.
            collections_to_save ([sagemaker.debugger.CollectionConfig]): A list
                of CollectionConfig objects to be saved.

        Returns:
            sagemaker.debugger.Rule: The instance of the custom Rule.
        """
    if bool(source) ^ bool(rule_to_invoke):
        raise ValueError(
            'If you provide a source, you must also provide a rule to invoke (and vice versa).'
            )
    merged_rule_params = {}
    if source is not None and rule_to_invoke is not None:
        merged_rule_params['source_s3_uri'] = source
        merged_rule_params['rule_to_invoke'] = rule_to_invoke
    other_trials_params = {}
    if other_trials_s3_input_paths is not None:
        for index, s3_input_path in enumerate(other_trials_s3_input_paths):
            other_trials_params['other_trial_{}'.format(str(index))
                ] = s3_input_path
    merged_rule_params.update(other_trials_params)
    merged_rule_params.update(rule_parameters or {})
    return cls(name=name, image_uri=image_uri, instance_type=instance_type,
        container_local_output_path=container_local_output_path,
        s3_output_path=s3_output_path, volume_size_in_gb=volume_size_in_gb,
        rule_parameters=merged_rule_params, collections_to_save=
        collections_to_save or [])


def asint(value):
    """Coerce to integer."""
    if value is None:
        return value
    return int(value)


def project_opened(project):
    """This function is called after opening the project"""


@classmethod
def from_ratios(cls, Rxy=1, Ryz=1):
    """Return isochoric ``DefGrad`` tensor with axial stretches defined by strain ratios.
        Default is identity tensor.

        Keyword Args:
          Rxy, Ryz (float): strain ratios

        Example:
          >>> F = DefGrad.from_ratios(Rxy=2, Ryz=3)
          >>> F
          DefGrad:
          [[2.28942849 0.         0.        ]
           [0.         1.14471424 0.        ]
           [0.         0.         0.38157141]]

        """
    assert Rxy >= 1, 'Rxy must be greater than or equal to 1.'
    assert Ryz >= 1, 'Ryz must be greater than or equal to 1.'
    y = (Ryz / Rxy) ** (1 / 3)
    return cls.from_comp(xx=y * Rxy, yy=y, zz=y / Ryz)


def fixspacing(s):
    """ Try to make the output prettier by inserting blank lines
        in random places.
    """
    result = []
    indent = -1
    for line in s.splitlines():
        line = line.rstrip()
        if not line:
            continue
        indent, previndent = len(line) - len(line.lstrip()), indent
        if indent <= previndent and indent < 8:
            if indent < previndent or not indent:
                result.append('')
        result.append(line)
    result.append('')
    return '\n'.join(result)


@classmethod
def from_pem_file(cls, pem_file):
    """Read a single PEM-encoded certificate from a file.

        Args:
            pem_file: the certificate file.

        Returns:
            a Certificate object
        """
    with open(pem_file, 'rb') as pem_cert_file:
        return cls.from_pem(pem_cert_file.read())


@classmethod
def dump_all(cls):
    """write all objects of Model class to an array of python objects"""
    return cls.__schema__().dump(cls.query.all(), many=True).data


@staticmethod
def metadata_id(item):
    """Extracts the identifier from a GitLab item."""
    return str(item['id'])


def type_name(value):
    """return pretty-printed string containing name of value's type"""
    cls = value.__class__
    if cls.__module__ and cls.__module__ not in ['__builtin__', 'builtins']:
        return '%s.%s' % (cls.__module__, cls.__name__)
    elif value is None:
        return 'None'
    else:
        return cls.__name__


@classmethod
def version_list(cls, options):
    """Lists content-view's versions."""
    cls.command_sub = 'version list'
    if options is None:
        options = {}
    return cls.execute(cls._construct_command(options), output_format='csv')


def getAuthenticatedMember():
    """ Return the currently authenticated member object

        o If no valid credentials are passed in the request, return
          the Anonymous User.

        o Permission:  Public
        """


def add_marker_move(CLIP_OT_add_marker=None, TRANSFORM_OT_translate=None):
    """Add new marker and move it on movie

    :param CLIP_OT_add_marker: Add Marker, Place new marker at specified location
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def syevd(A=None, out=None, name=None, **kwargs):
    """Eigendecomposition for symmetric matrix.
    Input is a tensor *A* of dimension *n >= 2*.

    If *n=2*, *A* must be symmetric, of shape *(x, x)*. We compute the eigendecomposition,
    resulting in the orthonormal matrix *U* of eigenvectors, shape *(x, x)*, and the
    vector *L* of eigenvalues, shape *(x,)*, so that:

       *U* \\* *A* = *diag(L)* \\* *U*

    Here:

       *U* \\* *U*\\ :sup:`T` = *U*\\ :sup:`T` \\* *U* = *I*

    where *I* is the identity matrix. Also, *L(0) <= L(1) <= L(2) <= ...* (ascending order).

    If *n>2*, *syevd* is performed separately on the trailing two dimensions of *A* (batch
    mode). In this case, *U* has *n* dimensions like *A*, and *L* has *n-1* dimensions.

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

    .. note:: Derivatives for this operator are defined only if *A* is such that all its
              eigenvalues are distinct, and the eigengaps are not too small. If you need
              gradients, do not apply this operator to matrices with multiple eigenvalues.

    Examples::

       Single symmetric eigendecomposition
       A = [[1., 2.], [2., 4.]]
       U, L = syevd(A)
       U = [[0.89442719, -0.4472136],
            [0.4472136, 0.89442719]]
       L = [0., 5.]

       Batch symmetric eigendecomposition
       A = [[[1., 2.], [2., 4.]],
            [[1., 2.], [2., 5.]]]
       U, L = syevd(A)
       U = [[[0.89442719, -0.4472136],
             [0.4472136, 0.89442719]],
            [[0.92387953, -0.38268343],
             [0.38268343, 0.92387953]]]
       L = [[0., 5.],
            [0.17157288, 5.82842712]]

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

    Parameters
    ----------
    A : NDArray
        Tensor of input matrices to be factorized

    out : NDArray, optional
        The output NDArray to hold the result.

    Returns
    -------
    out : NDArray or list of NDArrays
        The output of this function.
    """
    return 0,


def create_controller_js(stream, module):
    """
    Creates AngularJS controller from module
    :param stream:
    :param module:
    :return:
    """
    from wutu.util import get_implemented_methods
    from wutu.compiler.grammar import Provider, Function, SimpleDeclare
    stream.write("wutu.controller('{0}Controller', ".format(module.
        __class__.__name__))
    service = Provider('{0}Service'.format(module.__class__.__name__))
    scope = Provider('$scope')
    methods = get_implemented_methods(module)
    entity_name = '{0}_list'.format(module.get_entity_name())
    params = module.get_identifier()
    post_params = params + ('data',)
    put_params = 'data',
    scope[entity_name] = service.list()
    scope.refresh = Function(None, body=[SimpleDeclare(scope[entity_name].
        compile(), service.list())])
    scope['get_{0}'.format(module.get_entity_name())] = Function(params,
        returns=service.get(*params))
    scope['create_{0}'.format(module.get_entity_name())] = Function(put_params,
        body=[service.put(*put_params), scope.refresh()])
    scope['update_{0}'.format(module.get_entity_name())] = Function(post_params
        , body=[service.post(*post_params), scope.refresh()])
    scope['remove_{0}'.format(module.get_entity_name())] = Function(params,
        body=[service.delete(*params), scope.refresh()])
    impl = Function([scope.name, service.name], body=scope.assignments)
    stream.write(impl.compile())
    stream.write(');')


def _ri2ro(obj):
    """ Dummy function for ri2ro.

    This function will convert rpy2.rinterface (ri) low-level objects
    into rpy2.robjects (ro) higher-level objects.
    """
    raise NotImplementedError(
        "Conversion 'ri2ro' not defined for objects of type '%s'" % str(
        type(obj)))


def _read_star_block(lines, iline, line0, log, debug=False):
    """
    because this uses file streaming, there are 30,000 places where a try except
    block is needed, so this should probably be used all over.
    """
    data_lines = []
    try:
        iline += 1
        line0 = lines[iline].strip().lower()
        while not line0.startswith('*'):
            data_lines.append(line0.split(','))
            iline += 1
            line0 = lines[iline].strip().lower()
        iline -= 1
        line0 = lines[iline].strip().lower()
    except IndexError:
        pass
    if debug:
        for line in data_lines:
            log.debug(line)
    return data_lines, iline, line0


def investigate_nan_columns(data, verbose=False) ->None:
    """
    Prints an analysis of the nans in the dataframe
    Verbose is to actually show the database
    """
    col_dict = {}
    na_df = data.isna()
    total_size = na_df.shape[0]
    for col in na_df:
        a = na_df[col].value_counts()
        if False not in a.keys():
            col_dict[col] = 1.0
        elif True not in a.keys():
            pass
        else:
            col_dict[col] = a[True] / total_size
    print(f'{col_dict}')
    if verbose:
        for col in col_dict:
            print(f'For {col}\n {data[data[col].isnull()]}')
    return


def make_compat_bytes(in_str):
    """In Py2, does nothing. In Py3, converts to bytes, encoding to unicode."""
    assert isinstance(in_str, str), str(type(in_str))
    return in_str.encode()


@classmethod
def _get_inline_format_as_tuple(cls, text: str) ->list:
    """
        In case some inline formats have been applied we need to get a list of
        tuples indicating the formats to be applied via flags and the text
        where the format should be applied, for instance, if the text is:
        "[rB]Some@ Te[H]xt@"
        We'll get the list [('Some', 'rB), (' Te', None), ('xt', 'H')]
        """
    prev = ''
    last_special_char = None
    list_of_formats = []
    section_text = []
    section_flags = []
    current_action = cls.START_FORMAT
    counter = 0
    close_section = False
    for char in text:
        is_special = cls._define_char(prev, char)
        if is_special:
            action = cls._check_special_char_position(last_special_char, char)
            if action == cls.ESCAPE_CHAR:
                if current_action == cls.START_FLAGS:
                    section_flags.append(char)
                elif current_action == cls.START_FORMAT:
                    section_text.append(char)
            else:
                current_action = action
                if current_action == cls.END_FORMAT:
                    current_action = cls.START_FORMAT
                    close_section = True
                if last_special_char in [cls.end_format_char, None]:
                    current_action = cls.START_FLAGS
                    close_section = True
                last_special_char = char
        elif current_action == cls.START_FLAGS:
            section_flags.append(char)
        elif current_action == cls.START_FORMAT:
            section_text.append(char)
        prev = char
        counter += 1
        if counter == len(text) or close_section:
            list_of_formats.append((''.join(section_text), ''.join(
                section_flags) if len(section_flags) > 0 else None))
            section_text = []
            section_flags = []
            close_section = False
    return list_of_formats


def object_load_bmesh(bm: 'bmesh.types.BMesh', scene: 'bpy.types.Scene',
    object: 'bpy.types.Object'):
    """Loads a bmesh into an object/mesh. This is a “private” bmop.

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param scene: Undocumented.
    :type scene: 'bpy.types.Scene'
    :param object: Undocumented.
    :type object: 'bpy.types.Object'
    """
    pass


@classmethod
def _is_func_rational(cls, poly, func):
    """Check if a lambda is areational function."""
    var, expr = func.variables[0], func.expr
    return expr.is_rational_function(var)


def wordcount(text):
    """ Return the number of words in the given text. """
    if type(text) == str:
        return len(text.split(' '))
    elif type(text) == list:
        return len(text)
    else:
        raise ValueError(
            'Text to count words for must be of type str or of type list.')


def _resolve(name):
    """Resolve a dotted name to a global object."""
    name = name.split('.')
    used = name.pop(0)
    found = __import__(used)
    for n in name:
        used = used + '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            __import__(used)
            found = getattr(found, n)
    return found


@staticmethod
def extension():
    """Return most common file extension for format."""
    return 'csv'


def str_type(img):
    """
    Returns a string with image type.
    """
    return str(img.dtype)


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

        :param MemberPermanentlyDeleteAccountContentsType val:
        :rtype: EventType
        """
    return cls('member_permanently_delete_account_contents', val)


@classmethod
def ce_kill(cls, srv, *options, **kwargs):
    """
        Calls a remote proxy node to start the compute environment.
        """
    srvd = cls._ocean._get(srv)
    srchash = cls._ocean.freeze_hash(srv)
    assert srvd['type'] == 'environment'
    cls._proxy_ssh(srvd['ce-proxies'], srvd['ce-user'],
        'OCEAN_CKSUM=%s OCEAN_PATH=~/ocean OCEAN_MANIFEST=~/ocean/manifest/manifest.json DOCKER_HOST=%s ocean kill %s'
         % (srchash, srvd['ce-docker'], srv))


def do_batch(value, linecount, fill_with=None):
    """
    A filter that batches items. It works pretty much like `slice`
    just the other way round. It returns a list of lists with the
    given number of items. If you provide a second parameter this
    is used to fill up missing items. See this example:

    .. sourcecode:: html+jinja

        {%- for row in items|batch(3, ' ') %}

          {%- for column in row %}
            {{ column }}
          {%- endfor %}

        {%- endfor %}

    """
    tmp = []
    for item in value:
        if len(tmp) == linecount:
            yield tmp
            tmp = []
        tmp.append(item)
    if tmp:
        if fill_with is not None and len(tmp) < linecount:
            tmp += [fill_with] * (linecount - len(tmp))
        yield tmp


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


def determine_approximant_to_use(template_params):
    """Decision tree to determine the which approximant to use

    Parameters
    ----------
    template_params: dict
        dictionary of the best matching template parameters

    Returns
    -------
    approximant: str
        the approximant name
    """
    mass_ratio = float(template_params['mass_1']) / float(template_params[
        'mass_2'])
    if mass_ratio < 18:
        approximant = 'IMRPhenomD'
    else:
        approximant = 'SEOBNRv4'
    return approximant


def p_varargslist_7(p):
    """varargslist : fpdef varargslist_star COMMA STAR NAME COMMA DOUBLESTAR NAME"""
    p[2].args.insert(0, p[1])
    p[2].vararg = p[5][0]
    p[2].kwarg = p[8][0]
    p[0] = p[2]


def smart_split(line):
    """
    split string like:
    "C C 0.0033 0.0016 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4'"
    in the list like:
    ['C', 'C', '0.0033', '0.0016', 'International Tables Vol C Tables 4.2.6.8 and 6.1.1.4']
    """
    flag_in = False
    l_val, val = [], []
    for hh in line.strip():
        if (hh == ' ') & (not flag_in):
            if val != []:
                l_val.append(''.join(val))
            val = []
        elif (hh == ' ') & flag_in:
            val.append(hh)
        elif (hh == "'") | (hh == '"'):
            flag_in = not flag_in
        else:
            val.append(hh)
    if val != []:
        l_val.append(''.join(val))
    return l_val


def _get_palette_bytes(im):
    """
    Gets the palette for inclusion in the gif header

    :param im: Image object
    :returns: Bytes, len<=768 suitable for inclusion in gif header
    """
    return im.palette.palette


def expand_args(**args_to_expand):
    """Expand the given lists into the length of the layers.

    This is used as a convenience so that the user does not need to specify the
    complete list of parameters for model initialization.
    IE the user can just specify one parameter and this function will expand it
    """
    layers = args_to_expand['layers']
    try:
        items = args_to_expand.iteritems()
    except AttributeError:
        items = args_to_expand.items()
    for key, val in items:
        if isinstance(val, list) and len(val) != len(layers):
            args_to_expand[key] = [val[0] for _ in layers]
    return args_to_expand


@classmethod
def is_registered_class(manager, cls):
    """ is_registered_class(cls)

        Returns True if the given class is registered.

        """
    return cls in manager._registered_classes.values()


def clone_actions(subparser, time_args):
    """Uploading Arguments.

    :param subparser:
    """
    clone = subparser.add_parser('clone', parents=[time_args], help=
        'Clone Objects from one container to another.')
    clone.set_defaults(clone=True)
    clone.add_argument('-sc', '--source-container', metavar='[CONTAINER]',
        help='Target Container.', required=True, default=None)
    clone.add_argument('-tc', '--target-container', metavar='[CONTAINER]',
        help='Target Container.', required=True, default=None)
    clone.add_argument('-tr', '--target-region', metavar='[REGION]', help=
        'Target Container.', required=True, default=None)
    clone.add_argument('--target-snet', action='store_true', help=
        'Use Service Net to Stream the Objects.', default=False)
    clone.add_argument('--clone-headers', action='store_true', help=
        'Query the source object for headers and restore them on the target.',
        default=False)
    clone.add_argument('--save-newer', action='store_true', help=
        'Check to see if the target "last_modified" time is newer than the source. If "True" upload is skipped.'
        , default=False)
    clone.add_argument('--add-only', action='store_true', help=
        "Clone the object only if it doesn't exist in the target container.",
        default=False)


def copy():
    """Copies the current pose of the selected bones to copy/paste buffer

    """
    pass


def to_string():
    """Return a string of printable ASCII characters, suitable for
        passing into init_from_string."""


def parse_pathway_names(pathway_names_df):
    """Parse the pathway name dataframe.

    :param pandas.DataFrame pathway_names_df: Pathway hierarchy as dataframe
    :rtype: dict
    :return Object representation dictionary (reactome_id: (name, species))
    :rtype: set
    :return all species names
    """
    pathways = {}
    species_set = set()
    for _, (reactome_id, name, species) in pathway_names_df.iterrows():
        pathways[reactome_id] = name.strip(), species
        species_set.add(species)
    return pathways, species_set


def is_reference_target(resource, rtype, label):
    """ Return true if the resource has this rtype with this label """
    prop = resource.props.references.get(rtype, False)
    if prop:
        return label in prop


def is_iterable(obj):
    """
    Are we being asked to look up a list of things, instead of a single thing?
    We check for the `__iter__` attribute so that this can cover types that
    don't have to be known by this module, such as NumPy arrays.

    Strings, however, should be considered as atomic values to look up, not
    iterables. The same goes for tuples, since they are immutable and therefore
    valid entries.

    We don't need to check for the Python 2 `unicode` type, because it doesn't
    have an `__iter__` attribute anyway.
    """
    return hasattr(obj, '__iter__') and not isinstance(obj, str
        ) and not isinstance(obj, tuple)


def readprofile(repo, profile, changeid):
    """Resolve the raw content of a sparse profile file."""
    return repo.filectx(profile, changeid=changeid).data()


def delete_track():
    """Delete selected tracks

    """
    pass


def snatch(n):
    """
        last `n` things of incoming things

        @param n: number of things
        """


def _get_surface_index(layers, n_layers, surface_index):
    """Get index within each stack of the layer at the topographic surface.

    Parameters
    ----------
    layers : ndarray of shape `(n_layers, n_nodes)`
        Array of layer thicknesses. This array is the datastructure that
        contains all allocated layers, active or inactive.
    n_layers : int
        Number of active layers.
    surface_index : ndarray of shape `(n_nodes, )`

    Examples
    --------
    >>> import numpy as np
    >>> from landlab.layers.eventlayers import (_deposit_or_erode,
    ...                                         _get_surface_index)

    >>> layers = np.full((5, 3), 1.)
    >>> dz = np.array([-1., -2., -3.])

    Note here, if you are very confused by the use of ``_deposit_or_erode``
    we recommend you read the docstring associated with that function.

    >>> _deposit_or_erode(layers, 5, dz)
    >>> layers
    array([[ 1.,  1.,  1.],
           [ 1.,  1.,  1.],
           [ 1.,  1.,  0.],
           [ 1.,  0.,  0.],
           [ 0.,  0.,  0.]])

    >>> surface_index = np.empty(3, dtype=int)
    >>> _get_surface_index(layers, 5, surface_index)
    >>> surface_index
    array([3, 2, 1])
    """
    from .ext.eventlayers import get_surface_index
    layers = layers.reshape((layers.shape[0], -1))
    get_surface_index(layers, n_layers, surface_index)


def order():
    """associate `order_date`, remove items without active client order items and close the order.

    After the order has been closed, it can no longer be changed.
    This extends to client order items which are associated with this order.
    """