def get_beta_sigma_from_aligned_spins(eta, spin1z, spin2z):
    """
    Calculate the various PN spin combinations from the masses and spins.
    See <http://arxiv.org/pdf/0810.5336v3.pdf>.

    Parameters
    -----------
    eta : float or numpy.array
        Symmetric mass ratio of the input system(s)
    spin1z : float or numpy.array
        Spin(s) parallel to the orbit of the heaviest body(ies)
    spin2z : float or numpy.array
        Spin(s) parallel to the orbit of the smallest body(ies)

    Returns
    --------
    beta : float or numpy.array
        The 1.5PN spin combination
    sigma : float or numpy.array
        The 2PN spin combination
    gamma : float or numpy.array
        The 2.5PN spin combination
    chis : float or numpy.array
        (spin1z + spin2z) / 2.
    """
    chiS = 0.5 * (spin1z + spin2z)
    chiA = 0.5 * (spin1z - spin2z)
    delta = (1 - 4 * eta) ** 0.5
    spinspin = spin1z * spin2z
    beta = (113.0 / 12.0 - 19.0 / 3.0 * eta) * chiS
    beta += 113.0 / 12.0 * delta * chiA
    sigma = eta / 48.0 * (474 * spinspin)
    sigma += (1 - 2 * eta) * (81.0 / 16.0 * (chiS * chiS + chiA * chiA))
    sigma += delta * (81.0 / 8.0 * (chiS * chiA))
    gamma = (732985.0 / 2268.0 - 24260.0 / 81.0 * eta - 340.0 / 9.0 * eta * eta
        ) * chiS
    gamma += (732985.0 / 2268.0 + 140.0 / 9.0 * eta) * delta * chiA
    return beta, sigma, gamma


def data(w=3, h=2, s=0.5):
    """ Create flowchart data or I/O block (parallelogram)

        Parameters
        ----------
        w: float
            Width of box
        h: float
            Height of box
        s: float
            Slant of parallelogram

        Anchors: N, S, E, W
    """
    elem = {'name': 'FLOWDATA', 'extend': False, 'lblloc': 'center',
        'lblofst': 0, 'theta': -90}
    elem['paths'] = [[[0, 0], [0, w / 2 + s / 2], [h, w / 2 - s / 2], [h, -
        w / 2 - s / 2], [0, -w / 2 + s / 2], [0, 0]]]
    elem['anchors'] = {'W': [h / 2, -w / 2], 'E': [h / 2, w / 2], 'S': [h,
        0], 'N': [0, 0]}
    elem['drop'] = [h, 0]
    return elem


def ljust(text, width, fillchar=' '):
    """
    Creates a copy of ``text`` left justified in a string of length ``width``.

    Padding is done using the specified ``fillchar`` (default is an ASCII space). The original
    string is returned if ``width`` is less than or equal to len(s).

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

    :return: A copy of ``text`` left justified in a string of length ``width``.
    :rtype:  ``str``
    """
    assert isinstance(text, str), '%s is not a string' % text
    return text.ljust(width, fillchar)


def def_grads(prims):
    """ Define gradients of primitives """
    prims('random').def_grad_zero()
    prims('randn').def_grad_zero()


@staticmethod
def positional_to_model(value):
    """Converts a positional argument to a model value"""
    return value


def get_nth(li, i):
    """if i < len(l) returns l[i] else l[-1]"""
    try:
        return li[min(i, len(li) - 1)]
    except Exception:
        return li


def write_scene_list(history_db, scene_list):
    """writes to scene list table"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(history_db)
    cur = conn.cursor()
    insert_line = 'INSERT INTO "SceneList" (Scene) VALUES (?)'
    cur.executemany(insert_line, scene_list)
    conn.commit()
    conn.close()


def clean_whitespace(string, compact=False):
    """Return string with compressed whitespace."""
    for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '),
        ('  ', ' ')):
        string = string.replace(a, b)
    if compact:
        for a, b in (('\n', ' '), ('[ ', '['), ('  ', ' '), ('  ', ' '), (
            '  ', ' ')):
            string = string.replace(a, b)
    return string.strip()


def _get_bw_summary(coords, annotation):
    """Return summary of BigWig scores in an interval
    """
    chrom, start, end = coords
    try:
        return annotation.summarize(str(chrom), start, end, end - start
            ).min_val[0]
    except AttributeError:
        return None


def printUsage():
    """
    Print program usage information.
    :return:
    """
    print('USAGE:')
    print('python   wordsearch.py   <word-list-file>   <cols>   <rows>')


def ductility(delta_current, delta_y):
    """
    Computes the ductility for a given displacement and yield.
    :param delta_current: current displacement
    :param delta_y: yield displacement
    :return:
    """
    return delta_current / delta_y


@classmethod
def get(cls, resource_id=None, parent_id=None, grandparent_id=None):
    """"Retrieves the required resource."""
    return cls._get(resource_id, parent_id, grandparent_id)


@classmethod
def _substitute_xml_entity(cls, matchobj):
    """Used with a regular expression to substitute the
        appropriate XML entity for a special character."""
    entity = cls.CHARACTER_TO_XML_ENTITY[matchobj.group(0)]
    return '&%s;' % entity


@classmethod
def register_server_prober(klass, prober):
    """Register a control format prober for client-server environments.

        These probers will be used before ones registered with
        register_prober.  This gives implementations that decide to the
        chance to grab it before anything looks at the contents of the format
        file.
        """
    klass._server_probers.append(prober)


def iterexcept(call, exception, start=None):
    """
        call a function repeatedly until an exception is raised

        Converts a call-until-exception interface to an iterator interface.
        Like `iter(call, sentinel)` but uses an exception instead of a sentinel
        to end the loop.

        Raymond Hettinger, Python Cookbook recipe # 577155
        """


def scroll_left(deltax: int=0, deltay: int=0):
    """Scroll the view left

    :param deltax: Delta X
    :type deltax: int
    :param deltay: Delta Y
    :type deltay: int
    """
    pass


def t_UNIT(t):
    """cm|pt|ex|mm|in|em|%(?=x\\d|$)"""
    return t


def grant_permission_to_principal_no_inherit(role_id, principal_id):
    """Assign the role to the principal without local inherit."""


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 get_postgres_user(users, host, port, database):
    """
    For a list of host/port/database/user combinations, return the username that matches the
    host, port, database and user.

    :param users: list containing a sequence of AT LEAST (host, port, database, username)
    :param host: The hostname to match
    :param port: The port to match
    :param database: The database to match
    :return: A username or None
    """
    for user in users:
        if user[0].lower() == host.lower() and user[1].lower() == port.lower(
            ) and user[2].lower() == database.lower():
            return user[3]
    return None


@classmethod
def enable_timing(cls, do_time, max_depth=10000):
    """
        Enable (or disable) timing for all timers not already started.

        Arguments:
            - 'do_time': Boolean to enable or disable timing.
            - 'max_depth': Maximum depth of the timer stack. Timers beyond max_depth will not start.
                           Defaults to 10000
        """
    cls.timing_enabled = do_time
    if do_time:
        cls.max_depth = max_depth


def describe_scheduled_instance_availability(DryRun=None, Recurrence=None,
    FirstSlotStartTimeRange=None, MinSlotDurationInHours=None,
    MaxSlotDurationInHours=None, NextToken=None, MaxResults=None, Filters=None
    ):
    """
    Finds available schedules that meet the specified criteria.
    You can search for an available schedule no more than 3 months in advance. You must meet the minimum required duration of 1,200 hours per year. For example, the minimum daily schedule is 4 hours, the minimum weekly schedule is 24 hours, and the minimum monthly schedule is 100 hours.
    After you find a schedule that meets your needs, call  PurchaseScheduledInstances to purchase Scheduled Instances with that schedule.
    See also: AWS API Documentation

    Examples
    This example describes a schedule that occurs every week on Sunday, starting on the specified date. Note that the output contains a single schedule as an example.
    Expected Output:

    :example: response = client.describe_scheduled_instance_availability(
        DryRun=True|False,
        Recurrence={
            'Frequency': 'string',
            'Interval': 123,
            'OccurrenceDays': [
                123,
            ],
            'OccurrenceRelativeToEnd': True|False,
            'OccurrenceUnit': 'string'
        },
        FirstSlotStartTimeRange={
            'EarliestTime': datetime(2015, 1, 1),
            'LatestTime': datetime(2015, 1, 1)
        },
        MinSlotDurationInHours=123,
        MaxSlotDurationInHours=123,
        NextToken='string',
        MaxResults=123,
        Filters=[
            {
                'Name': 'string',
                'Values': [
                    'string',
                ]
            },
        ]
    )

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

    :type Recurrence: dict
    :param Recurrence: [REQUIRED]
            The schedule recurrence.
            Frequency (string) --The frequency (Daily , Weekly , or Monthly ).
            Interval (integer) --The interval quantity. The interval unit depends on the value of Frequency . For example, every 2 weeks or every 2 months.
            OccurrenceDays (list) --The days. For a monthly schedule, this is one or more days of the month (1-31). For a weekly schedule, this is one or more days of the week (1-7, where 1 is Sunday). You can't specify this value with a daily schedule. If the occurrence is relative to the end of the month, you can specify only a single day.
            (integer) --
            OccurrenceRelativeToEnd (boolean) --Indicates whether the occurrence is relative to the end of the specified week or month. You can't specify this value with a daily schedule.
            OccurrenceUnit (string) --The unit for OccurrenceDays (DayOfWeek or DayOfMonth ). This value is required for a monthly schedule. You can't specify DayOfWeek with a weekly schedule. You can't specify this value with a daily schedule.

    :type FirstSlotStartTimeRange: dict
    :param FirstSlotStartTimeRange: [REQUIRED]
            The time period for the first schedule to start.
            EarliestTime (datetime) -- [REQUIRED]The earliest date and time, in UTC, for the Scheduled Instance to start.
            LatestTime (datetime) -- [REQUIRED]The latest date and time, in UTC, for the Scheduled Instance to start. This value must be later than or equal to the earliest date and at most three months in the future.

    :type MinSlotDurationInHours: integer
    :param MinSlotDurationInHours: The minimum available duration, in hours. The minimum required duration is 1,200 hours per year. For example, the minimum daily schedule is 4 hours, the minimum weekly schedule is 24 hours, and the minimum monthly schedule is 100 hours.

    :type MaxSlotDurationInHours: integer
    :param MaxSlotDurationInHours: The maximum available duration, in hours. This value must be greater than MinSlotDurationInHours and less than 1,720.

    :type NextToken: string
    :param NextToken: The token for the next set of results.

    :type MaxResults: integer
    :param MaxResults: The maximum number of results to return in a single call. This value can be between 5 and 300. The default value is 300. To retrieve the remaining results, make another call with the returned NextToken value.

    :type Filters: list
    :param Filters: One or more filters.
            availability-zone - The Availability Zone (for example, us-west-2a ).
            instance-type - The instance type (for example, c4.large ).
            network-platform - The network platform (EC2-Classic or EC2-VPC ).
            platform - The platform (Linux/UNIX or Windows ).
            (dict) --A filter name and value pair that is used to return a more specific list of results. Filters can be used to match a set of resources by various criteria, such as tags, attributes, or IDs.
            Name (string) --The name of the filter. Filter names are case-sensitive.
            Values (list) --One or more filter values. Filter values are case-sensitive.
            (string) --

    :rtype: dict
    :return: {
        'NextToken': 'string',
        'ScheduledInstanceAvailabilitySet': [
            {
                'InstanceType': 'string',
                'Platform': 'string',
                'NetworkPlatform': 'string',
                'AvailabilityZone': 'string',
                'PurchaseToken': 'string',
                'SlotDurationInHours': 123,
                'Recurrence': {
                    'Frequency': 'string',
                    'Interval': 123,
                    'OccurrenceDaySet': [
                        123,
                    ],
                    'OccurrenceRelativeToEnd': True|False,
                    'OccurrenceUnit': 'string'
                },
                'FirstSlotStartTime': datetime(2015, 1, 1),
                'HourlyPrice': 'string',
                'TotalScheduledInstanceHours': 123,
                'AvailableInstanceCount': 123,
                'MinTermDurationInDays': 123,
                'MaxTermDurationInDays': 123
            },
        ]
    }

    :returns:
    (integer) --

    """
    pass


def grouped_select():
    """Select all objects in group

    """
    pass


@classmethod
def workflow_id_to_version(cls, workflow_id):
    """
        Converts an IRIDA workflow id to a version number.
        :param workflow_id: The workflow id.
        :return: The version number for the workflow.
        """
    return cls.WORKFLOW_VERSIONS[workflow_id]


def unflatten_index(i, strides):
    """Return the multiindex corresponding to the given flat index."""
    ii = []
    for s in strides:
        ii.append(i // s)
        i %= s
    return tuple(ii)


def define_dynamic_lists(m):
    """
    Spinning_Reserve_Up_Requirements and Spinning_Reserve_Down_Requirements
    are lists of model components that contribute to spinning reserve
    requirements in each balancing area and timepoint.

    Spinning_Reserve_Up_Provisions and Spinning_Reserve_Down_Provisions are
    lists of model components that help satisfy spinning reserve requirements
    in each balancing area and timepoint.

    Spinning_Reserve_Contingencies is a list of model components
    describing maximum contingency events. Elements of this list will be
    summarized into a Maximumcontingency variable that will be added to the
    Spinning_Reserve_Up_Requirements list.

    Each component in every list needs to use units of MW and be indexed by:
    (b, t) in BALANCING_AREA_TIMEPOINTS.
    """
    m.Spinning_Reserve_Up_Requirements = []
    m.Spinning_Reserve_Down_Requirements = []
    m.Spinning_Reserve_Up_Provisions = []
    m.Spinning_Reserve_Down_Provisions = []
    m.Spinning_Reserve_Contingencies = []


def update_ca_certificate(certificateId=None, newStatus=None,
    newAutoRegistrationStatus=None):
    """
    Updates a registered CA certificate.
    See also: AWS API Documentation

    :example: response = client.update_ca_certificate(
        certificateId='string',
        newStatus='ACTIVE'|'INACTIVE',
        newAutoRegistrationStatus='ENABLE'|'DISABLE'
    )

    :type certificateId: string
    :param certificateId: [REQUIRED]
            The CA certificate identifier.

    :type newStatus: string
    :param newStatus: The updated status of the CA certificate.
            Note: The status value REGISTER_INACTIVE is deprecated and should not be used.

    :type newAutoRegistrationStatus: string
    :param newAutoRegistrationStatus: The new value for the auto registration status. Valid values are: 'ENABLE' or 'DISABLE'.

    """
    pass


def select_next():
    """Select control points following already selected ones along the curves

    """
    pass


def get_origin(image):
    """
    Get origin of ANTsImage

    ANTsR function: `antsGetOrigin`
    """
    return image.origin


def job_pid_setter(this, value):
    """Try to save the pid while setting it to job.pid"""
    if value is None:
        return ''
    this.dir.joinpath('job.pid').write_text(str(value))
    return str(value)


def is_label_dataframe(label, df):
    """check column label existance"""
    setdiff = set(label) - set(df.columns.tolist())
    if len(setdiff) == 0:
        return True
    else:
        return False


def _to_11_bit(data):
    """
    Convert a bytearray to an list of 11-bit numbers.

    Args:
        data (bytes): bytearray to convert to 11-bit numbers

    Returns:
        int[]: list of 11-bit numbers
    """
    buffer = 0
    num_of_bits = 0
    output = []
    for i in range(len(data)):
        buffer |= data[i] << num_of_bits
        num_of_bits += 8
        if num_of_bits >= 11:
            output.append(buffer & 2047)
            buffer = buffer >> 11
            num_of_bits -= 11
    if num_of_bits != 0:
        output.append(buffer & 2047)
    return output


def select_less():
    """Deselect objects at the boundaries of parent/child relationships

    """
    pass


def _reset_gensym():
    """
    Resets the gensym counter to 0, which is useful for doctesting. Do not call
    this function during normal operation.
    """
    global _gensym_counter
    _gensym_counter = 0


def policy_validation_settings(**kwargs):
    """
    Set policy validation settings. This is used when policy based
    tasks are created and `validate_policy` is set to True. The
    following kwargs can be overridden in the create constructor.

    :param bool configuration_validation_for_alert_chain: default False
    :param bool duplicate_rule_check_settings: default False
    :param bool empty_rule_check_settings: default True
    :param bool emtpy_rule_check_settings_for_alert: default False
    :param bool general_check_settings: default True
    :param bool nat_modification_check_settings: default True
    :param bool non_supported_feature: default True
    :param bool routing_modification_check: default False
    :param bool unreachable_rule_check_settings: default False
    :param bool vpn_validation_check_settings: default True
    :return: dict of validation settings
    """
    validation_settings = {'configuration_validation_for_alert_chain':
        False, 'duplicate_rule_check_settings': False,
        'empty_rule_check_settings': True,
        'empty_rule_check_settings_for_alert': False,
        'general_check_settings': True, 'nat_modification_check_settings':
        True, 'non_supported_feature': True, 'routing_modification_check':
        False, 'unreachable_rule_check_settings': False,
        'vpn_validation_check_settings': True}
    for key, value in kwargs.items():
        validation_settings[key] = value
    return {'validation_settings': validation_settings}


def _get_site(node):
    """
    Get the name of the site where the checklist was recorded.

    :param node: the Tag for the body of the Location section.

    :return: the name of the site.

    """
    tag = node.find('h5', class_='obs-loc')
    location = tag.text.split('( Map )')[0]
    site = location.rsplit(',', maxsplit=3)[0]
    return ' '.join(site.split())


@staticmethod
def section_shape(positions, field):
    """defines shape of bilinear interpolated section/surface"""
    if field.ndim == 2:
        return len(positions),
    return len(positions), field.shape[2]


def _freqs(trace, freq=1):
    """Frequency of each label a trace.

    Parameters
    ----------
    trace: tuple of names

    freq: int
        Frequency of the given trace. A trace ("a", "b", "a", "c") w/ trace
        frequency of 3 would return the following frequency count:

        * a: 6
        * b: 3
        * c: 3

    Returns
    -------
    dict
        Frequency count of labels in trace.
    """
    freqs = {}
    for a in trace:
        if a not in freqs:
            freqs[a] = 0
        freqs[a] += 1 * freq
    return freqs


def nb_of_attrs_mismatch(source, target):
    """Generate a query which returns the number of attributes of a node which
    are not in its image."""
    query = (
        """REDUCE(invalid = 0, k in filter(k in keys({}) WHERE k <> 'id' AND k <> 'count') |
"""
        .format(source) + '\tinvalid + CASE\n' +
        '\t\tWHEN NOT k IN keys({}) THEN 1\n'.format(target) +
        """		ELSE REDUCE(invalid_values = 0, v in {}[k] |
""".format(source
        ) + '\t\t\tinvalid_values + CASE {}[k]\n'.format(target) +
        """				WHEN ['IntegerSet'] THEN CASE WHEN toInt(v) IS NULL THEN 1 ELSE 0 END
"""
         +
        "\t\t\t\tWHEN ['StringSet'] THEN CASE WHEN toString(v) <> v THEN 1 ELSE 0 END\n"
         +
        """				WHEN ['BooleanSet'] THEN CASE WHEN v=true OR v=false THEN 0 ELSE 1 END
"""
         + '\t\t\t\tELSE CASE WHEN NOT v IN {}[k] THEN 1 ELSE 0 END END)\n'
        .format(target) + '\t\tEND)')
    return query


def parts():
    """Return a tuple containing the calendar year, month, day,
        hour, minute second and timezone of the object"""


def _id_generator():
    """ A generator that returns the next number for untitled files. """
    i = 1
    while True:
        yield i
        i += 1
    return


def get_pgroup(module, array):
    """Return Protection Group or None"""
    try:
        return array.get_pgroup(module.params['name'])
    except Exception:
        return None


def asbool(some_value):
    """ Cast config values to boolean. """
    return str(some_value).lower() in ['y', 'yes', 't', 'true', '1', 'on']


def pypi_url(varmap):
    """Return the PyPI URL for program ``name`` from the setup vars.
    """
    return 'http://pypi.org/project/{}'.format(varmap['name'])


def __setitem__(_, key, value):
    """ Define a configuration value via dictionary access, e.g. obj[name] = value. """
    _.__map[str(key)] = value


@staticmethod
def blacklist(name, value, seq):
    """
        Implements the behavior of a blacklist by requesting a field be skipped
        whenever its name is found in the list of fields.

        :param name:
            The field name to inspect.
        :param value:
            The field's value.
        :param seq:
            The list of fields associated with the ``Role``.
        """
    if seq is not None and len(seq) > 0:
        return name in seq
    return False


def value_to_int(config_val, evar):
    """
    Convert the value to int.

    :param str config_val: The env var value.
    :param EnvironmentVariable evar: The EVar object we are validating
        a value for.
    :rtype: int
    """
    return int(config_val)


def get_body_region(defined):
    """Return the start and end offsets of function body"""
    scope = defined.get_scope()
    pymodule = defined.get_module()
    lines = pymodule.lines
    node = defined.get_ast()
    start_line = node.lineno
    if defined.get_doc() is None:
        start_line = node.body[0].lineno
    elif len(node.body) > 1:
        start_line = node.body[1].lineno
    start = lines.get_line_start(start_line)
    scope_start = pymodule.logical_lines.logical_line_in(scope.start)
    if scope_start[1] >= start_line:
        start = pymodule.source_code.index(':', start) + 1
        while pymodule.source_code[start].isspace():
            start += 1
    end = min(lines.get_line_end(scope.end) + 1, len(pymodule.source_code))
    return start, end


def getUser():
    """
        Return the HTTP user sent with this request, if any.

        If no user was supplied, return the empty string.

        @returns: the HTTP user, if any
        @rtype: L{str}
        """


def write_dataframe(df, args):
    """
    Write a DataFrame to location specified in commandline arguments,
    optionally filtered by specific columns
    """
    assert len(args.output) > 0
    if args.output_columns is not None and len(args.output_columns) > 0:
        valid_columns = set(df.columns)
        for col in args.output_columns:
            if col not in valid_columns:
                raise ValueError("Column not found '%s', valid options: %s" %
                    (col, list(df.columns)))
        df = df[args.output_columns]
    df.to_csv(args.output, index=False)


def _replace(_self, **kwds):
    """Return a new Triple object replacing specified fields with new values"""
    result = _self._make(map(kwds.pop, ('subject', 'predicate', 'object'),
        _self))
    if kwds:
        raise ValueError('Got unexpected field names: %r' % kwds.keys())
    return result


@classmethod
def last_week_of_year(cls, year):
    """Return the last week of the given year.
        This week with either have week-number 52 or 53.

        This will be the same as Week(year+1, 0), but will even work for
        year 9999 where this expression would overflow.

        The first week of a given year is simply Week(year, 1), so there
        is no dedicated classmethod for that.
        """
    if year == cls.max.year:
        return cls.max
    return cls(year + 1, 0)


def update_fields(item, **kwargs):
    """Updates the abstract field"""
    item['abstract'] = 'Abstract has been updated'
    return item


def get_timeout(filesize, add=0):
    """
    Get a proper time-out limit based on the file size.

    :param filesize: file size (int).
    :param add: optional additional time to be added [s] (int)
    :return: time-out in seconds (int).
    """
    timeout_max = 3 * 3600
    timeout_min = 300
    timeout = timeout_min + int(filesize / 500000.0) + add
    return min(timeout, timeout_max)


def worker_input(arg, errors, dayfirst, yearfirst, utc, box, format, exact,
    unit, infer_datetime_format, origin, cache, slice_list):
    """
    Generates an argument list for worker functions.
    :return: Argument list for worker function.
    """
    arg_list = []
    for i in slice_list:
        lower_bound = i[0]
        upper_bound = i[1]
        arg_list.append([arg[lower_bound:upper_bound]])
    for i in arg_list:
        i.extend((errors, dayfirst, yearfirst, utc, box, format, exact,
            unit, infer_datetime_format, origin, cache))
    return arg_list


def reverse_complement(dna):
    """Complement and reverse DNA string"""
    complements = str.maketrans('acgtrymkbdhvACGTRYMKBDHV',
        'tgcayrkmvhdbTGCAYRKMVHDB')
    return dna.translate(complements)[::-1]


@classmethod
def get_producer(cls):
    """
        Get the default producer.
        """
    return cls._producer


def RACCU_calc(TOP, P, POP):
    """
    Calculate RACCU (Random accuracy unbiased).

    :param TOP: test outcome positive
    :type TOP : int
    :param P: condition positive
    :type P : int
    :param POP: population
    :type POP : int
    :return: RACCU as float
    """
    try:
        result = ((TOP + P) / (2 * POP)) ** 2
        return result
    except (ZeroDivisionError, TypeError):
        return 'None'


@staticmethod
def name():
    """
        Name of the instrument, e.g. 'nova_seq'

        :returns: name of instrument as string
        """
    raise NotImplementedError


def attributive(adjective):
    """ For a predicative adjective, returns the attributive form.
    """
    raise NotImplementedError


def cycle_render_slot(reverse: bool=False):
    """Cycle through all non-void render slots

    :param reverse: Cycle in Reverse
    :type reverse: bool
    """
    pass


def _sum_contingency(contingency, category='total'):
    """
        Returns sums of specified categories in contingency table
        Author: Dougie Squire
        Date: 12/05/2018

        Parameters
        ----------
        contingency : xarray DataArray
            A contingency table of the form output from doppyo.skill.contingency
        category : str, optional
            Contingency table category to sum. Options are 'total', 'reference' and 'comparison'

        Returns
        -------
        summed :
            Sum of all counts in specified category

        Examples
        --------
        >>> da_cmp = xr.DataArray(np.random.normal(size=(3,3)),
        ...                       coords=[('x', np.arange(3)), ('y', np.arange(3))])
        >>> da_ref = xr.DataArray(np.random.normal(size=(3,3)),
        ...                       coords=[('x', np.arange(3)), ('y', np.arange(3))])
        >>> category_edges_cmp = np.linspace(-2,2,3)
        >>> category_edges_ref = np.linspace(-2,2,3)
        >>> contingency = doppyo.skill.contingency(da_cmp, da_ref, category_edges_cmp,
        ...                                        category_edges_ref, over_dims='y')
        >>> doppyo.skill._sum_contingency(contingency, category='reference')
        <xarray.DataArray 'contingency' (x: 3, category: 2)>
        array([[0, 3],
               [2, 1],
               [2, 1]])
        Coordinates:
          * x         (x) int64 0 1 2
          * category  (category) int64 1 2
    """
    if category == 'total':
        N = contingency.sum(dim=('reference_category',
            'comparison_category'), skipna=True)
    elif category == 'reference':
        N = contingency.sum(dim='comparison_category', skipna=True).rename({
            'reference_category': 'category'})
    elif category == 'comparison':
        N = contingency.sum(dim='reference_category', skipna=True).rename({
            'comparison_category': 'category'})
    else:
        raise ValueError(f'"{category}" is not a recognised category')
    return N


def collect_by_type(obj_sequence, cache=None):
    """
    collects objects from obj_sequence and stores them into buckets by
    type. cache is an optional dict into which we collect the results.
    """
    if cache is None:
        cache = {}
    for val in obj_sequence:
        key = type(val)
        bucket = cache.get(key, None)
        if bucket is not None:
            bucket.append(val)
        else:
            cache[key] = [val]
    return cache


def _get_default_bins():
    """Ported from the C++ function InitDefaultBucketsInner() in the following file.
    https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/lib/histogram/histogram.cc
    See the following tutorial for more details on how TensorFlow initialize bin distribution.
    https://www.tensorflow.org/programmers_guide/tensorboard_histograms"""
    v = 1e-12
    buckets = []
    neg_buckets = []
    while v < 1e+20:
        buckets.append(v)
        neg_buckets.append(-v)
        v *= 1.1
    return neg_buckets[::-1] + [0] + buckets


def ADD_TO_SET(expression):
    """
    Returns an array of all unique values that results from applying an expression
    to each document in a group of documents that share the same group by key.
    See https://docs.mongodb.com/manual/reference/operator/aggregation/addToSet/
    for more details
    :param expression: expression
    :return: Aggregation operator
    """
    return {'$addToSet': expression}


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

        :param SsoRemoveLoginUrlType val:
        :rtype: EventType
        """
    return cls('sso_remove_login_url', val)


def result(values, state):
    """
    Return computed value from actions
    """
    return state


def ints_to_int_be(*args):
    """
    Combine a set of 8-bit integers into a single integer. (Big Endian)

    The main purpose of this function is to get around the limitation Python
    has of specifying structures with integers that have unusual byte sizes.

    :param args: List or tuple of 8-bit integers
    :type args: list|tuple
    :return: int
    :rtype: int
    """
    num = 0
    for _int in args:
        num <<= 8
        num = num | _int
    return num


def run_as_root() ->bool:
    """When the user that runs the app is root, return True."""
    import os
    return os.geteuid() == 0


@staticmethod
def ToUnicode(s):
    """Convert to unicode if necessary."""
    if isinstance(s, bytes):
        s = s.decode('utf8')
    return s


@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 unregister(module_name: str):
    """Unregisters an addon’s UI translations.

    :param module_name: The name identifying the addon.
    :type module_name: str
    """
    pass


def env_disable_database_delete(cfg) ->bool:
    """Determine if database delete convenience functions should be disabled.
    See "env_config" for details."""
    return cfg.get('ARANGO_DISABLE_DATABASE_DELETE') != 'false'


def formatLogRecord(msg1, anzleer):
    """ ändert die formatierung des textes im record
    """
    if '\n' in msg1:
        t2 = ''.zfill(anzleer).replace('0', ' ')
        msg1 = '\n%s+- ' % t2 + msg1.replace('\n', '\n%s|- ' % t2
            ) + '\n%s--' % t2
    return msg1


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 '+'


def get_filesize(filename):
    """Returns the size of a file, in bytes."""
    import os
    try:
        return os.stat(filename)[6]
    except OSError:
        return -1


def toggle_render():
    """Toggle rendered shading mode of the viewport

    """
    pass


def _norm_from_ccorr_data(data, norm=None):
    """Determines normalization type from ccorr data"""
    try:
        d, c, sq, s1, s2 = data
    except ValueError:
        raise ValueError('Not a valid correlation data')
    if s1 is None:
        if sq is None:
            default_norm = 0
            available_norm = 0
        else:
            default_norm = 4
            available_norm = 5
    elif sq is None:
        default_norm = 2
        available_norm = 2
    else:
        default_norm = 6
        available_norm = 7
    if norm is None:
        return default_norm
    else:
        if norm not in range(8):
            raise ValueError('Normalization mode must be in range(8)')
        if norm & available_norm == norm:
            return norm
        else:
            raise ValueError('Normalization mode incompatible with input data.'
                )


def unenumerate(value, type):
    """Returns the value of a specific type"""
    return value[type]


def unify_walk(a, b, U):
    """
    unify_walk(a, b, U) returns an Unification where a and b are unified,
    given the unification that already exists in the Unification U. If the
    unification fails, it returns False.

    There are two ways to expand the functionality of unify_walk. The first way
    is:
    @comm_guard(type_of_a, type_of_b)
    def unify_walk(a, b, U):
        ...
    A function defined as such will be executed whenever the types of a and b
    match the declaration. Note that comm_guard automatically guarantees that
    your function is commutative: it will try to match the types of a, b or
    b, a.
    It is recommended to define unify_walk in that fashion for new types of
    Variable because different types of Variable interact a lot with each other,
    e.g. when unifying an OrVariable with a NotVariable, etc. You can return
    the special marker FALL_THROUGH to indicate that you want to relay execution
    to the next match of the type signature. The definitions of unify_walk are
    tried in the reverse order of their declaration.

    Another way is to override __unify_walk__ in an user-defined class.

    Limitations: cannot embed a Variable in another (the functionality could
    be added if required)

    Here is a list of unification rules with their associated behavior:

    """
    if a.__class__ != b.__class__:
        return False
    elif a == b:
        return U
    else:
        return False


def set_instances_default(cls, attr, value):
    """Set DEFAULT attribute for instances of classes created
        by this metaclass

        Arguments:
        attr -- attribute name
        value -- new attribute value
        """
    for instance in cls.get_instances():
        instance.set_instance_attr(attr, value)


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

        :param FileCopyDetails val:
        :rtype: EventDetails
        """
    return cls('file_copy_details', val)


def parse_message_id(value, **kwargs):
    """Parse a Message-ID: header."""
    return value.strip('\n')


def update_locals(locals_instance, instance_iterator, *args, **kwargs):
    """import all of the detector classes into the local namespace to make it
    easy to do things like `import scrubadub.detectors.NameDetector` without
    having to add each new ``Detector`` or ``Filth``
    """
    for instance in instance_iterator():
        locals_instance.update({type(instance).__name__: instance.__class__})


def _gene_length(htseq_genomic_feature):
    """
    Get feature length
    :param htseq_genomic_feature: HTSeq.GenomeFeature
        GenomeFeature from a GFF_Reader iterable
    :return: int
        Feature length
    """
    return abs(htseq_genomic_feature.iv.start - htseq_genomic_feature.iv.end)


def preprocess_reference_text(text):
    """Preprocess a PDF text.

    Parameters
    ----------
    text : str
        The text (possibly from a converted PDF) to preprocess.

    Returns
    -------
    tuple
        A tuple consisting of the following elements:
        - has_reference_section : A boolean which is true when the text contained the string 'reference'
          (not case-sensitive), false otherwise.
        - reference_section : A string containing the reference section.
        - non_reference_section : A string containing the text which was not in the reference section.
    """
    try:
        splitpoint = text.lower().rindex('reference')
    except ValueError:
        splitpoint = False
    while splitpoint and len(text) - splitpoint < 100 and 'reference' in text[:
        splitpoint].lower():
        text = text[:splitpoint]
        splitpoint = text.lower().rindex('reference')
    if not splitpoint:
        has_reference_section = False
        non_reference_section, reference_section = text, ''
    else:
        has_reference_section = True
        non_reference_section, reference_section = text[:splitpoint], text[
            splitpoint:]
    return has_reference_section, reference_section, non_reference_section


def bin2gray(value):
    """
    Convert a binary value to an gray coded value see _[1]. This also works for arrays.
    ..[1] https://en.wikipedia.org/wiki/Gray_code#Constructing_an_n-bit_Gray_code
    """
    return value ^ value >> 1


def getTOFbeta(ins, dsp):
    """get TOF peak profile beta

    :param dict ins: instrument parameters with at least 'beat-0', 'beta-1' & 'beta-q'
      as values only
    :param float dsp: d-spacing of peak

    :returns: float getTOFbeta: peak beat

    """
    return ins['beta-0'] + ins['beta-1'] / dsp ** 4 + ins['beta-q'] / dsp ** 2


@classmethod
def allowed_fields(cls):
    """Return list of fields for application usage."""
    return cls._fields().keys()


def rangeFrameLocator(tickLocs, axisRange):
    """
	Convert axis tick positions for a Tufte style range frame. Takes existing tick locations, places a tick at the min and max of the data, and drops exiting ticks that fall outside of this range or tooo colse to the margins.

	TODO: Convert to a true axis artist that also sets spines

	:param list tickLocs: List of current tick locations on the axis
	:param tuple axisRange: Tuple of (min, max) value on the axis
	:returns: List of tick locations
	:rtype: list
	"""
    cadance = tickLocs[1] - tickLocs[0]
    newTicks = [axisRange[0]]
    for tick in tickLocs:
        if (tick < axisRange[0] + cadance / 2.0) & (tick < axisRange[0] +
            cadance):
            pass
        elif (tick > axisRange[1] - cadance / 2.0) & (tick > axisRange[1] -
            cadance):
            pass
        else:
            newTicks.append(tick)
    newTicks.append(axisRange[1])
    return newTicks


def truncated(text, max_length=100, msg='...'):
    """
    >>> truncated("hello world!", 5)
    'hello...'
    >>> truncated("hello world!", 25)
    'hello world!'
    >>> truncated("hello world!", 5, " [truncated]")
    'hello [truncated]'
    """
    if len(text) < max_length:
        return text
    else:
        return text[:max_length] + msg


def _has_name(soup_obj):
    """checks if soup_obj is really a soup object or just a string
    If it has a name it is a soup object"""
    try:
        name = soup_obj.name
        if name == None:
            return False
        return True
    except AttributeError:
        return False


def _dict_hashable_1(dct):
    """ Simple non-recursive dict -> hashable """
    return tuple(sorted(dct.items()))


def is_collection(v):
    """
    Decide if a variable contains multiple values and therefore can be
    iterated, discarding strings (single strings can also be iterated, but
    shouldn't qualify)
    """
    return hasattr(v, '__iter__') and not isinstance(v, str)


@staticmethod
def Callback(f):
    """
            Decorator that designates a method to be attached to a signal from
            the template
        """
    f._gtk_callback = True
    return f


def define_not_worked_days(list_of_days):
    """
    Define specific days off

    Keyword arguments:
    list_of_days -- list of integer (0: Monday ... 6: Sunday) - default [5, 6]
    """
    global NOT_WORKED_DAYS
    NOT_WORKED_DAYS = list_of_days
    return


@classmethod
def _get_origin(cls):
    """Return list of Model names for origin Reference"""
    return ['sale.sale']


def integer_log(x, xi, limit=1000):
    """
    Computation of integer logarithm.
    For x and x^i returns exponent i if such i exists.
    :param x: base
    :param xi: power value
    :param limit: search limit
    :return: exponent
    """
    if xi == 1:
        return 0
    for i in range(limit):
        xi, r = divmod(xi, x)
        if xi == 1:
            return i + 1
        if r > 0:
            return


@classmethod
def autodetect_settings(cls, autoconfigure_prefix):
    """
        Returns a tuple of :class:`.Setting` objects, that are required for
        :func:`autoconfigure` to complete successfully.
        """
    return ()


def unqote(text):
    """Strip pair of leading and trailing quotes from text."""
    if text.startswith('"') and text.endswith('"') or text.startswith("'"
        ) and text.endswith("'"):
        text = text[1:-1]
    return text


def getStrOutOfList(ls, separator=','):
    """
    #2013.2.24 bugfix
    2012.11.25 reverse of getListOutOfStr
    """
    if not ls:
        return ''
    firstElement = ls[0]
    if type(firstElement) != str:
        ls_str = map(str, ls)
    else:
        ls_str = ls
    return separator.join(ls_str)


def json():
    """Return Python structure, ready for be dumper in JSON"""


def max_subarray(A):
    """
    Maximum subarray problem
    """
    max_ending_here = max_so_far = A[0]
    for x in A[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far


def _hex_to_rgb(value):
    """
    _hex_to_rgb converts a string of 3 hex color values
    into a tuple of decimal values
    """
    value = value.lstrip('#')
    dec = int(value, 16)
    return dec


@classmethod
def resetLogLevel(cls):
    """Resets the log level (the root log level)"""
    cls.setLogLevel(cls.DftLogLevel)


@staticmethod
def readFile(filename):
    """
		Reads data from a file
		"""
    with open(filename, 'rb') as f:
        return f.read().decode('utf-8')


def datetime_to_unix_miliseconds_epoch(dt):
    """
    The number of milliseconds after Jan 1, 1970 00:00:00 UTC
    """
    import time
    return time.mktime(dt.timetuple()) * 1000.0 + dt.microsecond / 1000.0


def function_name(func):
    """
    Given a side-effect function, return its string name.
    """
    return func.__name__


def remember(result):
    """remember user as valid

        result is authomatic result data.
        """


@classmethod
def get_string_types(cls):
    """Get the list of all string types"""
    return [cls.VARCHAR, cls.ENUM, cls.VAR_STRING, cls.STRING]


def scope_flavors_ids_set(flavors_suffix=''):
    """Scope flavors set with '.'

    Returns a scoped name for the list of flavors in the form
    suffix
    """
    return flavors_suffix


def prepend_string(t, string):
    """Prepend a string to a target node as text."""
    node = t.tree
    if node.text is not None:
        node.text += string
    else:
        node.text = string


@classmethod
def getModuleInfo(cls):
    """Get module information. Returns a string."""
    ret = []
    ret.append("Hardware module '%s':" % cls.name)
    ret.append('')
    ret.append('Parameters:')
    for desc in cls.getParamDescs():
        if desc.mandatory:
            defStr = 'mandatory'
        else:
            defStr = 'default: %s' % str(getattr(desc, 'defaultValueStr', None)
                )
        ret.append(' %s = %s (%s)%s' % (desc.name, desc.typeStr.upper(),
            defStr, '  -  ' + desc.description if desc.description else ''))
    return '\n'.join(ret)


@classmethod
def from_iris(cls, cube: 'iris_Cube') ->'DataArray':
    """Convert a iris.cube.Cube into an xarray.DataArray
        """
    from ..convert import from_iris
    return from_iris(cube)


def first(iterable, default=None, key=None):
    """Return first element of *iterable* that evaluates to ``True``, else
    return ``None`` or optional *default*. Similar to :func:`one`.

    >>> first([0, False, None, [], (), 42])
    42
    >>> first([0, False, None, [], ()]) is None
    True
    >>> first([0, False, None, [], ()], default='ohai')
    'ohai'
    >>> import re
    >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
    >>> m.group(1)
    'bc'

    The optional *key* argument specifies a one-argument predicate function
    like that used for *filter()*.  The *key* argument, if supplied, should be
    in keyword form. For example, finding the first even number in an iterable:

    >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
    4

    By Hynek Schlawack, author of `the original standalone module`_.

    .. _the original standalone module: https://github.com/hynek/first
    """
    return next(iter(filter(key, iterable)), default)


@staticmethod
def identity(x):
    """Return a copy of the input.

        This is here for serialization compatibility with pickle.
        """
    return x


def P_otc6486(H, D, gamma, c):
    """ Returns the uplift resistance of cohesive materials.

    OTC6486 - Equation (7)
    """
    return gamma * H * D + 2 * H * c


def estimated_hours(ticket, planned_resource):
    """ Returns the estimated hours for the planned resource
        """


@classmethod
def union(cls, family):
    """union of a family of Lebesgue sets."""
    return cls.operate(cls.UNION, family)


def project_ecef_vector_onto_sc(inst, x_label, y_label, z_label,
    new_x_label, new_y_label, new_z_label, meta=None):
    """Express input vector using s/c attitude directions

    x - ram pointing
    y - generally southward
    z - generally nadir

    Parameters
    ----------
    x_label : string
        Label used to get ECEF-X component of vector to be projected
    y_label : string
        Label used to get ECEF-Y component of vector to be projected
    z_label : string
        Label used to get ECEF-Z component of vector to be projected
    new_x_label : string
        Label used to set X component of projected vector
    new_y_label : string
        Label used to set Y component of projected vector
    new_z_label : string
        Label used to set Z component of projected vector
    meta : array_like of dicts (None)
        Dicts contain metadata to be assigned.
    """
    import pysatMagVect
    x, y, z = pysatMagVect.project_ecef_vector_onto_basis(inst[x_label],
        inst[y_label], inst[z_label], inst['sc_xhat_ecef_x'], inst[
        'sc_xhat_ecef_y'], inst['sc_xhat_ecef_z'], inst['sc_yhat_ecef_x'],
        inst['sc_yhat_ecef_y'], inst['sc_yhat_ecef_z'], inst[
        'sc_zhat_ecef_x'], inst['sc_zhat_ecef_y'], inst['sc_zhat_ecef_z'])
    inst[new_x_label] = x
    inst[new_y_label] = y
    inst[new_z_label] = z
    if meta is not None:
        inst.meta[new_x_label] = meta[0]
        inst.meta[new_y_label] = meta[1]
        inst.meta[new_z_label] = meta[2]
    return


def scan_created_accounts(log, org_client):
    """
    Query AWS Organization for accounts with creation status of 'SUCCEEDED'.
    Returns a list of dictionary.
    """
    log.debug('running')
    status = org_client.list_create_account_status(States=['SUCCEEDED'])
    created_accounts = status['CreateAccountStatuses']
    while 'NextToken' in status and status['NextToken']:
        status = org_client.list_create_account_status(States=['SUCCEEDED'],
            NextToken=status['NextToken'])
        created_accounts += status['CreateAccountStatuses']
    return created_accounts


@classmethod
def parse(cls, storefile, template_store=None, language_code=None,
    is_template=False):
    """Parse store and returns TranslationFormat instance.

        This wrapper is needed for AutodetectFormat to be able to return instance of
        different class.
        """
    return cls(storefile, template_store, language_code, is_template)


@staticmethod
def always_trigger(dt):
    """
        A should_trigger implementation that will always trigger.
        """
    return True


def p_option_expr(p):
    """ option_expr : op_key op_value
                    | op_key EQUAL op_value
    """
    if len(p) > 3:
        p[0] = {p[1]: p[3]}
    else:
        p[0] = {p[1]: p[2]}


def Nu_Achenbach(Re, Pr, voidage):
    """Calculates Nusselt number of a fluid passing over a bed of particles
    using a correlation shown in [1]_ and also cited in the review of [2]_.

    .. math::
        Nu = [(1.18Re^{0.58})^4 + (0.23\\left(\\frac{Re}{1-\\epsilon}
        \\right)^{0.75})^4]^{0.25}

    Parameters
    ----------
    Re : float
        Reynolds number with pebble diameter as characteristic dimension, [-]
    Pr : float
        Prandtl number of the fluid []
    voidage : float
        Void fraction of bed packing [-]

    Returns
    -------
    Nu : float
        Nusselt number for heat transfer to the packed bed [-]

    Notes
    -----
    Claimed value for Re/ε < 7.7E5
    Developed with tests performed in a wind tunnel at conditions up to 30 bar.

    Examples
    --------
    >>> Nu_Achenbach(2000, 0.7, 0.4)
    117.70343608599121

    References
    ----------
    .. [1] Achenbach, E. "Heat and Flow Characteristics of Packed Beds."
       Experimental Thermal and Fluid Science 10, no. 1 (January 1, 1995):
       17-27. doi:10.1016/0894-1777(94)00077-L.
    .. [2] Abdulmohsin, Rahman S., and Muthanna H. Al-Dahhan. "Characteristics
       of Convective Heat Transport in a Packed Pebble-Bed Reactor." Nuclear
       Engineering and Design 284 (April 1, 2015): 143-52.
       doi:10.1016/j.nucengdes.2014.11.041.
    """
    return ((1.18 * Re ** 0.58) ** 4 + (0.23 * (Re / (1 - voidage)) ** 0.75
        ) ** 4) ** 0.25


@staticmethod
def __to_html__(name: str) ->str:
    """Convert a prop name to be usable as an html attribute name.

        Parameters
        ----------
        name : str
            The name to convert.

        Returns
        -------
        str
            The converted name.

        """
    if name.startswith('_'):
        name = name[1:]
    return name.replace('__', ':').replace('_', '-')


def _setup_depot(specs):
    """Setup depot model

    'DEPOT' key added to `specs`
    """
    specs['DEPOT'] = specs['DEPOT_SECTION']


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

        :param SharedLinkSettingsAllowDownloadEnabledType val:
        :rtype: EventType
        """
    return cls('shared_link_settings_allow_download_enabled', val)


@staticmethod
def get_root_and_key(n):
    """
        Return square root expansion root and key for square root of n

        >>> SqrtExpansion.get_root_and_key(24)
        (4, (1, 8))
        """
    root = int(n ** 0.5)
    a_0 = epsilon_0 = int(n ** 0.5)
    gamma_0 = n - epsilon_0 ** 2
    a, epsilon, gamma = a_0, epsilon_0, gamma_0
    expansion = []
    while True:
        a = (int(n ** 0.5) + epsilon) // gamma
        epsilon = a * gamma - epsilon
        gamma = (n - epsilon ** 2) // gamma
        expansion.append(a)
        if epsilon == epsilon_0 and gamma == gamma_0:
            break
    return root, tuple(expansion)


@staticmethod
def _layoutChunk(entries, start, dims):
    """Layout the entries into the given box, starting at start"""
    row, col = start
    numrows, numcols = dims
    colstats = [0] * numcols
    layout = []
    for plotter, num, lines in entries:
        if row + lines > numrows:
            col += 1
            row = 0
        if col >= numcols:
            return [], [], numrows + 1
        if lines > numrows:
            return [], [], lines
        layout.append((plotter, num, col, row, lines))
        row += lines
        colstats[col] += 1
    return layout, colstats, numrows


def create_app_engine(app, config):
    """ Create a new SQLAlchemy engine for a given app """
    from sqlalchemy import create_engine
    return create_engine(config.get('app_db', 'sqlite:///%s.db' % app))


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


def values_exist(expected: set, actual: set) ->bool:
    """
    Check the expected worksheets exist.
    :return:
    """
    return expected <= actual


def calculate_metabolic_coverage(model):
    u"""
    Return the ratio of reactions and genes included in the model.

    Determine whether the amount of reactions and genes in model not equal to
    zero, then return the ratio.

    Parameters
    ----------
    model : cobra.Model
        The metabolic model under investigation.

    Returns
    -------
    float
        The ratio of reactions to genes also called metabolic coverage.

    Raises
    ------
    ValueError
        If the model does not contain either reactions or genes.

    Notes
    -----
    According to [1]_ this is a good quality indicator expressing the degree of
    metabolic coverage i.e. modeling detail of a given reconstruction. The
    authors explain that models with a 'high level of modeling detail have
    ratios >1, and [models] with low level of detail have ratios <1'. They
    explain that 'this difference arises because [models] with basic or
    intermediate levels of detail often include many reactions in which several
    gene products and their enzymatic transformations are ‘lumped’'.

    References
    ----------
    .. [1] Monk, J., Nogales, J., & Palsson, B. O. (2014). Optimizing
          genome-scale network reconstructions. Nature Biotechnology, 32(5),
          447–452. http://doi.org/10.1038/nbt.2870

    """
    if len(model.reactions) == 0 or len(model.genes) == 0:
        raise ValueError('The model contains no reactions or genes.')
    return float(len(model.reactions)) / float(len(model.genes))


def count_intervals(dat):
    """
    We will have instances of continuous downtimes being split into different
    state transitions. For example, if a 2 out of 3 system transitions
    from 2 down to 3 down and then back to 2 down, we want to treat those
    three transitions as a single DOWN event for the system. This method helps with
    that.
    """
    prev_start = 0
    prev_end = 0
    intervals = 0
    for _, row in dat.iterrows():
        curr_start = row['start']
        curr_end = row['end']
        if curr_start > prev_end:
            intervals += 1
        prev_start = curr_start
        prev_end = curr_end
    return intervals


def assuan_serialize(data):
    """Serialize data according to ASSUAN protocol (for GPG daemon communication)."""
    for c in [b'%', b'\n', b'\r']:
        escaped = '%{:02X}'.format(ord(c)).encode('ascii')
        data = data.replace(c, escaped)
    return data


def errno_from_exception(e):
    """Provides the errno from an Exception object.

    There are cases that the errno attribute was not set so we pull
    the errno out of the args but if someone instatiates an Exception
    without any args you will get a tuple error. So this function
    abstracts all that behavior to give you a safe way to get the
    errno.
    """
    if hasattr(e, 'errno'):
        return e.errno
    elif e.args:
        return e.args[0]
    else:
        return None


@staticmethod
def fit_deriv(x, *params):
    """One dimensional Scale model derivative with respect to parameter"""
    d_factor = x
    return [d_factor]


def DebugToFile(fileName):
    """Setup a file name to print debugging messages to
    FILE-NAME = string
              The name of a file to log to
    Returns: void
    Throws:  nothing

    Sets up a file to print debugging messages to.
    """
    global _debugFileName
    _debugFileName = fileName


def ndo_int(data, n):
    """mimic of gmx_fio_ndo_int in gromacs"""
    return [data.unpack_int() for i in range(n)]


def task_result(success=True, message='', actions=None):
    """
    Formats a response from a task so that the task caller can dispatch actions
    :param success: bool
    :param message: str
    :param actions: list(dict)
    :return: tuple
    """
    if not actions:
        actions = []
    return success, message, actions


@classmethod
def UNITS(cls):
    """
        Units of this class.
        """
    return cls._UNITS[:]


def view_all_preview():
    """Zoom preview to fit in the area

    """
    pass


def wasted_votes(party1_votes, party2_votes):
    """
    Computes the wasted votes for each party in the given race.
    :party1_votes: the number of votes party1 received in the race
    :party2_votes: the number of votes party2 received in the race
    """
    total_votes = party1_votes + party2_votes
    if party1_votes > party2_votes:
        party1_waste = party1_votes - total_votes / 2
        party2_waste = party2_votes
    else:
        party2_waste = party2_votes - total_votes / 2
        party1_waste = party1_votes
    return party1_waste, party2_waste


def get_vpn(oneandone_conn, vpn, full_object=False):
    """
    Validates that the vpn exists by ID or a name.
    Returns the vpn if one was found.
    """
    for _vpn in oneandone_conn.list_vpns(per_page=1000):
        if vpn in (_vpn['id'], _vpn['name']):
            if full_object:
                return _vpn
            return _vpn['id']


def semimajoraxis(period, mass):
    """ Given period in years and mass in solar masses, return the semi-major axis in au of an orbit using
        Kepler's third law.
        Written by Logan Pearce, 2019
    """
    import numpy as np
    import astropy.units as u
    try:
        period = period.to(u.yr)
        mass = mass.to(u.Msun)
        sma = ((mass * period ** 2) ** (1 / 3)).value * u.au
    except:
        sma = (mass * period ** 2) ** (1 / 3)
    return sma


def get_telemetry_info(user_info_db):
    """gets the telemetry information:"""
    from src.praxxis.sqlite import connection
    conn = connection.create_connection(user_info_db)
    cur = conn.cursor()
    query = (
        'SELECT Value FROM "UserInfo" WHERE Key in ("URL", "Host", "Username", "Password", "ID") ORDER BY Key="ID", Key="Password", Key="Username", Key="URL", Key="Host" '
        )
    cur.execute(query)
    conn.commit()
    info = cur.fetchall()
    if info is not None:
        for i in range(len(info)):
            info[i] = info[i][0]
    conn.close()
    return info


@staticmethod
def _check_intervals(intervals):
    """Split phase intervals that go beyond phase 1"""
    if isinstance(intervals, tuple):
        intervals = [intervals]
    for phase_interval in intervals:
        if phase_interval[0] > phase_interval[1]:
            intervals.remove(phase_interval)
            intervals.append([phase_interval[0], 1])
            intervals.append([0, phase_interval[1]])
    return intervals


@staticmethod
def _cartpole_balance_death(env, time_step) ->bool:
    """If the reward is less than 0.7 consider a state dead. This threshold is because rewards
        lesser than 0.7 involve positions where the cartpole is not balanced.
        """
    return time_step.reward < 0.75 or abs(env.physics.cart_position()) > 0.5


def mel2hz(mel):
    """Convert a value in Mels to Hertz

    :param mel: a value in Mels. This can also be a numpy array, conversion proceeds element-wise.
    :returns: a value in Hertz. If an array was passed in, an identical sized array is returned.
    """
    return 700 * (10 ** (mel / 2595.0) - 1)


def print_success(text: str) ->None:
    """
    Print the given text in green to indicate success.

    :param text: The text to print
    :return: None
    """
    print(f'\x1b[32m{text}\x1b[0m')


@classmethod
def delete(cls, session, body):
    """Issue a delete call on the session

        :param str body: The body of the bulk delete request.
            The API works on a text/plain list of lines in the
            format /container_name (to delete empty containers)
            or /container_name/object_name (to delete objects
            in a container)

        :rtype:`~rackspace.object_store.v1.bulk_delete.BulkDelete`
        """
    resp = session.delete(cls.base_path, service=cls.service, data=body).body
    return cls.existing(**resp)


def new_mean_temperature(area, height_external, temperature_external, heat):
    """
    Calculates a new mean temperature for the volume.
    :param area: in m^2
    :param height_external: in m
    :param temperature_external: in K
    :param heat: in J
    :return: temperature in K
    """
    volume_air = area * height_external
    specific_heat_capacity = 1005
    density_air = 1.29 * 273 / temperature_external
    energy_air = (volume_air * specific_heat_capacity * density_air *
        temperature_external)
    return (energy_air + heat) / (volume_air * density_air *
        specific_heat_capacity)


@classmethod
def get_exchange_name(cls):
    """
        Get exchange name
        :return: Exchange name string
        """
    return 'Bitfinex'


def updateActions():
    """Update wizard actions."""


def safe(s):
    """Convert special characters to html entities."""
    return s.replace('&', '&').replace('<', '<').replace('>', '>')


def extract_dims(array, ndim=1):
    """Decrease the dimensionality of ``array`` by extracting ``ndim`` leading singleton dimensions."""
    for _ in range(ndim):
        assert len(array) == 1
        array = array[0]
    return array


def stripped(jid):
    """ strip trailing part of a JID, the part after the / """
    try:
        return str(jid).split('/')[0]
    except:
        return str(jid)


def fmodifier_copy():
    """Copy the F-Modifier(s) of the active F-Curve

    """
    pass


def check_class(var, cls, allowNone=False):
    """ Checks if a variable is an instance of the cls class, raises TypeError if the check fails.
    """
    if not isinstance(var, cls) and not (allowNone and var is None):
        raise TypeError('Unexpected type {}, was expecting {}'.format(type(
            var), cls))


def qualified_name(x):
    """Return the qualified name of 'x' (including the module).
    The format is: `module.submodule:attr.subattr`.
    """
    return '%s:%s' % (x.__module__, x.__qualname__)


def get_item_from_model(item_type, item_id, model):
    """ Return the appropriate item from the model according to the specified
    item type and item id.

    Parameters
    ----------
    item_type : str
    item_id : str
    model : GEMEditor.model.classes.cobra.Model

    Returns
    -------
    item : GEMEditor.model.classes.cobra.Reaction, GEMEditor.model.classes.cobra.Metabolite, GEMEditor.model.classes.cobra.Gene, GEMEditor.model.classes.cobra.Model

    Raises
    ------
    ValueError
        If item_type is not "Reaction", "Model", "Gene", "GeneGroup" or "Metabolite"
    KeyError
        If item id is not present in the corresponding collection
    """
    if item_type == 'Reaction':
        return model.reactions.get_by_id(item_id)
    elif item_type == 'Metabolite':
        return model.metabolites.get_by_id(item_id)
    elif item_type == 'Gene':
        return model.genes.get_by_id(item_id)
    elif item_type == 'GeneGroup':
        raise NotImplementedError
    elif item_type == 'Model':
        return model
    elif item_type == 'Compartment':
        return model.gem_compartments[item_id]
    else:
        raise ValueError("Unexpected item type '{0}' with id {1}".format(
            item_type, item_id))


def add_spelling(ix, fieldnames, commit=True):
    """Adds spelling files to an existing index that was created without
    them, and modifies the schema so the given fields have the ``spelling``
    attribute. Only works on filedb indexes.

    >>> ix = index.open_dir("testindex")
    >>> add_spelling(ix, ["content", "tags"])

    :param ix: a :class:`whoosh.filedb.fileindex.FileIndex` object.
    :param fieldnames: a list of field names to create word graphs for.
    :param force: if True, overwrites existing word graph files. This is only
        useful for debugging.
    """
    from whoosh.automata import fst
    from whoosh.reading import SegmentReader
    writer = ix.writer()
    storage = writer.storage
    schema = writer.schema
    segments = writer.segments
    for segment in segments:
        ext = segment.codec().FST_EXT
        r = SegmentReader(storage, schema, segment)
        f = segment.create_file(storage, ext)
        gw = fst.GraphWriter(f)
        for fieldname in fieldnames:
            gw.start_field(fieldname)
            for word in r.lexicon(fieldname):
                gw.insert(word)
            gw.finish_field()
        gw.close()
    for fieldname in fieldnames:
        schema[fieldname].spelling = True
    if commit:
        writer.commit(merge=False)


def Deep_Data(L_1197, L_1216, L_1235, L_1373, L_1453, L_1503):
    """
        Deep-Data Hydrocarbon Index =============================================
            Convert numpy arrays of radiance data to a Deep-Data hydrocarbon
            index map

        Inputs ==================================================================
            L_1197 : At-sensor radiance at 1197 nm wavelength (numpy array)
            L_1216 : At-sensor radiance at 1216 nm wavelength (numpy array)
            L_1235 : At-sensor radiance at 1235 nm wavelength (numpy array)
            L_1373 : At-sensor radiance at 1373 nm wavelength (numpy array)
            L_1453 : At-sensor radiance at 1453 nm wavelength (numpy array)
            L_1503 : At-sensor radiance at 1503 nm wavelength (numpy array)

        Returns =================================================================
            Deep-Data Hydrocarbon Index Map

    """
    return 1.2 * L_1197 - 1.1 * L_1216 + 0.5 * (1.2 * L_1235 - L_1197 * 1.1
        ) - (1.2 * L_1373 - 1.1 * L_1453 + 0.5 * (1.2 * L_1503 - L_1373 * 1.1))


def testPropertiesValidity(new_properties, member=None):
    """ Return None if the supplied properties are valid;  otherwise
            return a string explaining why not.

        o 'new_properties' is a mapping containing the properties to test.

        o 'member', if passed, is the ID of the member for whome the
          properties are being set;  if not passed, use the currently-
          authenticated member.

        o Permission:  Public
        """


def write_name(name):
    """Abaqus has odd rules for writing words without spaces vs. with spaces"""
    return '%r' % name if ' ' in name else '%s' % name


def register(email, display_name=None):
    """Register the given email address and link it to this user.

        :param email: The text email address to register.
        :type email: str
        :param display_name: The user's display name.  If not given the empty
            string is used.
        :type display_name: str
        :return: The address object linked to the user.  If the associated
            address object already existed (unlinked to a user) then the
            `display_name` parameter is ignored.
        :rtype: `IAddress`
        :raises AddressAlreadyLinkedError: if this `IAddress` is already
            linked to another user.
        """


@classmethod
def apply(cls, text, mode):
    """
        Apply mode for text

        :param text:
        :param mode:
        :return:
        """
    if mode == cls.SCREAMING_SNAKE_CASE:
        return cls._screaming_snake_case(text)
    if mode == cls.snake_case:
        return cls._snake_case(text)
    if mode == cls.lowercase:
        return cls._snake_case(text).replace('_', '')
    if mode == cls.lowerCamelCase:
        return cls._camel_case(text)
    if mode == cls.CamelCase:
        return cls._camel_case(text, True)
    if callable(mode):
        return mode(text)
    return text


@classmethod
def from_latitude_longitude(cls, latitude=0.0, longitude=0.0):
    """Creates a point from lat/lon in WGS84"""
    assert -180.0 <= longitude <= 180.0, 'Longitude needs to be a value between -180.0 and 180.0.'
    assert -90.0 <= latitude <= 90.0, 'Latitude needs to be a value between -90.0 and 90.0.'
    return cls(latitude=latitude, longitude=longitude)


def get_floorare_pp(floorarea, reg_pop_by, base_yr, sim_period,
    assump_diff_floorarea_pp):
    """Calculate future floor area per person depending
    on assumptions on final change and base year data

    Arguments
    ----------
    floorarea : dict
        Floor area base year for all regions
    reg_pop_by : dict
        Population of base year for all regions
    base_yr, : int
        base year
    sim_period: list
        Simulation period
    assump_diff_floorarea_pp : float
        Assumption of change in floor area up to end of simulation

    Returns
    -------
    floor_area_pp : dict
        Contains all values for floor area per person for every year

    Note
    ----
    - Linear change of floor area per person is assumed over time
    """
    floor_area_pp = {}
    if reg_pop_by == 0:
        floor_area_pp[base_yr] = 0
    else:
        floor_area_pp[base_yr] = floorarea / reg_pop_by
    for curr_yr in sim_period:
        if curr_yr == base_yr:
            pass
        else:
            floor_area_pp[curr_yr] = floor_area_pp[base_yr] * (1 +
                assump_diff_floorarea_pp[curr_yr])
    return floor_area_pp


def set_prefs(prefs):
    """This function is called before opening the project"""
    prefs['ignored_resources'] = ['*.pyc', '*~', '.ropeproject', '.hg',
        '.svn', '_svn', '.git', '.tox', '.env', 'env', 'venv',
        'node_modules', 'bower_components']
    prefs['save_objectdb'] = True
    prefs['compress_objectdb'] = False
    prefs['automatic_soa'] = True
    prefs['soa_followed_calls'] = 0
    prefs['perform_doa'] = True
    prefs['validate_objectdb'] = True
    prefs['max_history_items'] = 32
    prefs['save_history'] = True
    prefs['compress_history'] = False
    prefs['indent_size'] = 4
    prefs['extension_modules'] = []
    prefs['import_dynload_stdmods'] = True
    prefs['ignore_syntax_errors'] = False
    prefs['ignore_bad_imports'] = False
    prefs['prefer_module_from_imports'] = False
    prefs['split_imports'] = False
    prefs['pull_imports_to_top'] = True
    prefs['sort_imports_alphabetically'] = False
    prefs['type_hinting_factory'
        ] = 'rope.base.oi.type_hinting.factory.default_type_hinting_factory'


def clumping_factor_HB(z, beta=2):
    """Clumping factor as a function of redshift used by Haiman & Bryan (2006).

    See Haiman & Bryan (2006ApJ...650....7H).
    """
    return 1 + 9 * ((1 + z) / 7) ** -beta


@classmethod
def has_smart_authorization(cls, request, ppm_id):
    """
        Make a request to P2MD to determine if a participant has authorized any SMART provider.
        """
    response = cls.head(request, f'/sources/api/smart/-/{ppm_id}', raw=True)
    return response.ok


def _unbin(tile_data, factor):
    """
    tile_data should have shape (num_frames, y, x)
    """
    s = tile_data.shape
    tile_data = tile_data.reshape((s[0], s[1], 1, s[2]))
    unbinned = tile_data.repeat(factor, axis=2)
    return unbinned.reshape((s[0], factor * s[1], s[2]))


def read_uic3tag(fh, byteorder, dtype, plane_count):
    """Read MetaMorph STK UIC3Tag from file and return as dictionary."""
    assert dtype == '2I' and byteorder == '<'
    values = fh.read_array('<u4', 2 * plane_count).reshape(plane_count, 2)
    return {'wavelengths': values[:, (0)] / values[:, (1)]}


def size2str(size):
    """Converts a file size into a string"""
    if size >= 1000000000:
        return str(size // 1048576) + 'M'
    elif size >= 10000000:
        return str(size // 1024) + 'K'
    else:
        return str(size)


def maxlevels(ticks):
    """returns a tuple maxticklevel, maxlabellevel from a list of tick instances"""
    maxticklevel = maxlabellevel = 0
    for tick in ticks:
        if tick.ticklevel is not None and tick.ticklevel >= maxticklevel:
            maxticklevel = tick.ticklevel + 1
        if tick.labellevel is not None and tick.labellevel >= maxlabellevel:
            maxlabellevel = tick.labellevel + 1
    return maxticklevel, maxlabellevel


def ipaddress():
    """
    Determine our own IP adress.
    This seems to be far more complicated than you would think:
    """
    try:
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('gmail.com', 80))
        result = s.getsockname()[0]
        s.close()
        return result
    except Exception:
        return ''


def call_formatter(cmd, input):
    """
    Return the formatted version of the given file.
    """
    from subprocess import Popen, PIPE, CalledProcessError
    import logging
    logging.debug('calling %r', cmd)
    p = Popen(cmd, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    out, err = p.communicate(input)
    if p.returncode:
        raise CalledProcessError(p.returncode, cmd, err)
    return out


def is_bool(value):
    """Return True if `value` is a boolean."""
    return bool(value) == value


def cervical_cancer(round_limit=2, random_method='uniform_mersenne'):
    """Performs a Scan with Iris dataset and simple dense net"""
    import talos as ta
    scan_object = ta.Scan(ta.templates.datasets.cervical_cancer()[0], ta.
        templates.datasets.cervical_cancer()[1], ta.templates.params.
        cervical_cancer(), ta.templates.models.cervical_cancer, 'test',
        round_limit=round_limit)
    return scan_object


def hash_trees(tree):
    """Hashes trees and adds frequencies and a hash map.

    Parameters
    ----------
    tree : tuple
        A tuple of elements corresponding to a tree:
            + A set of vertices
            + A dictionary of edges
            + A dictionary that corresponds to an ordering of vertices
            + A dictionary of labels

    Returns
    -------
    hash_tree : tuple
        A hashed version of the tree:
            + A dictionary from vertices to tuples containing the subtree size,
              frequencies and node ID
            + A dictionary between hashes and vertices
              (representing a valid hash map)
            + A list of ordered vertices, based on an the inverse
              topological ordering

    """
    vertex, edge, ordering, labels = tree
    v_ordered = sorted(list(vertex), key=lambda x: (ordering[x], labels[x]))
    vertices_hash_map = dict()
    vertices = dict()
    for v in v_ordered:
        if v not in edge or len(edge[v]) == 0:
            if labels[v] not in vertices_hash_map:
                vertices_hash_map[labels[v]] = list()
            vertices_hash_map[labels[v]].append(v)
            vertices[v] = [0, 1, str(labels[v])]
        else:
            neighbors_ids = []
            d = 0
            for n in edge[v]:
                d += 1 + vertices[n][0]
                neighbors_ids.append(vertices[n][2])
            ID = str(labels[v]) + '(' + ','.join(neighbors_ids) + ')'
            vertices[v] = [d, 1, ID]
            if ID not in vertices_hash_map:
                vertices_hash_map[ID] = list()
            vertices_hash_map[ID].append(v)
    return vertices, vertices_hash_map, v_ordered


def currenttransaction():
    """Obtain the current transaction instance or None."""


@classmethod
def validate_data(cls, data):
    """
        Validates data with respect to the data definition.
        """
    pass


def DFChangeHeader(df, newheader):
    """df=DataFrame (pandas) and newheader=list or array"""
    from pandas import DataFrame
    df.columns = newheader
    return df


def replace(s, replace):
    """Replace multiple values in a string"""
    for r in replace:
        s = s.replace(*r)
    return s


def transform_to_another_scale(x, a, b, c, d):
    """ tranforms a value x from the scale [a,b] to the scale [c,d] """
    return (x - a) * ((d - c) / (b - a)) + c


def is_response_to_head(response):
    """
    Checks whether the request of a response has been a HEAD-request.
    Handles the quirks of AppEngine.

    :param conn:
    :type conn: :class:`httplib.HTTPResponse`
    """
    method = response._method
    if isinstance(method, int):
        return method == 3
    return method.upper() == 'HEAD'


@staticmethod
def _enqueue_output(stream, queue):
    """
        Add chunks of data from a stream to a queue until the stream is empty.
        """
    for line in iter(lambda : stream.read(4096), b''):
        queue.put(line)
    stream.close()


def feature_spawn(df):
    """Takes a time series and spawns several new features that explicitly
    detail information about the series.

    The DataFrame spawned contains the following features
    spawned for each column in the input DataFrame:

        Exponentially Weighted Moving Average of various Half Lives:
            1 day,
            1 week,
            1 month,
            1 quarter,
            6 months,
            1 year

        Rolling vol of different window sizes:
            1 week,
            1 month,
            1 quarter

    :param df:              The dataset of independent variables
    :type  df:              pd.DataFrame

    :return:                The DataFrame containing spawned features
    :rtype:                 pd.DataFrame
    """
    hlf_dict = {'week': 5, 'month': 22, 'quarter': 66, 'half_year': 132,
        'year': 260}
    for col in df.columns:
        for half_life in hlf_dict:
            df[col + '_ema_' + half_life] = df[col].ewm(span=hlf_dict[
                half_life]).mean()
    for i, half_life in enumerate(hlf_dict):
        if i < 3:
            df[col + '_roll_vol_' + half_life] = df[col].rolling(window=
                hlf_dict[half_life]).std(ddof=0)
    df.dropna(inplace=True)
    return df


@classmethod
def task_cnt(cls):
    """ECoreCorrType暂时支持的相关计算方法个数"""
    return 4


def move_dates(apps, schema_editor):
    """Move dates to models."""
    Domain = apps.get_model('admin', 'Domain')
    DomainAlias = apps.get_model('admin', 'DomainAlias')
    Mailbox = apps.get_model('admin', 'Mailbox')
    Alias = apps.get_model('admin', 'Alias')
    for model in [Domain, DomainAlias, Mailbox, Alias]:
        for instance in model.objects.all():
            instance.creation = instance.dates.creation
            instance.last_modification = instance.dates.last_modification
            instance.save()


def roundto(num, nearest):
    """
    Rounds :param:`num` to the nearest increment of :param:`nearest`
    """
    return int((num + nearest / 2) // nearest * nearest)


def group_insert():
    """Insert selected nodes into a node group

    """
    pass


def addDependent(location):
    """Add a dependency to a dependent object by location

        The location is the physical path to the dependent object.
        """


def _arma_predict_in_sample(start, end, endog, resid, k_ar, method):
    """
    Pre- and in-sample fitting for ARMA.
    """
    if 'mle' in method:
        fittedvalues = endog - resid
    else:
        fittedvalues = endog[k_ar:] - resid
    fv_start = start
    if 'mle' not in method:
        fv_start -= k_ar
    fv_end = min(len(fittedvalues), end + 1)
    return fittedvalues[fv_start:fv_end]


def hash_to_hex_str(x):
    """Convert a big-endian binary hash to displayed hex string.

    Display form of a binary hash is reversed and converted to hex.
    """
    return bytes(reversed(x)).hex()


@classmethod
def is_datasource_for(cls, data, header, **kwargs):
    """Determines if header corresponds to an EIT image"""
    return header.get('instrume') == 'EIT'


def end_transition(obj, *args, **kwargs):
    """Ends a state transition with some state."""
    from .models import System
    return System.get(obj).end_transition(*args, **kwargs)


@classmethod
def download_gencove_data(cls, request, ppm_id):
    """
        Downloads the Gencove dataset for the passed user
        :param request: The original Django request object
        :param ppm_id: The PPM ID of the requesting user
        :return: The requested dataset
        """
    response = cls.get(request, f'/sources/api/gencove/{ppm_id}/download',
        raw=True)
    if response:
        return response.content
    return None


@classmethod
def set_mongo_replica_set(cls, replica_set=None):
    """
        assigns the MONGO_REPLICA_SET var in config and regenerates mongodb uri

        returns Class
        """
    assert isinstance(replica_set, (str, type(None))
        ), 'database must be a string or NoneType'
    cls.MONGO_REPLICA_SET = replica_set
    cls.generate_mongo_uri()
    return cls


def DoInsertDockRow(panes, dock_direction, dock_layer, dock_row):
    """
    This is an internal function that inserts a new dock
    row by incrementing all existing dock row values by one.

    :param `panes`: a list of :class:`AuiPaneInfo`;
    :param integer `dock_direction`: the :class:`AuiDockInfo` docking direction to analyze;
    :param integer `dock_layer`: the :class:`AuiDockInfo` layer to analyze;
    :param integer `dock_row`: the :class:`AuiDockInfo` row to analyze.
    """
    for pane in panes:
        if (not pane.IsFloating() and pane.dock_direction == dock_direction and
            pane.dock_layer == dock_layer and pane.dock_row >= dock_row):
            pane.dock_row += 1
    return panes


def duplicate_move(MESH_OT_duplicate=None, TRANSFORM_OT_translate=None):
    """Duplicate mesh and move

    :param MESH_OT_duplicate: Duplicate, Duplicate selected vertices, edges or faces
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def save_cont_parameters_to_file(dataset, filename):
    """Save Chebyshev coefficients to file."""
    with open(filename, 'w') as output:
        header = '# Chebyshev Polynomial Coefficients'
        output.write(header + '\n')
        for reg_num, region in enumerate(dataset.regions):
            output.write('# Region %i: \n' % reg_num)
            cheb_parnames = list()
            for parname in dataset.best_fit.keys():
                if 'R%i_cheb' % reg_num in parname:
                    cheb_parnames.append(parname)
            cheb_parnames = sorted(cheb_parnames)
            for i, parname in enumerate(cheb_parnames):
                coeff = dataset.best_fit[parname]
                line = ' p%-2i  =  %.3e    %.3e' % (i, coeff.value, coeff.
                    stderr)
                output.write(line + '\n')
            output.write('\n')


@classmethod
def get(cls, data_source_id):
    """
        Gets the data source.

        Parameters
        ----------
        data_source_id : str
            the identifier of the data source.

        Returns
        -------
        data_source : DataSource
            the requested data source.

        Examples
        --------
        .. code-block:: python

            >>> import datarobot as dr
            >>> data_source = dr.DataSource.get('5a8ac9ab07a57a0001be501f')
            >>> data_source
            DataSource('Diagnostics')
        """
    return cls.from_location('{}{}/'.format(cls._path, data_source_id))


def svg2str(display_object, dpi=300):
    """
    Serializes a nilearn display object as a string
    """
    from io import StringIO
    image_buf = StringIO()
    display_object.frame_axes.figure.savefig(image_buf, dpi=dpi, format=
        'svg', facecolor='k', edgecolor='k')
    return image_buf.getvalue()


def parse_vault_id(vault_id):
    """
    parse the returned vaults
    vaults.list() returns {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}'}
    """
    _, _, subscription_id, _, resource_group, *unimportant, vault_name = (
        vault_id.split('/'))
    return subscription_id, resource_group, vault_name


@staticmethod
def interfaces_roles_change_and_tree_remains_or_transitions_to_active_state(
    interface: 'TreeInterfaceDownstream') ->None:
    """
        Tree remains or changes to Active state AND
        interface not directly connected to the source AND
        interface roles change (Root->Non-Root)
        """
    interface.logger.debug(
        'interfaces_roles_change_and_tree_remains_or_transitions_to_active_state'
        )
    interface.send_i_am_upstream()


def validate_boolean(b):
    """Convert b to a boolean or raise a ValueError."""
    try:
        b = b.lower()
    except AttributeError:
        pass
    if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
        return True
    elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
        return False
    else:
        raise ValueError('Could not convert {0!r} to boolean'.format(b))


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


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

        :param GuestAdminSignedInViaTrustedTeamsDetails val:
        :rtype: EventDetails
        """
    return cls('guest_admin_signed_in_via_trusted_teams_details', val)


def brunet_w(num_types, num_tokens):
    """Calculate Brunet’s W (1978).

    Used formula:
        .. math::
            W = V^{V^{0.172}}

    Parameters:
        num_types (int): Absolute number of types.
        num_tokens (int): Absolute number of tokens.
    """
    a = -0.172
    return num_tokens ** num_types ** -a


@classmethod
def get_name(cls):
    """ Returns the name of the supplier.
		"""
    return 'csv'


def deltas(deltacode, all_delta_types=False):
    """
    Return a generator of Delta dictionaries for JSON serialized ouput.  Omit
    all unmodified Delta objects unless the user selects the '-a'/'--all'
    option.
    """
    for delta in deltacode.deltas:
        if all_delta_types is True:
            yield delta.to_dict()
        elif not delta.is_unmodified():
            yield delta.to_dict()


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

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

       - arcsinh(default) = default
       - arcsinh(row_sparse) = row_sparse
       - arcsinh(csr) = csr

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

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

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

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


def get_metadata_url(illust_id: int) ->str:
    """Get illust Metadata URL from ``illust_id``.

    :param illust_id: Pixiv illust_id
    :type illust_id: :class:`int`
    :return: Pixiv Metadata URL
    :rtype: :class:`str`

    """
    return 'https://www.pixiv.net/ajax/illust/{}/ugoira_meta'.format(illust_id)


def intToBin(i):
    """ Integer to two bytes """
    i1 = i % 256
    i2 = int(i / 256)
    return chr(i1) + chr(i2)


def get_files(model_db):
    """get model and converter files"""
    pass


def car(ol):
    """
        from elist.elist import *
        ol=[1,2,3,4]
        car(ol)
    """
    return ol[0]


def rotate_axes(position, axes):
    """Rotate axes in position

    Examples
    --------
    >>> rotate_axes([1, 2, 3], "xy")
    (1, 2, 3)
    >>> rotate_axes([1, 2, 3], "yz")
    (2, 3, 1)
    """
    missing_axes = set('xyz') - set(axes)
    for a in missing_axes:
        axes += a
    assert len(axes) == 3
    mapping = dict(x=0, y=1, z=2)
    return tuple(position[mapping[a]] for a in axes)


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


def xor_polygons_phidl(A, B, hash_geom=True):
    """ Given two devices A and B, performs a layer-by-layer XOR diff between
    A and B, and returns polygons representing the differences between A and B.
    """
    from phidl import Device
    import gdspy
    if hash_geom and A.hash_geometry() == B.hash_geometry():
        return Device()
    D = Device()
    A_polys = A.get_polygons(by_spec=True)
    B_polys = B.get_polygons(by_spec=True)
    A_layers = A_polys.keys()
    B_layers = B_polys.keys()
    all_layers = set()
    all_layers.update(A_layers)
    all_layers.update(B_layers)
    for layer in all_layers:
        if layer in A_layers and layer in B_layers:
            p = gdspy.fast_boolean(A_polys[layer], B_polys[layer],
                operation='xor', precision=0.001, max_points=4000, layer=
                layer[0], datatype=layer[1])
        elif layer in A_layers:
            p = A_polys[layer]
        elif layer in B_layers:
            p = B_polys[layer]
        if p is not None:
            D.add_polygon(p, layer=layer)
    return D


def delete(address_type, address):
    """ Remove an opt out for an address. """


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

        :param TeamFolderRenameType val:
        :rtype: EventType
        """
    return cls('team_folder_rename', val)


def touch(file_name):
    """
    Creates an empty file. An existing file remains untouched.

    :param file_name: Name of the file.
    """
    open(file_name, 'a').close()


def is_multiclass_classifier(clf):
    """
    Return True if a classifier is multiclass or False if it is binary.
    """
    return clf.coef_.shape[0] > 1


def getAge():
    """Return comment age"""


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 '+'


def derive_names(name):
    """Get name of network, firewall & boot instance from boot disk"""
    network = name + '-network'
    firewall = name + '-firewall-allow-all'
    boot = name
    return network, firewall, boot


def make_host_list(serverlist):
    """Create fabric compatible host list from updian's server list."""
    host_list = []
    for server in serverlist:
        user = server.user or server.defaults['user']
        port = server.port or server.defaults['port']
        hostspec = '%s@%s:%d' % (user, server.hostname, port)
        host_list.append(hostspec)
    return host_list


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

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


def draw_preview(snap: bool=False):
    """Draw preview of current sketch stroke (internal use)

    :param snap: Snap
    :type snap: bool
    """
    pass


def copy_parameters(model1, model2):
    """Overwrite model1's parameters with model2's."""
    model1.load_state_dict(model2.state_dict())


def ceil_div(a, b):
    """Ceil integer division (``ceil(a / b)`` using integer arithmetic)."""
    return (a - 1) // b + 1


def load_setuptools_extension(finder, module):
    """the setuptools.extension module optionally loads
       Pyrex.Distutils.build_ext but its absence is not considered an error."""
    module.IgnoreName('Pyrex.Distutils.build_ext')


def _len_guards(M):
    """Handle small or incorrect window lengths"""
    if int(M) != M or M < 0:
        raise ValueError('Window length M must be a non-negative integer')
    return M <= 1


def is_jsfunc(func: str) ->bool:
    """Heuristically check function or expression."""
    func = func.strip()
    if func.startswith('function') or func.startswith('async '):
        return True
    elif '=>' in func:
        return True
    return False


def iterParticlesByMic(partSet):
    """ Iterate the particles ordered by micrograph """
    for i, part in enumerate(partSet.iterItems(orderBy=['_micId', 'id'],
        direction='ASC')):
        yield i, part


def __add__(actions):
    """Add two actions collections

        The result has the actions in the first collection followed by
        the actions in the second collection.

        Actions should have different names in the two collections.
        The bahavior is undefined if the names overlap.

        """


def SetProgressDisplay(display):
    """Set the progress display to use (called from SCons.Script)"""
    global progress_display
    progress_display = display


@classmethod
def load(cls, fname):
    """
        Load a pickled results instance

        .. warning::

           Loading pickled models is not secure against erroneous or
           maliciously constructed data. Never unpickle data received from
           an untrusted or unauthenticated source.

        Parameters
        ----------
        fname : {str, handle}
            A string filename or a file handle.

        Returns
        -------
        Results
            The unpickled results instance.
        """
    from statsmodels.iolib.smpickle import load_pickle
    return load_pickle(fname)


def is_key(sarg):
    """Check if `sarg` is a key (eg. -foo, --foo) or a negative number (eg. -33).
    """
    if not sarg.startswith('-'):
        return False
    if sarg.startswith('--'):
        return True
    return not sarg.lstrip('-').isnumeric()


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 pchange1(f, c, o=1):
    """Calculate the percentage change within the same variable.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the column ``c``.
    c : str
        Name of the column in the dataframe ``f``.
    o : int
        Offset to the previous value.

    Returns
    -------
    new_column : pandas.Series (float)
        The array containing the new feature.

    """
    new_column = f[c] / f[c].shift(o) - 1.0
    return new_column


def add_chromsome_prefix(sel, data):
    """Add the chromosome in front of every feature"""
    if type(sel) == str:
        chrom = sel,
    else:
        chrom = sel['chr'],
    for f in data:
        yield chrom + tuple(f)


def should_build_with_cython(package, release=None):
    """Returns the previously used Cython version (or 'unknown' if not
    previously built) if Cython should be used to build extension modules from
    pyx files.  If the ``release`` parameter is not specified an attempt is
    made to determine the release flag from `astropy.version`.
    """
    try:
        version_module = __import__(package + '.cython_version', fromlist=[
            'release', 'cython_version'])
    except ImportError:
        version_module = None
    if release is None and version_module is not None:
        try:
            release = version_module.release
        except AttributeError:
            pass
    try:
        cython_version = version_module.cython_version
    except AttributeError:
        cython_version = 'unknown'
    have_cython = False
    try:
        import Cython
        have_cython = True
    except ImportError:
        pass
    if have_cython and (not release or cython_version == 'unknown'):
        return cython_version
    else:
        return False


@classmethod
def get_session_token_key(cls):
    """
        Get the session token key used to store/retrieve the user's session
        token in the flask session.
        """
    return 'manage_session_token'