def order_new_request(message, futures):
    """Intercepts order new request info messages (on-req) and check for
    Future objets with a matching cid.

    Parameters
    ----------
    message : str
        The unaltered response message returned by bitfinex.
    futures : dict
        A dict of intercept_id's and future objects.
        dict{intercept_id, future_object}
    """
    order_cid = message[4][2]
    future_id = f'on-req_{order_cid}'
    futures[future_id].set_result({'status': message[6], 'id': message[4][0
        ], 'cid': order_cid, 'response': message[4], 'comment': message[7]})
    del futures[future_id]


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

    The ".dev0" means dirty.

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


@staticmethod
def get_namespace(env):
    """ Grabs ES namespace from health page """
    from .ff_utils import get_health_page
    health = get_health_page(ff_env=env)
    return health.get('namespace', '')


def pure_translation(position, translation_vec):
    """
    pure translation of point by a vector in same coordinate frame

    Parameters
    ----------
    position : np.array(3,1)
        position of point in any coord frame
    translation_vec : np.array(3,1)
        translation vector in same coord frame

    Returns
    -------
    tr_vec : np.array(3,1)
        translated position of point by trans_vec
        in same coord frame

    Raises
    ------
    """
    tr_vec = position + translation_vec
    return tr_vec


@staticmethod
def on_shutdown():
    """Method ran on worker shutdown."""
    pass


def newLine(match):
    """
    把匹配到的东西前后加入换行符，用于对inline文本进行处理
    :param match:
    :return:
    """
    return '\n{}\n'.format(match.group())


def __len__():
    """Return len of queue"""


def check_valid_config_space(config_space, parameters):
    """Check if the parameters is valid based on a configuration space

    Args:
        config_space (ConfigSpace): configuration space
        parameters (dict): parameters dictionary

    Raises:
        ValueError: If there is invalid values
    """
    base = config_space.get_default_configuration()
    for key, value in parameters.items():
        if key in base:
            base[key] = value


def remove_egdes(edges, newLabels):
    """
    Mark boundary of the cut.

    :param points: edges: shape (n,); newLabels: shape(k,)

    :rtype: marked edges.
    """
    if newLabels[int(edges[0])] != newLabels[int(edges[1])]:
        edges[2] = 0
    else:
        edges[2] = 1
    return edges


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

        :param UploadSessionOffsetError val:
        :rtype: UploadSessionLookupError
        """
    return cls('incorrect_offset', val)


def get_counters():
    """Return a dictionary with the following keys::

             count-objects-checked: count of how many objects were checked
             count-objects-healthy: how many of those objects were completely
                                    healthy
             count-objects-unhealthy: how many were damaged in some way
             count-objects-unrecoverable: how many were unrecoverable
             count-corrupt-shares: how many shares were found to have
                                   corruption, summed over all objects
                                   examined
        """


def get_verbose_flag(verbose):
    """Return verbose flag ' -v' if verbose=True, and empty string otherwise,
       for programs executed as shell commands.

    Parameters
    ----------
    verbose: bool
        Verbose mode

    Returns
    -------
    verbose_flag: string
        Verbose flag for shell command
    """
    if verbose is True:
        verbose_flag = ' -v'
    else:
        verbose_flag = ''
    return verbose_flag


def percent_vo2(hr_percentage):
    """
    Converts a maximum heart rate percentage into a percentage of VO2Max based using the Swain conversion formula

    SWAIN, D. et al. (1994) Target heart rates for the development of cardiorespiratory fitness. Medicine & Science in Sports & Exercise, 26(1), p. 112-116

    args:
        hr_percentage (float): percentage of maximum heart rate

    Returns:
        float: estimated conversion to percentage of VO2Max
    """
    converted_percentage = hr_percentage * 100
    formula_result = (converted_percentage - 37.182) / 0.6463
    return formula_result / 100


def filter_missing_rna(s2bins, bins2s, rna_cov):
    """
    remove any bins that don't have 16S
    """
    for bin, scaffolds in list(bins2s.items()):
        c = 0
        for s in scaffolds:
            if s in rna_cov:
                c += 1
        if c == 0:
            del bins2s[bin]
    for scaffold, bin in list(s2bins.items()):
        if bin not in bins2s:
            del s2bins[scaffold]
    return s2bins, bins2s


def is_elastic(datasource):
    """Detect if given resource uses elastic."""
    return datasource.get('backend') == 'elastic' or datasource.get(
        'search_backend') == 'elastic'


@classmethod
def get_meta(cls, action):
    """ Get action metadata """
    return getattr(action, cls.ACTION_ATTR, {})


def is_four_prices_doji(body, top, bottom):
    """Se existir o doji de quatro preços retorna True."""
    if abs(body) > 0:
        return False
    if top > 0:
        return False
    if bottom > 0:
        return False
    return True


def horner(x, a):
    """
    Use `Horner's method <https://introcs.cs.princeton.edu/python/21function/horner.py.html>`_ to compute and return the polynomial

    .. math::

        f(x) = a_0 + a_1 x^1 + a_2 x^2 + \\ldots + a_{n-1} x^{(n-1)}

    Args:
        x (float): input
        a (list): list of polynomial coefficients

    Returns:
        float: the polynomial evaluated at `x`
    """
    result = 0
    for i in range(len(a) - 1, -1, -1):
        result = a[i] + x * result
    return result


def interleave(list_a, list_b):
    """
    >>> interleave([0, 2, 4, 6], [1, 3, 5])
    [0, 1, 2, 3, 4, 5, 6]

    https://stackoverflow.com/a/7947461
    """
    size_a, size_b = len(list_a), len(list_b)
    if size_a - size_b not in (0, 1):
        raise ValueError("The lists' sizes are too different: ({}, {})".
            format(size_a, size_b))
    res = [None] * (size_a + size_b)
    res[::2] = list_a
    res[1::2] = list_b
    return res


def get_express_checkout_details(token):
    """ GetExpressCheckoutDetails """


def get_extra_metadata(domain='llc', nx=90):
    """
    Return the extra_metadata dictionay for selected domains

    PARAMETERS
    ----------
    domain : str
        domain can be llc, aste, cs
    nx : int
        size of the face in the x direction

    RETURNS
    -------
    extra_metadata : dict
        all extra_metadata to handle multi-faceted grids
    """
    available_domains = ['llc', 'aste', 'cs']
    if domain not in available_domains:
        raise ValueError('not an available domain')
    llc = {'has_faces': True, 'ny': 13 * nx, 'nx': nx, 'ny_facets': [3 * nx,
        3 * nx, nx, 3 * nx, 3 * nx], 'face_facets': [0, 0, 0, 1, 1, 1, 2, 3,
        3, 3, 4, 4, 4], 'facet_orders': ['C', 'C', 'C', 'F', 'F'],
        'face_offsets': [0, 1, 2, 0, 1, 2, 0, 0, 1, 2, 0, 1, 2],
        'transpose_face': [False, False, False, False, False, False, False,
        True, True, True, True, True, True]}
    aste = {'has_faces': True, 'ny': 5 * nx, 'nx': nx, 'ny_facets': [int(5 *
        nx / 3.0), 0, nx, int(2 * nx / 3.0), int(5 * nx / 3.0)],
        'pad_before_y': [int(1 * nx / 3.0), 0, 0, 0, 0], 'pad_after_y': [0,
        0, 0, int(1 * nx / 3.0), int(1 * nx / 3.0)], 'face_facets': [0, 0,
        2, 3, 4, 4], 'facet_orders': ['C', 'C', 'C', 'F', 'F'],
        'face_offsets': [0, 1, 0, 0, 0, 1], 'transpose_face': [False, False,
        False, True, True, True]}
    cs = {'has_faces': True, 'ny': nx, 'nx': nx, 'ny_facets': [nx, nx, nx,
        nx, nx, nx], 'face_facets': [0, 1, 2, 3, 4, 5], 'facet_orders': [
        'F', 'F', 'F', 'F', 'F', 'F'], 'face_offsets': [0, 0, 0, 0, 0, 0],
        'transpose_face': [False, False, False, False, False, False]}
    if domain == 'llc':
        extra_metadata = llc
    elif domain == 'aste':
        extra_metadata = aste
    elif domain == 'cs':
        extra_metadata = cs
    return extra_metadata


@staticmethod
def _get_variation_id(value, capital=False):
    """ Convert an integer value to a character. a-z then double aa-zz etc
        Args:
            value (int): integer index we're looking up
            capital (bool): whether we convert to capitals or not
        Returns (str): alphanumeric representation of the index
        """
    value = int(value)
    base_power = base_start = base_end = 0
    while value >= base_end:
        base_power += 1
        base_start = base_end
        base_end += pow(26, base_power)
    base_index = value - base_start
    alphas = ['a'] * base_power
    for index in range(base_power - 1, -1, -1):
        alphas[index] = chr(int(97 + base_index % 26))
        base_index /= 26
    characters = ''.join(alphas)
    return characters.upper() if capital else characters


def pad_packed_tensor(input, lengths, value, l_min=None):
    """Pads a packed batch of variable length tensors with given value.

    Parameters
    ----------
    input : Tensor
        The input tensor with shape :math:`(N, *)`
    lengths : list or tensor
        The array of tensor lengths (of the first dimension) :math:`L`.
        It should satisfy :math:`\\sum_{i=1}^{B}L_i = N`,
        where :math:`B` is the length of :math:`L`.
    value : float
        The value to fill in the tensor.
    l_min : int or None, defaults to None.
        The minimum length each tensor need to be padded to, if set to None,
        then there is no minimum length requirement.

    Returns
    -------
    Tensor
        The obtained tensor with shape :math:`(B, \\max(\\max_i(L_i), l_{min}), *)`
    """
    pass


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

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


def no_devices():
    """
    Returns an empty list

    :return: []
    """
    return []


@staticmethod
def create_attrinfos(classinfos):
    """Browse all class in classinfos dict to create a final attrinfo dict

        Parameters
        ----------
        classinfos : `dict`
            The final classinfos dict

        Returns
        -------
        attrinfos : `dict`
            Dictionary in which key is an attribute name and value is a dict
            with all its information.
        """
    attrinfos = {}
    for cls_key, info_index in sorted(classinfos.items(), key=lambda item:
        item[1]['index'], reverse=True):
        classinfos = info_index['attr']
        for attr_name in classinfos:
            attrinfos.setdefault(attr_name, {})
            attrinfos[attr_name].update(classinfos[attr_name])
    return attrinfos


def getDefaultTraversal(request, ob):
    """Get the default published object for the request

        Allows a default view to be added to traversal.
        Returns (ob, steps_reversed).
        """


def approximate_puso_extrema(H):
    """approximate_puso_extrema.

    Find the approximate minimum and maximum possible values that a PUSO can
    take. This is very approximate! The estimated minimum value that this
    function returns will definitely be less than or equal to the true
    minimum (most likely, it will be much less). Similarly, the estimated
    maximum value that this function returns will definitely be greater than or
    equal to the true maximum (most likely, it will be much more).

    Parameters
    ----------
    H : dict, PUSO, or PUSOMatrix object.
        ``H`` represents a PUSO. Please see ``qubovert.PUSO`` or
        ``qubovert.utils.PUSOMatrix``.

    Return
    ------
    bounds : tuple (min, max).
        The approximate minimum and maximum of the PUSO.

    """
    min_, max_ = 0, 0
    for k, v in H.items():
        if not k:
            min_ += v
            max_ += v
        else:
            min_ -= abs(v)
            max_ += abs(v)
    return min_, max_


def rhum(dew, temperature):
    """
    Calculate relative humidity from dew temperature and ambient temperature.

    This uses the range of constants which yields results accurate in the range
    -20 to 50 Celsius.

    Parameters
    ----------
    dew : ndarray
        Dew point temperature (Celsius).
    temperature : ndarray
        Ambient temperature (Celsius).

    Returns
    -------
    rhum : ndarray
        Relative humidity (%).

    References
    ----------
    http://www.vaisala.com/Vaisala%20Documents/Application%20notes/Humidity_Conversion_Formulas_B210973EN-F.pdf

    """
    m = 7.59138
    Tn = 240.7263
    rhum = 100 * 10 ** (m * (dew / (dew + Tn) - temperature / (temperature +
        Tn)))
    return rhum


def get_file_size():
    """Return the file size, in bytes."""


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

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


def partial_designs_generator(designs):
    """generator which combines the full factorial part of the design
    with the non full factorial part into a single dict

    Parameters
    ----------
    designs: iterable of tuples

    Yields
    ------
    dict
        experimental design dict

    """
    for design in designs:
        try:
            ff_part, other_part = design
        except ValueError:
            ff_part = design
            other_part = {}
        design = ff_part.copy()
        design.update(other_part)
        yield design


def create_topic(Name=None):
    """
    Creates a topic to which notifications can be published. Users can create at most 100,000 topics. For more information, see http://aws.amazon.com/sns . This action is idempotent, so if the requester already owns a topic with the specified name, that topic's ARN is returned without creating a new topic.
    See also: AWS API Documentation

    :example: response = client.create_topic(
        Name='string'
    )

    :type Name: string
    :param Name: [REQUIRED]
            The name of the topic you want to create.
            Constraints: Topic names must be made up of only uppercase and lowercase ASCII letters, numbers, underscores, and hyphens, and must be between 1 and 256 characters long.

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

    """
    pass


def break_by_timegap(points, timegap=360):
    """Break into trip segments when time recorded between points is
       > timegap variable and group points by segment number in a dictionary"""
    trips = []
    group = 1
    for idx, row in enumerate(points):
        dt = row['timestamp_UTC']
        if idx == 0:
            previous_row = row
            period = 0
        else:
            period = int((dt - previous_row['timestamp_UTC']).total_seconds())
            if period > timegap:
                group += 1
            previous_row = row
        row['segment_group'] = group
        row['break_period'] = period
        row['note'] = ''
        row['merge_codes'] = []
        trips.append(dict(row))
    segment_groups = {}
    for t in trips:
        segment_groups.setdefault(t['segment_group'], []).append(t)
    return segment_groups


@classmethod
def get_integration_smearing_method(cls, calc, **kwargs):
    """Return the smearing method name as string."""
    smearing = cls._get_raw_integration_smearing_method(calc, **kwargs)
    if smearing is None:
        return None
    if smearing in cls._smearing_aliases:
        return cls._smearing_aliases[smearing]
    return 'other'


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


def external_url(refname):
    """
        Attempts to guess an absolute URL for the external identifier
        given.

        Note that this just returns the refname with an ".ext" suffix.
        It will be up to whatever is interpreting the URLs to map it
        to an appropriate documentation page.
    """
    return '/%s.ext' % refname


def get_title():
    """Return the document title.
        """


def with_metaclass(meta, *bases):
    """Create a base class with a metaclass."""
    return meta('NewBase', bases, {})


@classmethod
def greyple(cls):
    """A factory method that returns a :class:`Colour` with a value of ``0x99aab5``."""
    return cls(10070709)


@staticmethod
def _isSingleCharacter(keychr):
    """Check whether given keyboard character is a single character.

        Parameters: key character which will be checked.
        Returns: True when given key character is a single character.
        """
    if not keychr:
        return False
    if len(keychr) == 1:
        return True
    return keychr.count('<') == 1 and keychr.count('>') == 1 and keychr[0
        ] == '<' and keychr[-1] == '>'


def raw_to_series(df, idx, val):
    """Convert data frame to series with multi-index."""
    d = df.set_index(list(map(str, idx)))
    s = df[val]
    s.index = d.index
    return s


def style_spectrum_plot(ax, log_freqs, log_powers):
    """Apply style and aesthetics to a power spectrum plot.

    Parameters
    ----------
    ax : matplotlib.Axes
        Figure axes to apply styling to.
    log_freqs : bool
        Whether the frequency axis is plotted in log space.
    log_powers : bool
        Whether the power axis is plotted in log space.
    """
    xlabel = 'Frequency' if not log_freqs else 'log(Frequency)'
    ylabel = 'Power' if not log_powers else 'log(Power)'
    ax.set_xlabel(xlabel, fontsize=20)
    ax.set_ylabel(ylabel, fontsize=20)
    ax.tick_params(axis='both', which='major', labelsize=16)
    ax.grid(True)
    if ax.get_legend_handles_labels()[0]:
        ax.legend(prop={'size': 16}, loc='upper right')


def read_reject_parameters(fname):
    """Read rejection parameters from .cov or .ave config file.

    Parameters
    ----------
    fname : str
        Filename to read.

    Returns
    -------
    params : dict
        The rejection parameters.
    """
    with open(fname, 'r') as f:
        lines = f.readlines()
    reject_names = ['gradReject', 'magReject', 'eegReject', 'eogReject',
        'ecgReject']
    reject_pynames = ['grad', 'mag', 'eeg', 'eog', 'ecg']
    reject = dict()
    for line in lines:
        words = line.split()
        if words[0] in reject_names:
            reject[reject_pynames[reject_names.index(words[0])]] = float(words
                [1])
    return reject


def __ne__(A, other):
    """Returns true if both objects are not equal"""
    return not A == other


def trunc(s, length):
    """Truncate a string to a given length.

    The string is truncated by cutting off the last (length-4) characters
    and replacing them with ' ...'
    """
    if s and len(s) > length:
        return s[:length - 4] + ' ...'
    else:
        return s


def get_cls_import_path(cls):
    """Return the import path of a given class"""
    module = cls.__module__
    if module is None or module == str.__module__:
        return cls.__name__
    return module + '.' + cls.__name__


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 url(txt):
    """convert text to a url

    this is quite conservative, since relative urls are supported
    """
    txt = txt.strip('\t\r\n \'"')
    if txt:
        return txt


def reshape_fortran(tensor, shape):
    """The missing Fortran reshape for mx.NDArray

    Parameters
    ----------
    tensor : NDArray
        source tensor
    shape : NDArray
        desired shape

    Returns
    -------
    output : NDArray
        reordered result
    """
    return tensor.T.reshape(tuple(reversed(shape))).T


def make_internal():
    """Make active text file internal

    """
    pass


def polynomial_reduce_mod(poly, polymod, p):
    """Reduce poly by polymod, integer arithmetic modulo p.

  Polynomials are represented as lists of coefficients
  of increasing powers of x."""
    assert polymod[-1] == 1
    assert len(polymod) > 1
    while len(poly) >= len(polymod):
        if poly[-1] != 0:
            for i in range(2, len(polymod) + 1):
                poly[-i] = (poly[-i] - poly[-1] * polymod[-i]) % p
        poly = poly[0:-1]
    return poly


def calculate_change(current_value, previous_value):
    """
    Calculate change in value given current value and previous value. Can be either +ve or -ve
    :param current_value: str
    :param previous_value: str
    :return: str or na (convert number to string to make data type consistent)
    """
    if not previous_value:
        pass
    else:
        diff = int(current_value) - int(previous_value)
        if int(previous_value):
            return str(diff / int(previous_value))
    return 'na'


def failed(obj):
    """Return a Boolean that indicates if the value is an instance of smonad.types.ftry.Failure

    >>> from smonad.types.ftry import Failure, Success
    >>> failed(Failure('shit is fucked up'))
    True
    >>> failed(Success('it worked!'))
    False
    """
    from smonad.types.ftry import Try, Failure
    assert isinstance(obj, Try)
    return isinstance(obj, Failure)


def calculate_absolute_position_non_replaced_height(node, context):
    """Implements S10.6.7"""
    raise NotImplementedError('Section 10.6.7')


@classmethod
def fetch_user_by_email(cls, email):
    """return User object for given email, or return None if not found"""
    users = cls.list(email=email)
    return users and users[0] or None


def bunch_kwargs(parser, positional=[], **kwargs):
    """Makes object from arguments dict. used to have common interface
    for arguments passed to main() from command line or calling script."""
    arg = parser.parse_args(positional)
    vars(arg).update(kwargs)
    return arg


def build_option_parser(parser):
    """Hook to add global options"""
    return parser


def formula_2006(foyer_fiscal, period, parameters):
    """
        Restitutions d'impôt sur le revenu et degrèvements percus en l'année 'n'
        """
    ppe = foyer_fiscal('ppe', period)
    restit_imp = foyer_fiscal('restit_imp', period)
    return ppe + restit_imp


def _get_get_param(http_request, key, default=None, aslist=False):
    """Returns value from the key:value pair, of the HTTP GET request, for
    example 'service' or 'request'

    :param http_request: http_request object
    :param key: key value you need to dig out of the HTTP GET request
    """
    key = key.lower()
    value = default
    for k in http_request.args.keys():
        if k.lower() == key:
            value = http_request.args.get(k)
            if aslist:
                value = value.split(',')
    return value


def getBlacklistStatus(category):
    """Get the blacklisting status of the given category.

        Note that this only applies to the current context - the status is
        not inherited, and will default to None if not set.
        """


@classmethod
def process_keyword_query_filter(cls, query, search_params):
    """Update query dict for given keyword.

    query: dict
    search_params: dict

    return tuple (query dict, keyword_query)
    """
    keyword_query = None
    if search_params.get('keyword'):
        keyword_query = cls._process_keyword(search_params.get('keyword'))
    if keyword_query:
        if not query.get('bool'):
            query['bool'] = {'must': []}
        if not query['bool'].get('must'):
            query['bool']['must'] = []
        must_or_should = 'must' if 'must' in keyword_query['bool'
            ] else 'should'
        query['bool']['must'].append({'bool': {must_or_should:
            keyword_query['bool'][must_or_should]}})
    return query, keyword_query


def get_dwell_time(dicom_img, dcm_info):
    """ Get the dwell time or effective echo spacing.
        Returns effective echo spacing written in dcm_info for Siemens and GE
        scanners and compute it for Philips scanner as described in:
        https://www.spinozacentre.nl/wiki/index.php/NeuroWiki:Current_\\
        developments

    For further references see:
    http://support.brainvoyager.com/functional-analysis-preparation/
    27-pre-processing/459-epi-distortion-correction-echo-spacing.html
    and
    https://fsl.fmrib.ox.ac.uk/fsl/fslwiki/eddy/
    Faq#How_do_I_know_what_to_put_into_my_--acqp_file

    Parameters
    ----------
    dicom_img: dicom.dataset.FileDataset object
        one of the dicom image loaded by pydicom.
    dcm_info: dict
        dictionary containing dicom metadata.

    Returns
    -------
    dwell_time: float
        effective echo spacing in s.
    """
    manufacturer = dcm_info['Manufacturer']
    if manufacturer.upper() in ['SIEMENS', 'GE MEDICAL SYSTEMS', 'GE']:
        dwell_time = dcm_info['EffectiveEchoSpacing']
    elif manufacturer.upper() in ['PHILIPS MEDICAL SYSTEMS', 'PHILIPS']:
        gyromagnetic_proton_gamma_ratio = 42.576 * pow(10, 6)
        b0 = float(dicom_img[24, 135].value)
        water_fat_difference = 3.35 * pow(10, -6)
        delta_b0 = water_fat_difference * b0
        fourier_partial_ratio = dicom_img[24, 147].value
        acceleration_factor = dicom_img[int('2005', 16), int('140f', 16)][0][
            24, 36969].value
        nb_phase_encoding_steps = float(dicom_img[24, 137].value)
        Ny = float(nb_phase_encoding_steps) * (float(fourier_partial_ratio) /
            100)
        Ny = Ny / acceleration_factor
        BW_Nx = float(dicom_img[24, 149].value)
        water_shift_pixel = (gyromagnetic_proton_gamma_ratio * delta_b0 *
            Ny / BW_Nx)
        resonance_frequency = 42.576 * pow(10, 6)
        water_shift_hertz = b0 * water_fat_difference * resonance_frequency
        etl = float(dicom_img[24, 137].value)
        dwell_time = water_shift_pixel / (water_shift_hertz * etl /
            acceleration_factor)
    else:
        raise ValueError('Unknown manufacturer : {0}...'.format(manufacturer))
    return dwell_time


def normalise(img, mean, std):
    """
    Normalise an image with a certain mean and standard deviation. Can be different for different bands.

    Parameters
    ----------
    img : numpy.ndarray
        The image to be normalised.
    mean : float or numpy.ndarray
        Either a float to be the mean for all bands or a numpy.ndarray with the mean for each band.
    std : float or numpy.ndarray
        The same as for the means but with standard deviations instead.

    Returns
    -------
    norm_img : numpy.ndarray
        The normalised image.
    """
    norm_img = (img - mean) / std
    return norm_img


def get_allowed_edit():
    """
        Get the list of groups that are allowed to add content to the tile
        """


def expand_to_neighboring_punct(i, is_puncts):
    """
    >>> expand_to_neighboring_punct(0, [False, True, True])
    (0, 3)
    >>> expand_to_neighboring_punct(2, [True, True, False])
    (0, 3)
    >>> expand_to_neighboring_punct(1, [False, False, False])
    (1, 2)
    """
    start = i
    end = i + 1
    while start > 0 and is_puncts[start - 1]:
        start -= 1
    while end < len(is_puncts) and is_puncts[end]:
        end += 1
    return start, end


@classmethod
def _engine_python(cls, expression, record):
    """Evaluate the pythonic expression and return its value
        """
    if expression is None:
        return ''
    assert record is not None, 'Record is undefined'
    template_context = cls.template_context(record)
    return eval(expression, template_context)


def mbflow2str(flow: int):
    """unit of flow is MB
    """
    str = None
    if flow < 1024:
        return '%d Mb' % flow
    gb, mb = divmod(flow, 1024)
    if mb != 0:
        return '%d Gb %d Mb' % (gb, mb)
    else:
        return '%d Gb' % gb


def cswap(swap: int, x_2: int, x_3: int) ->(int, int):
    """
    Conditional constant-time swap.

    Parameters:
        swap (int): 0 or 1. 1 means swap.
        x_2  (int): First int.
        x_3  (int): Second int.

    Returns:
        (int, int): Formatted as (x_2, x_3)
    """
    dummy = swap * (x_2 - x_3)
    x_2 = x_2 - dummy
    x_3 = x_3 + dummy
    return x_2, x_3


def format_float_to_str(num):
    """Format number into human-readable float format.

     More precise it convert float into the string and remove redundant
     zeros from the floating part.
     It will format the number by the following examples:
     0.0000001 -> 0.0
     0.000000 -> 0.0
     37 -> 37.0
     1.0000001 -> 1.0
     1.0000011 -> 1.000001
     1.0000019 -> 1.000002

    :param num: Number to be formatted
    :return: string representation of the number
    """
    num_str = '%f' % num
    float_part = num_str.split('.')[1].rstrip('0') or '0'
    return num_str.split('.')[0] + '.' + float_part


@classmethod
def match_project_from_metric_name(cls, metric_name):
    """Parses the project from a metric resource.

        Args:
          metric_name (string): A fully-qualified path representing a metric
            resource.

        Returns:
          A string representing the project.
        """
    return cls._METRIC_PATH_TEMPLATE.match(metric_name).get('project')


def address(name=False, addressLine1=False, addressLine2=False,
    addressLine3=False, phone=False, email=False, twitterHandle=False):
    """
    *Get The HTML5 address element*

    **Key Arguments:**
        - ``name`` -- name of person
        - ``addressLine1`` -- first line of the address
        - ``addressLine2`` -- second line of the address
        - ``addressLine3`` -- third line of the address
        - ``phone`` -- telephone number
        - ``email`` -- email address
        - ``twitterHandle`` -- twitter handle

    **Return:**
        - address
    """
    falseList = [name, addressLine1, addressLine2, addressLine3, phone,
        email, twitterHandle]
    for item in falseList:
        if not item:
            item = ''
    if name:
        name = '%(name)s
' % locals()
    else:
        name = ''
    if addressLine1:
        addressLine1 = '%(addressLine1)s
' % locals()
    else:
        addressLine1 = ''
    if addressLine2:
        addressLine2 = '%(addressLine2)s
' % locals()
    else:
        addressLine2 = ''
    if addressLine3:
        addressLine3 = '%(addressLine3)s
' % locals()
    else:
        addressLine3 = ''
    if phone:
        phone = 'p: %(phone)s
' % locals()
    else:
        phone = ''
    if email:
        email = (
            'e: %(email)s
'
             % locals())
    else:
        email = ''
    if twitterHandle:
        twitterHandle = (
            't: %(twitterHandle)s
' %
            locals())
    else:
        twitterHandle = ''
    address = (
        """
        <address>
            %(name)s
            %(addressLine1)s
            %(addressLine2)s
            %(addressLine3)s
            %(phone)s
            %(email)s
            %(twitterHandle)s
        </address>
    """
         % locals())
    return address


def hash_to_bytesuri(s):
    """
    Convert in and from bytes uri format used in Registry contract
    """
    s = 'ipfs://' + s
    return s.encode('ascii').ljust(32 * (len(s) // 32 + 1), b'\x00')


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


@classmethod
def from_knx(cls, raw):
    """Parse/deserialize from KNX/IP raw data."""
    cls.test_bytesarray(raw, 1)
    if raw[0] > cls.value_max:
        return raw[0] - 256
    return raw[0]


@staticmethod
def _get_switchboard_kwargs(free_params, prev_switchboard, prev_output_dim):
    """Return the kwargs for the cls '__init__' method.

        Reference implementation, merges input into one single channel.
        Override this method for other switchboard classes.
        """
    in_channel_dim = prev_output_dim // prev_switchboard.output_channels
    return {'input_dim': prev_output_dim, 'connections': list(range(
        prev_output_dim)), 'out_channel_dim': prev_output_dim,
        'in_channel_dim': in_channel_dim}


def deg2hms(x):
    """Transform degrees to *hours:minutes:seconds* strings.

    Parameters
    ----------
    x : float
        The degree value to be written as a sexagesimal string.

    Returns
    -------
    out : str
        The input angle written as a sexagesimal string, in the
        form, hours:minutes:seconds.

    """
    from astropy.coordinates import Angle
    ac = Angle(x, unit='degree')
    hms = ac.to_string(unit='hour', sep=':', pad=True)
    return str(hms)


def _is_url_without_path_query_or_fragment(url_parts):
    """
    Determines if a URL has a blank path, query string and fragment.

    :param url_parts: A URL.
    :type url_parts:  :class:`urlparse.ParseResult`
    """
    return url_parts.path.strip('/') in ['', 'search'
        ] and url_parts.query == '' and url_parts.fragment == ''


def to_list(l):
    """
    Helper function for py2/py3 compatibility used e.g. in
    list(dict.keys())

    Don't use it for structures like list(zip(x, y)), where six.moves.zip is
    used, so it is always an iterator.
    """
    if isinstance(l, list):
        return l
    else:
        return list(l)


def store(data, blob):
    """Store the data into the blob
        Raises NonStorable if data is not storable.
        """


def is_array(obj):
    """
    Checks if a given sequence is a numpy Array object.

    Parameters
    ----------
    obj : object
        The input argument.

    Returns
    -------
    test result : bool
        The test result of whether seq is a numpy Array or not.

    >>> import numpy as np

    >>> is_array([1, 2, 3, 4, 5])
    False

    >>> is_array(np.array([1, 2, 3, 4, 5]))
    True
    """
    return hasattr(obj, 'dtype')


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


@classmethod
def from_other_object(cls, other_object, sub_face=False):
    """Initialize Surface boundary condition from an adjacent other object.

        Args:
            other_object: Another object (Face, Aperture, Door) of the same type
                that this boundary condition is assigned.  This other_object will be
                set as the adjacent object in this boundary condition.
            sub_face: Boolean to note whether this boundary condition is applied to a
                sub-face (an Aperture or a Door) instead of a Face. Default: False.
        """
    error_msg = (
        'Surface boundary conditions can only be assigned to objects with parent Rooms.'
        )
    bc_objects = [other_object.identifier]
    if other_object.has_parent:
        bc_objects.append(other_object.parent.identifier)
        if sub_face:
            if other_object.parent.has_parent:
                bc_objects.append(other_object.parent.parent.identifier)
            else:
                raise AttributeError(error_msg)
    else:
        raise AttributeError(error_msg)
    return cls(bc_objects, sub_face)


def sub_size_tag_from_sub_size(sub_size):
    """Generate a sub-grid tag, to customize phase names based on the sub-grid size used.

    This changes the phase name 'phase_name' as follows:

    sub_size = None -> phase_name
    sub_size = 1 -> phase_name_sub_size_2
    sub_size = 4 -> phase_name_sub_size_4
    """
    return '__sub_' + str(sub_size)


def transform_point(point, matrix):
    """Transform point by matrix.

    :param list point: 2-item list
    :param list matrix: 6-item list representing transformation matrix
    :returns list: 2-item transformed point
    """
    x, y = point
    a, b, c, d, e, f = matrix
    new_x = x * a + y * c + e
    new_y = x * b + y * d + f
    return [new_x, new_y]


@classmethod
def get_friendly_name(cls):
    """Returns a human-readable name of the curve that can be
        used in messages."""
    return 'accumulation curve'


def makeDirectory(path):
    """Create the given path as a directory. (Returns successfully without
        doing anything if the directory already exists.)
        """


@classmethod
def preprocess(cls, data):
    """
        A preprocessor for the order form data that can be overridden
        by custom form classes. The default preprocessor here handles
        copying billing fields to shipping fields if "same" checked.
        """
    if data.get('same_billing_shipping', '') == 'on':
        for field in data:
            bill_field = field.replace('shipping_detail', 'billing_detail')
            if field.startswith('shipping_detail') and bill_field in data:
                data[field] = data[bill_field]
    return data


def _toggle_instance(instance, new_value, old_value):
    """Alter instance upon visually toggling it"""
    instance.data['publish'] = new_value


def _write_string(record, sub_string, pos):
    """Function that actually writes the generated strings to a 'stream"""
    new_pos = pos + len(sub_string)
    if pos > len(record):
        record = record.ljust(pos)
        out = record + sub_string
    elif pos == len(record):
        out = record + sub_string
    elif pos < len(record):
        out = record[:pos] + sub_string + record[new_pos:]
    return new_pos, out


def update_headerlet_phdu(tweakwcs_item, headerlet):
    """Update the primary header data unit keywords of a headerlet object in-place

    Parameters
    ==========
    tweakwcs_item :
        Basically the output from tweakwcs which contains the cross match and fit information for every chip
        of every valid input image.

    headerlet : headerlet object
        object containing WCS information
    """
    rms_ra = tweakwcs_item.meta['fit_info']['RMS_RA'].value
    rms_dec = tweakwcs_item.meta['fit_info']['RMS_DEC'].value
    fit_rms = tweakwcs_item.meta['fit_info']['FIT_RMS']
    nmatch = tweakwcs_item.meta['fit_info']['nmatches']
    catalog = tweakwcs_item.meta['fit_info']['catalog']
    fit_method = tweakwcs_item.meta['fit method']
    x_shift = tweakwcs_item.meta['fit_info']['shift'][0]
    y_shift = tweakwcs_item.meta['fit_info']['shift'][1]
    rot = tweakwcs_item.meta['fit_info']['rot']
    scale = tweakwcs_item.meta['fit_info']['scale'][0]
    skew = tweakwcs_item.meta['fit_info']['skew']
    primary_header = headerlet[0].header
    primary_header['RMS_RA'] = rms_ra
    primary_header['RMS_DEC'] = rms_dec
    primary_header['NMATCH'] = nmatch
    primary_header['CATALOG'] = catalog
    primary_header['FITMETH'] = fit_method
    primary_header['FIT_RMS'
        ] = fit_rms, 'RMS (mas) of the 2D fit of the headerlet solution'
    primary_header['HISTORY'] = '~~~~~ FIT PARAMETERS ~~~~~'
    primary_header['HISTORY'] = '{:>15} : {:9.4f} "/pixels'.format('platescale'
        , tweakwcs_item.wcs.pscale)
    primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('x_shift',
        x_shift)
    primary_header['HISTORY'] = '{:>15} : {:9.4f} pixels'.format('y_shift',
        y_shift)
    primary_header['HISTORY'] = '{:>15} : {:9.4f} degrees'.format('rotation',
        rot)
    primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('scale', scale)
    primary_header['HISTORY'] = '{:>15} : {:9.4f}'.format('skew', skew)


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def scale_image(ar, n):
    """Given a 2d numpy array, return a version of the array created by
    replacing each cell with an n by n square of cells.

    This is useful if you don't want each cell of your cellular automaton
    picture to appear larger than 1 pixel. """
    return ar.repeat(n, axis=0).repeat(n, axis=1)


@classmethod
def RegisterParsers(cls, parser_classes):
    """Registers parser classes.

    The parser classes are identified based on their lower case name.

    Args:
      parser_classes (list[type]): parsers classes (subclasses of BaseParser).

    Raises:
      KeyError: if parser class is already set for the corresponding name.
    """
    for parser_class in parser_classes:
        cls.RegisterParser(parser_class)


def duplicate_move_linked(OBJECT_OT_duplicate=None, TRANSFORM_OT_translate=None
    ):
    """Duplicate selected objects and move them

    :param OBJECT_OT_duplicate: Duplicate Objects, Duplicate selected objects
    :param TRANSFORM_OT_translate: Translate, Translate (move) selected items
    """
    pass


def _is_open(span_str, brackets='()'):
    """Check if the span ends with an unclosed `bracket`."""
    offset = span_str.find(brackets[0])
    nesting = 0 if offset == -1 else 1
    while offset != -1:
        opener = span_str.find(brackets[0], offset + 1)
        closer = span_str.find(brackets[1], offset + 1)
        if opener == -1:
            if closer == -1:
                offset = -1
            else:
                offset = closer
                nesting -= 1
        elif closer == -1:
            offset = opener
            nesting += 1
        elif opener < closer:
            offset = opener
            nesting += 1
        elif closer < opener:
            offset = closer
            nesting -= 1
        else:
            msg = 'at offset={}: closer={}, opener={}'
            raise RuntimeError(msg.format(offset, closer, opener))
    return nesting > 0


@classmethod
def round_to_context(cls, x, ctx):
    """Not actually used?"""
    return cls.dtype._round_to_context(x, ctx=ctx, strict=False)


def list_attacks(ResourceArns=None, StartTime=None, EndTime=None, NextToken
    =None, MaxResults=None):
    """
    Returns all ongoing DDoS attacks or all DDoS attacks during a specified time period.
    See also: AWS API Documentation

    :example: response = client.list_attacks(
        ResourceArns=[
            'string',
        ],
        StartTime={
            'FromInclusive': datetime(2015, 1, 1),
            'ToExclusive': datetime(2015, 1, 1)
        },
        EndTime={
            'FromInclusive': datetime(2015, 1, 1),
            'ToExclusive': datetime(2015, 1, 1)
        },
        NextToken='string',
        MaxResults=123
    )

    :type ResourceArns: list
    :param ResourceArns: The ARN (Amazon Resource Name) of the resource that was attacked. If this is left blank, all applicable resources for this account will be included.
            (string) --

    :type StartTime: dict
    :param StartTime: The time period for the attacks.
            FromInclusive (datetime) --The start time, in the format 2016-12-16T13:50Z.
            ToExclusive (datetime) --The end time, in the format 2016-12-16T15:50Z.

    :type EndTime: dict
    :param EndTime: The end of the time period for the attacks.
            FromInclusive (datetime) --The start time, in the format 2016-12-16T13:50Z.
            ToExclusive (datetime) --The end time, in the format 2016-12-16T15:50Z.

    :type NextToken: string
    :param NextToken: The ListAttacksRequest.NextMarker value from a previous call to ListAttacksRequest . Pass null if this is the first call.

    :type MaxResults: integer
    :param MaxResults: The maximum number of AttackSummary objects to be returned. If this is left blank, the first 20 results will be returned.

    :rtype: dict
    :return: {
        'AttackSummaries': [
            {
                'AttackId': 'string',
                'ResourceArn': 'string',
                'StartTime': datetime(2015, 1, 1),
                'EndTime': datetime(2015, 1, 1),
                'AttackVectors': [
                    {
                        'VectorType': 'string'
                    },
                ]
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


@classmethod
def get_alias(cls, item_id):
    """Returns item alias by ID.

        :param int item_id: Item ID.
        :rtype: str
        """
    return cls.aliases.get(item_id)


@classmethod
def as_version(cls, number):
    """Convert version number to version object"""
    if isinstance(number, cls):
        return number
    return cls([number])


@classmethod
def createFromRunningProcesses(cls, programConfig):
    """
            createFromRunningProcesses - Create a Program using programConfig. scans all running processes, and returns a constructed Program if a match is found.

            @param programConfig <ProgramConfig.ProgramConfig> - The config for a program

            @return - A constructed "Program" if a match found, ootherwise None.

            Should not raise anything.
        """
    allMyPids = cls.getMyRunningPids()
    proctitleRE = programConfig.proctitle_re
    for pid in allMyPids:
        try:
            procCmdline = cls._getProcCmdline(pid)
            if programConfig.useshell is True and procCmdline['cmdline'
                ].startswith('/bin/sh -c'):
                continue
            if bool(proctitleRE.search(procCmdline['cmdline'])):
                prog = cls(programConfig.pidfile, pid, running=True, **
                    procCmdline)
                return prog
        except:
            pass
    return None


@staticmethod
def __is_observed__(values):
    """
        Checks if the values represent an observed evidence. If all likelihoods are 0 with exactly
        one of them being 1, then this map of values represent observed evidence.

        :param values: Map of values, where keys are values and values are likelihoods.
        :return: A boolean indicating if the values represent observed evidence.
        """
    one = 0
    zero = 0
    for k, v in values.items():
        if 1.0 == v:
            one += 1
        else:
            zero += 1
    return 1 == one and len(values) - 1 == zero


def to_s3_uri(code_dict):
    """Constructs a S3 URI string from given code dictionary

    :param dict code_dict: Dictionary containing Lambda function Code S3 location of the form
                          {S3Bucket, S3Key, S3ObjectVersion}
    :return: S3 URI of form s3://bucket/key?versionId=version
    :rtype string
    """
    try:
        uri = 's3://{bucket}/{key}'.format(bucket=code_dict['S3Bucket'],
            key=code_dict['S3Key'])
        version = code_dict.get('S3ObjectVersion', None)
    except (TypeError, AttributeError):
        raise TypeError('Code location should be a dictionary')
    if version:
        uri += '?versionId=' + version
    return uri


def join(chars=()):
    """
    Join a sequence of characters into a string.

    :param bytes chars: list of chars

    :rtype: str
    """
    return b''.join(chars).decode()


@classmethod
def pc_str_width(cls):
    """How many characters wide can pc_covered_str be?"""
    width = 3
    if cls._precision > 0:
        width += 1 + cls._precision
    return width


def __gt__(a, b):
    """ Test if Va > Vb """
    return int(a) > int(b)


def to_idx(vec, w_shape):
    """
    vec = (idn, idh, idw)
    w_shape = [n, h, w, c]
    """
    return vec[:, (2)] + w_shape[2] * (vec[:, (1)] + w_shape[1] * vec[:, (0)])


def native_string(string):
    """
    Make C{string} be the type of C{str}, decoding with ASCII if required.
    """
    if isinstance(string, bytes):
        return string.decode('ascii')
    else:
        raise ValueError('This is already a native string.')


def _jaccard(a_rows, a_cols, b_rows, b_cols):
    """Jaccard coefficient on the elements of the two biclusters."""
    intersection = (a_rows * b_rows).sum() * (a_cols * b_cols).sum()
    a_size = a_rows.sum() * a_cols.sum()
    b_size = b_rows.sum() * b_cols.sum()
    return intersection / (a_size + b_size - intersection)


@classmethod
def maptag(cls, tag, fn):
    """
        Map (override) tag => I{class} mapping.

        @param tag: An XSD tag name.
        @type tag: str
        @param fn: A function or class.
        @type fn: fn|class.

        """
    cls.tags[tag] = fn


def zener_maxcurrent(Vz, powerrating):
    """
    Vz: breakdown voltage of zener diode
    powerrating: power rating of the diode

    Returns the maximum current (in A) passing through the diode
    """
    I_max = powerrating / Vz
    return I_max


def select_less():
    """Deselect vertices at the boundary of each selection region

    """
    pass


def describe_maintenance_window_executions(WindowId=None, Filters=None,
    MaxResults=None, NextToken=None):
    """
    Lists the executions of a Maintenance Window (meaning, information about when the Maintenance Window was scheduled to be active and information about tasks registered and run with the Maintenance Window).
    See also: AWS API Documentation

    :example: response = client.describe_maintenance_window_executions(
        WindowId='string',
        Filters=[
            {
                'Key': 'string',
                'Values': [
                    'string',
                ]
            },
        ],
        MaxResults=123,
        NextToken='string'
    )

    :type WindowId: string
    :param WindowId: [REQUIRED]
            The ID of the Maintenance Window whose executions should be retrieved.

    :type Filters: list
    :param Filters: Each entry in the array is a structure containing:
            Key (string, between 1 and 128 characters)
            Values (array of strings, each string is between 1 and 256 characters)
            The supported Keys are ExecutedBefore and ExecutedAfter with the value being a date/time string such as 2016-11-04T05:00:00Z.
            (dict) --Filter used in the request.
            Key (string) --The name of the filter.
            Values (list) --The filter values.
            (string) --

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

    :type NextToken: string
    :param NextToken: The token for the next set of items to return. (You received this token from a previous call.)

    :rtype: dict
    :return: {
        'WindowExecutions': [
            {
                'WindowId': 'string',
                'WindowExecutionId': 'string',
                'Status': 'PENDING'|'IN_PROGRESS'|'SUCCESS'|'FAILED'|'TIMED_OUT'|'CANCELLING'|'CANCELLED'|'SKIPPED_OVERLAPPING',
                'StatusDetails': 'string',
                'StartTime': datetime(2015, 1, 1),
                'EndTime': datetime(2015, 1, 1)
            },
        ],
        'NextToken': 'string'
    }

    """
    pass


def expand_port_ranges(port_ranges):
    """Expand ``port_ranges`` to a :obj:`set` of ports.

    Examples:
        Here is an example usage of this function:

        >>> from cloudmarker import util
        >>> ports = util.expand_port_ranges(['22', '3389', '8080-8085'])
        >>> print(ports == {22, 3389, 8080, 8081, 8082, 8083, 8084, 8085})
        True
        >>> ports = util.expand_port_ranges(['8080-8084', '8082-8086'])
        >>> print(ports == {8080, 8081, 8082, 8083, 8084, 8085, 8086})
        True

        Note that in a port range of the form ``m-n``, both ``m`` and
        ``n`` are included in the expanded port set. If ``m > n``, we
        get an empty port set.

        >>> ports = util.expand_port_ranges(['8085-8080'])
        >>> print(ports == set())
        True

        If an invalid port range is found, it is ignored.

        >>> ports = util.expand_port_ranges(['8080', '8081a', '8082'])
        >>> print(ports == {8080, 8082})
        True
        >>> ports = util.expand_port_ranges(['7070-7075', '8080a-8085'])
        >>> print(ports == {7070, 7071, 7072, 7073, 7074, 7075})
        True

    Arguments:
        port_ranges (list): A list of strings where each string is a
            port number (e.g., ``'80'``) or port range (e.g., ``80-89``).

    Returns:
        set: A set of integers that represent the ports specified
            by ``port_ranges``.

    """
    expanded_port_set = set()
    for port_range in port_ranges:
        if port_range.isdigit():
            expanded_port_set.add(int(port_range))
            continue
        if '-' not in port_range:
            continue
        start_port, end_port = port_range.split('-', 1)
        if not start_port.isdigit() or not end_port.isdigit():
            continue
        expanded_ports = range(int(start_port), int(end_port) + 1)
        expanded_port_set.update(expanded_ports)
    return expanded_port_set


def stack(*data, **kwargs):
    """Join a sequence of arrays along a new axis.
    The axis parameter specifies the index of the new axis in the dimensions of the
    result. For example, if axis=0 it will be the first dimension and if axis=-1 it
    will be the last dimension.
    Examples::
      x = [1, 2]
      y = [3, 4]
      stack(x, y) = [[1, 2],
                     [3, 4]]
      stack(x, y, axis=1) = [[1, 3],
                             [2, 4]]

    This function support variable length of positional input.

    Parameters
    ----------
    data : Symbol[]
        List of arrays to stack
    axis : int, optional, default='0'
        The axis in the result array along which the input arrays are stacked.

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

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


def check_categories(lines):
    """
  find out how many row and col categories are available
  """
    rcat_line = lines[0].split('\t')
    num_rc = 0
    found_end = False
    for inst_string in rcat_line[1:]:
        if inst_string == '':
            if found_end is False:
                num_rc = num_rc + 1
        else:
            found_end = True
    max_rcat = 15
    if max_rcat > len(lines):
        max_rcat = len(lines) - 1
    num_cc = 0
    for i in range(max_rcat):
        ccat_line = lines[i + 1].split('\t')
        if ccat_line[0] == '' and len(ccat_line) > 1:
            num_cc = num_cc + 1
    num_labels = {}
    num_labels['row'] = num_rc + 1
    num_labels['col'] = num_cc + 1
    return num_labels


def get_rule(RuleId=None):
    """
    Returns the  Rule that is specified by the RuleId that you included in the GetRule request.
    See also: AWS API Documentation

    Examples
    The following example returns the details of a rule with the ID example1ds3t-46da-4fdb-b8d5-abc321j569j5.
    Expected Output:

    :example: response = client.get_rule(
        RuleId='string'
    )

    :type RuleId: string
    :param RuleId: [REQUIRED]
            The RuleId of the Rule that you want to get. RuleId is returned by CreateRule and by ListRules .

    :rtype: dict
    :return: {
        'Rule': {
            'RuleId': 'string',
            'Name': 'string',
            'MetricName': 'string',
            'Predicates': [
                {
                    'Negated': True|False,
                    'Type': 'IPMatch'|'ByteMatch'|'SqlInjectionMatch'|'SizeConstraint'|'XssMatch',
                    'DataId': 'string'
                },
            ]
        }
    }

    """
    pass


def context_set_value(data_path: str='', value: str=''):
    """Set a context value

    :param data_path: Context Attributes, RNA context string
    :type data_path: str
    :param value: Value, Assignment value (as a string)
    :type value: str
    """
    pass


def axes_to_canvas(item, x, y):
    """Convert (x,y) from axes coordinates to canvas coordinates system"""
    plot, ax, ay = item.plot(), item.xAxis(), item.yAxis()
    return plot.transform(ax, x), plot.transform(ay, y)


@classmethod
def has_connection(cls, pid, connection):
    """Check to see if a pool has the specified connection

        :param str pid: The pool ID
        :param connection: The connection to check for
        :type connection: psycopg2.extensions.connection
        :rtype: bool

        """
    with cls._lock:
        cls._ensure_pool_exists(pid)
        return connection in cls._pools[pid]


@classmethod
def list(cls, page_size: int=None, next_token: str=None, sort: str=None,
    amino_acids: str=None, archive_reason: str=None, folder_id: str=None,
    modified_at: str=None, name: str=None, project_id: str=None, schema_id:
    str=None, registry_id: str=None, **kwargs):
    """List :class:`AASequence` models.

        :param page_size: Number of results to return. Defaults to 50, maximum of 100.
        :param next_token: Token for pagination
        :param sort: Method by which to order search results. Valid sorts are modifiedAt
                (modified time, most recent first) and name (entity name, alphabetical).
                 Optionally add :asc or :desc to specify ascending or descending order.
                 Default is modifiedAt.
        :param archive_reason: Archive reason. Restricts DNA Sequences to those with the
                specified archive reason. Use “NOT_ARCHIVED” to filter for unarchived
                DNA Sequences.
        :param folder_id: ID of a folder. Restricts results to those in the folder.
        :param modified_at: Datetime, in RFC 3339 format. Supports the > and <
                operators. Time zone defaults to UTC. Restricts results to those
                modified in the specified range. e.g. > 2017-04-30.
        :param name: Name of a DNA Sequence. Restricts results to those with the
                specified name.
        :param project_id: ID of a project. Restricts results to those in the project.
        :param schema_id: ID of a schema. Restricts results to those of the specified
                schema.
        :param registry_id: ID of a registry. Restricts results to those registered in
                this registry.
        :return:
        """
    return super().list(page_size=page_size, next_token=next_token, sort=
        sort, amino_acids=amino_acids, modified_at=modified_at, name=name,
        folder_id=folder_id, project_id=project_id, schema_id=schema_id,
        archive_reason=archive_reason, registry_id=registry_id, **kwargs)


def multiply_matrix(matrix: 'mathutils.Matrix'):
    """Multiply the current stack matrix.

    :param matrix: A 4x4 matrix.
    :type matrix: 'mathutils.Matrix'
    """
    pass


@classmethod
def _from_xml(cls, node, path):
    """Create an instance of this class from an XML node.

        Parameters
        ----------
        node : :class:`lxml.etree.Element`
            The node to parse.
        path : str
            The string path where the XML file is located (used for resolving
            the location of mesh or image files).

        Returns
        -------
        obj : :class:`URDFType`
            An instance of this class parsed from the node.
        """
    return cls(**cls._parse(node, path))


@classmethod
def is_type_match(cls, data_type):
    """
        Returns whether the given type is the same type of the file or not
        :param data_type: str
        :return: bool
        """
    return data_type == cls.get_data_type()


@staticmethod
def __new__(*args, **kwargs):
    """ Create and return a new object.  See help(type) for accurate signature. """
    pass


@classmethod
def worldZX(cls):
    """Construct the world ZX frame.

        Returns
        -------
        :class:`compas.geometry.Frame`
            The world ZX frame.

        Examples
        --------
        >>> frame = Frame.worldZX()
        >>> frame.point
        Point(0.000, 0.000, 0.000)
        >>> frame.xaxis
        Vector(0.000, 0.000, 1.000)
        >>> frame.yaxis
        Vector(1.000, 0.000, 0.000)
        """
    return cls([0, 0, 0], [0, 0, 1], [1, 0, 0])


def filter_by_dept_abbrevs(frame, dept_list):
    """Uses the list of departments defined by the user to
    return those departments from the results frame"""
    return frame[frame['dept_acro'].isin(dept_list)]


def validate_cipher_suite_id(cipher_suite_id):
    """Validates that a CipherSuite conforms to the proper format.

    Args:
        cipher_suite_id (int): CipherSuite id.

    Returns:
        (int): The original CipherSuite id.

    """
    if not isinstance(cipher_suite_id, int):
        raise TypeError('CipherSuite ID must be of type int.')
    if not 0 <= cipher_suite_id <= 3:
        raise ValueError('Invalid CipherSuite.')
    return cipher_suite_id


def render_git_describe(pieces):
    """TAG[-DISTANCE-gHEX][-dirty].

    Like 'git describe --tags --dirty --always'.

    Exceptions:
    1: no tags. HEX[-dirty]  (note: no 'g' prefix)
    """
    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if pieces['distance']:
            rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
    else:
        rendered = pieces['short']
    if pieces['dirty']:
        rendered += '-dirty'
    return rendered


def html_escape(string):
    """ Escape HTML special characters ``&<>`` and quotes ``'"``. """
    return string.replace('&', '&').replace('<', '<').replace('>',
        '>').replace('"', '"').replace("'", ''')


@classmethod
def custom(cls, mu=1.0, pi=None, W=None, **kwargs):
    """
        Create a GTR model by specifying the matrix explicitly

        Parameters
        ----------

         mu : float
            Substitution rate

         W : nxn matrix
            Substitution matrix

         pi : n vector
            Equilibrium frequencies

         **kwargs:
            Key word arguments to be passed

        Keyword Args
        ------------

         alphabet : str
            Specify alphabet when applicable. If the alphabet specification is
            required, but no alphabet is specified, the nucleotide alphabet will be used as
            default.

        """
    gtr = cls(**kwargs)
    gtr.assign_rates(mu=mu, pi=pi, W=W)
    return gtr


@staticmethod
def user_parse(data):
    """Parse information from the provider."""
    yield 'id', data.get('id') or data.get('user_id')
    first_name, _, last_name = data['name'].partition(' ')
    yield 'first_name', first_name
    yield 'last_name', last_name
    yield 'email', data.get('email')
    yield 'picture', data.get('profile_image_url')
    yield 'locale', data.get('lang')
    yield 'link', data.get('url')
    yield 'username', data.get('screen_name')
    city, _, country = map(lambda s: s.strip(), data.get('location', '').
        partition(','))
    yield 'city', city
    yield 'country', country


@classmethod
def create_folder(cls, folder_name: str):
    """Crete folder in root program directory, if not exists."""
    data_path = cls.get_root_path() / folder_name
    if not data_path.exists():
        data_path.mkdir(parents=True, exist_ok=True)


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 extract_metadata(name):
    """ Try to determine metadata from video title. """
    seps = name.count(' - ')
    artist = title = None
    if seps == 1:
        pos = name.find(' - ')
        artist = name[:pos].strip()
        title = name[pos + 3:].strip()
    else:
        title = name.strip()
    return dict(artist=artist, title=title)


def _ErlList(elements):
    """An Erlang list. This maps to a python list."""
    return elements


@property
def registered_hooks(cls):
    """
        A generator of all registered hooks.
        """
    if not cls.abstract:
        raise TypeError(
            'registered_hooks property accessed on a non-abstract hook')
    for hook in cls._registered_hooks.values():
        yield hook


def unsubscribe(requestor, service, nodeIdentifier, subscriber):
    """
        Called when a subscribe request has been received.

        @param requestor: The entity the request originated from.
        @type requestor: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param service: The entity the request was addressed to.
        @type service: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @param nodeIdentifier: The identifier of the node to unsubscribe from.
        @type nodeIdentifier: C{unicode}
        @param subscriber: The entity to be unsubscribed.
        @type subscriber: L{JID<twisted.words.protocols.jabber.jid.JID>}
        @return: A deferred that fires with C{None} when unsubscription has
                 succeeded.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


@staticmethod
def _remove_node(node, nodes, constraints):
    """
        Returns a new set where node has been removed from nodes, subject to
        symmetry constraints. We know, that for every constraint we have
        those subgraph nodes are equal. So whenever we would remove the
        lower part of a constraint, remove the higher instead.
        """
    while True:
        for low, high in constraints:
            if low == node and high in nodes:
                node = high
                break
        else:
            break
    return frozenset(nodes - {node})


def get_fully_qualified_name(instance: object) ->str:
    """
    Get at the fully qualified name of an object, e.g.
    an instance of a :class:`~py_trees.composites.Sequence`
    becomes 'py_trees.composites.Sequence'.

    Args:
        instance (:obj:`object`): an instance of any class

    Returns:
        :obj:`str`: the fully qualified name
    """
    module = instance.__class__.__module__
    builtin = str.__class__.__module__
    if module is None or module == builtin:
        return instance.__class__.__name__
    else:
        return module + '.' + instance.__class__.__name__


def copy_tracks():
    """Copy selected tracks to clipboard

    """
    pass


@classmethod
def create(cls, _attributes=None, **attributes):
    """
        Save a new model an return the instance.

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

        :return: The new instance
        :rtype: Model
        """
    if _attributes is not None:
        attributes.update(_attributes)
    model = cls(**attributes)
    model.save()
    return model


@classmethod
def get_image_prefix(cls):
    """
        Return filename prefix.

        For example, Icons8 icons are all prefixed with `icons8-`, so that you can call your icons
        without repeating the prefix in the name.
        """
    return ''


def screw(steps: int=9, turns: int=1, center: float=(0.0, 0.0, 0.0), axis:
    float=(0.0, 0.0, 0.0)):
    """Extrude selected vertices in screw-shaped rotation around the cursor in indicated viewport

    :param steps: Steps, Steps
    :type steps: int
    :param turns: Turns, Turns
    :type turns: int
    :param center: Center, Center in global view space
    :type center: float
    :param axis: Axis, Axis in global view space
    :type axis: float
    """
    pass


def ellipsis(source, max_length):
    """Truncates a string to be at most max_length long."""
    if max_length == 0 or len(source) <= max_length:
        return source
    return source[:max(0, max_length - 3)] + '...'


def getPrincipalsForRole(role_id):
    """Get the principals that have been granted a role.

        Return the list of (principal id, setting) who have been assigned or
        removed from a role.

        If no principals have been assigned this role,
        then the empty list is returned.
        """


def find_sorted_peaks(x):
    """Find peaks, i.e. local maxima, of an array. Interior points are peaks if
    they are greater than both their neighbors, and edge points are peaks if
    they are greater than their only neighbor. In the case of ties, we
    (arbitrarily) choose the first index in the sequence of equal values as the
    peak.
    Returns a list of tuples (i, x[i]) of peak indices i and values x[i],
    sorted in decreasing order by peak value.
    """
    peak_inds = []
    nbins = len(x)
    for i in range(nbins):
        if i == 0 or x[i] > x[i - 1]:
            if i == nbins - 1 or x[i] > x[i + 1]:
                peak_inds.append(i)
            elif x[i] == x[i + 1]:
                for j in range(i + 1, nbins):
                    if x[j] != x[i]:
                        if x[j] < x[i]:
                            peak_inds.append(i)
                        break
                if j == nbins - 1 and x[i] == x[j]:
                    peak_inds.append(i)
    sorted_peak_inds = sorted(peak_inds, key=lambda i: x[i], reverse=True)
    return list(zip(sorted_peak_inds, x[sorted_peak_inds]))


def delWidget(pageIndex, columnIndex, widgetIndex, retJson=True):
    """ Delete specific widget from current dashboard.

        @param pageIndex
        index of page the widget lies on( start from 0 )

        @param columnIndex
        index of column the widget lies on( start from 0 )

        @param widgetIndex
        index of the widget, count from top to bottom( start from 0 )

        @retJson
        format return value to json format or not( default True )

        @return
        a dict contains state of process, format like:
        {
            'success': True,
            'msg': 'Delete widget success.'
        }

        """


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

    The ".dev0" means dirty.

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


def _get_chunks(shape, ncpu):
    """Split the array into equal sized chunks based on the number of
    available processors. The last chunk in each dimension absorbs the
    remainder array elements if the number of CPUs does not divide evenly into
    the number of array elements.

    Examples
    --------
    >>> _get_chunks((4, 4), 4)
    ((2, 2), (2, 2))
    >>> _get_chunks((4, 4), 2)
    ((2, 2), (4,))
    >>> _get_chunks((5, 5), 2)
    ((2, 3), (5,))
    >>> _get_chunks((2, 4), 2)
    ((1, 1), (4,))
    """
    from math import ceil
    chunks = []
    nchunks_per_dim = int(ceil(ncpu ** (1.0 / len(shape))))
    used_chunks = 1
    for i in shape:
        if used_chunks < ncpu:
            regular_chunk = i // nchunks_per_dim
            remainder_chunk = regular_chunk + i % nchunks_per_dim
            if regular_chunk == 0:
                chunk_lens = remainder_chunk,
            else:
                chunk_lens = (regular_chunk,) * (nchunks_per_dim - 1) + (
                    remainder_chunk,)
        else:
            chunk_lens = i,
        chunks.append(chunk_lens)
        used_chunks *= nchunks_per_dim
    return tuple(chunks)


def _join_translated(translated_parts, os_sep_class):
    """Join translated glob pattern parts.

    This is different from a simple join, as care need to be taken
    to allow ** to match ZERO or more directories.
    """
    res = ''
    for part in translated_parts[:-1]:
        if part == '.*':
            res += part
        else:
            res += part + os_sep_class
    if translated_parts[-1] == '.*':
        res += '.+'
        res += '({os_sep_class}?.*)?'.format(os_sep_class=os_sep_class)
    else:
        res += translated_parts[-1]
    return res


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

        :param TeamMemberInfo val:
        :rtype: MembersGetInfoItem
        """
    return cls('member_info', val)


def _get_options_group(group=None):
    """Get a specific group of options which are allowed."""
    hex_options = frozenset(['--check-sigs', '--default-key',
        '--default-recipient', '--delete-keys', '--delete-secret-keys',
        '--delete-secret-and-public-keys', '--desig-revoke', '--export',
        '--export-secret-keys', '--export-secret-subkeys', '--fingerprint',
        '--gen-revoke', '--hidden-encrypt-to', '--hidden-recipient',
        '--list-key', '--list-keys', '--list-public-keys',
        '--list-secret-keys', '--list-sigs', '--recipient', '--recv-keys',
        '--send-keys', '--edit-key', '--sign-key'])
    unchecked_options = frozenset(['--list-options', '--passphrase-fd',
        '--status-fd', '--verify-options', '--command-fd'])
    other_options = frozenset(['--debug-level', '--keyserver'])
    dir_options = frozenset(['--homedir'])
    keyring_options = frozenset(['--keyring', '--primary-keyring',
        '--secret-keyring', '--trustdb-name'])
    file_or_none_options = frozenset(['--decrypt', '--decrypt-files',
        '--encrypt', '--encrypt-files', '--import', '--verify',
        '--verify-files', '--output'])
    pref_options = frozenset(['--digest-algo', '--cipher-algo',
        '--compress-algo', '--compression-algo', '--cert-digest-algo',
        '--personal-digest-prefs', '--personal-digest-preferences',
        '--personal-cipher-prefs', '--personal-cipher-preferences',
        '--personal-compress-prefs', '--personal-compress-preferences',
        '--pinentry-mode', '--print-md', '--trust-model'])
    none_options = frozenset(['--allow-loopback-pinentry', '--always-trust',
        '--armor', '--armour', '--batch', '--check-sigs', '--check-trustdb',
        '--clearsign', '--debug-all', '--default-recipient-self',
        '--detach-sign', '--export', '--export-ownertrust',
        '--export-secret-keys', '--export-secret-subkeys', '--fingerprint',
        '--fixed-list-mode', '--gen-key', '--import-ownertrust',
        '--list-config', '--list-key', '--list-keys', '--list-packets',
        '--list-public-keys', '--list-secret-keys', '--list-sigs',
        '--lock-multiple', '--lock-never', '--lock-once',
        '--no-default-keyring', '--no-default-recipient',
        '--no-emit-version', '--no-options', '--no-tty', '--no-use-agent',
        '--no-verbose', '--print-mds', '--quiet', '--sign', '--symmetric',
        '--throw-keyids', '--use-agent', '--verbose', '--version',
        '--with-colons', '--yes'])
    hex_or_none_options = hex_options.intersection(none_options)
    allowed = hex_options.union(unchecked_options, other_options,
        dir_options, keyring_options, file_or_none_options, pref_options,
        none_options)
    if group and group in locals().keys():
        return locals()[group]


def read_epi_params(item_basename):
    """Read all the necessary EPI parameters from text files with the given basename.

    Args:
        basename (str): The basename for all the files we need to read.
            In particular the following files should exist:
                - basename + '.read_out_time.txt' (with the read out time)
                - basename + '.phase_enc_dir.txt' (with the phase encode direction, like AP, PA, LR, RL, SI, IS, ...)

    Returns:
        dict: A dictionary for use in the nipype workflow 'all_peb_pipeline'. It contains the keys:
            - read_out_time (the read out time of the scan)
            - enc_dir (the phase encode direction, converted to nipype standards (x, -x, y, -y, ...))
    """
    with open(item_basename + '.read_out_times.txt', 'r') as f:
        read_out_time = float(f.read())
    with open(item_basename + '.phase_enc_dir.txt', 'r') as f:
        phase_encoding = f.read()
    phase_enc_dirs_translate = {'AP': 'y-', 'PA': 'y', 'LR': 'x-', 'RL':
        'x', 'SD': 'x-', 'DS': 'x', 'SI': 'z-', 'IS': 'z', 'HF': 'z-', 'FH':
        'z'}
    return {'read_out_time': read_out_time, 'enc_dir':
        phase_enc_dirs_translate[phase_encoding]}


def DiffLocals(OldLocals, NewLocals):
    """
	return dictionary of values that are different.
	"""
    DiffDict = {}
    for k, v in NewLocals.items():
        if k in OldLocals:
            if not OldLocals[k] is v:
                DiffDict[k] = v
        else:
            DiffDict[k] = v
    return DiffDict


@classmethod
def _from_dict(cls, _dict):
    """Initialize a Category object from a json dictionary."""
    args = {}
    if 'label' in _dict:
        args['label'] = _dict.get('label')
    if 'provenance_ids' in _dict:
        args['provenance_ids'] = _dict.get('provenance_ids')
    return cls(**args)


def createAndAdd(data):
    """Create and return an object that has been added to the context.

        The data argument is a dictionary with values supplied by the
        form.

        If any user errors occur, they should be collected into a list
        and raised as a `WidgetsError`.

        This is normally expected to simply call the create() and
        add() methods.

        """


def is_plugin_section(secname):
    """Check whether ``secname`` starts with ``plugin:``."""
    return secname.startswith('plugin:')


@classmethod
def _from_dict(cls, _dict):
    """Initialize a SemanticRolesVerb object from a json dictionary."""
    args = {}
    if 'text' in _dict:
        args['text'] = _dict.get('text')
    if 'tense' in _dict:
        args['tense'] = _dict.get('tense')
    return cls(**args)


def down(f):
    """Perform computation rounding down."""
    return f()


def log1p(img):
    """
        Element-wise log of 1 + an `Image`.

        If the `Image` is empty, returns the empty `Image`.

        Example
        -------
        >>> import descarteslabs.workflows as wf
        >>> img = wf.Image.from_id("landsat:LC08:PRE:TOAR:meta_LC80270312016188_v1").pick_bands("red")
        >>> img.log1p().compute(geoctx) # doctest: +SKIP
        ImageResult:
        ...
        """
    from ..math import arithmetic
    return arithmetic.log1p(img)


@classmethod
def everything(cls):
    """
        Create a new set of everything.

        One can not iterate over the elements of this set, but many
        operations are actually well defined and useful.
        """
    res = cls([])
    res.everything = True
    return res


@classmethod
def _constructor(cls, alpha, **kwargs):
    """
        Constructs distribution and moments objects.
        """
    retval = super()._constructor(alpha, **kwargs)
    if retval[2] != cls._moments.dims:
        raise ValueError(
            'Parent has wrong dimensionality. Must be a two-dimensional vector.'
            )
    return retval[0], retval[1], retval[2], retval[3
        ], cls._distribution, cls._moments, retval[6]


def map_enum_to_dict(enum_list):
    """__map_enum_to_dict
        Maps enum types to dict of {"name": enum} pairs, for use in frontend programming/TaskTypeRestriction generation.
    Parameters
    ----------
    enum_list: list of enum
        list of enum to generate dict from.
    Returns
    -------
    enum_dict: dict
        Dict containing {enum.name: enum} pairs.
    """
    enum_dict = {}
    for item in enum_list:
        enum_dict[item.name] = item
    return enum_dict


def nav(root, items):
    """Access a nested object in root by item sequence."""
    for k in items:
        root = root[k]
    return root


def p_host_identifier_option_decls(p):
    """ host_identifier_option_decls : HOST_IDENTIFIER option_decl
                                     | HOST_IDENTIFIER option_decl host_identifier_option_decls
    """
    p[0] = {p[1]: p[2]}
    if len(p) > 3:
        p[0][p[1]].update(p[3][p[1]])


def phdiff2fmap(in_file, delta_te, newpath=None):
    """
    Converts the input phase-difference map into a fieldmap in Hz,
    using the eq. (1) of [Hutton2002]_:

    .. math::

        \\Delta B_0 (\\text{T}^{-1}) = \\frac{\\Delta \\Theta}{2\\pi\\gamma \\Delta\\text{TE}}

    In this case, we do not take into account the gyromagnetic ratio of the
    proton (:math:`\\gamma`), since it will be applied inside TOPUP:

    .. math::

        \\Delta B_0 (\\text{Hz}) = \\frac{\\Delta \\Theta}{2\\pi \\Delta\\text{TE}}

    """
    import math
    import numpy as np
    import nibabel as nb
    from nipype.utils.filemanip import fname_presuffix
    out_file = fname_presuffix(in_file, suffix='_fmap', newpath=newpath)
    image = nb.load(in_file)
    data = image.get_data().astype(np.float32) / (2.0 * math.pi * delta_te)
    nii = nb.Nifti1Image(data, image.affine, image.header)
    nii.set_data_dtype(np.float32)
    nii.to_filename(out_file)
    return out_file


def add_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    from django.apps import apps
    Setting = apps.get_model('settings', 'Setting')
    FileField = apps.get_model('filefields', 'FileField')
    key = ''
    for key_file_type, value_file_type in FileField.FILE_TYPE:
        try:
            value = ''
            if key_file_type == 'P':
                value = 'https://cdn.aparnik.com/static/img/icon_pdf.png'
            elif key_file_type == 'M':
                value = 'https://cdn.aparnik.com/static/img/icon_movie.png'
            elif key_file_type == 'V':
                value = 'https://cdn.aparnik.com/static/img/icon_voice.png'
            elif key_file_type == 'I':
                value = 'https://cdn.aparnik.com/static/img/icon_image.png'
            elif key_file_type == 'L':
                value = 'https://cdn.aparnik.com/static/img/icon_image.png'
            else:
                continue
            key = 'FILE_TYPE_%s_ICON' % key_file_type
            Setting.objects.get(key=key)
        except Exception:
            Setting.objects.create(title='آیکن مربوط به فایل تایپ %s' %
                value_file_type, key=key, value=value, value_type='s',
                is_show=False, is_variable_in_home=False)


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

        :param SharedFolderUnmountDetails val:
        :rtype: EventDetails
        """
    return cls('shared_folder_unmount_details', val)


def p_definition_list(t):
    """definition_list : definition definition_list
                       | empty"""


def extract_rows(data, *rows):
    """Extract rows specified in the argument list.

>>> chart_data.extract_rows([[10,20], [30,40], [50,60]], 1, 2)
[[30,40],[50,60]]
"""
    try:
        out = []
        for r in rows:
            out.append(data[r])
        return out
    except IndexError:
        raise IndexError('data=%s rows=%s' % (data, rows))
    return out


def getControllerTranslations():
    """ Returns a list of dicts, each containing the 'id' and 'msg' for a
            slideshow controller button.
        """


def group_remove():
    """Remove the active bone group

    """
    pass


def strip_byte_order_mark(text):
    """Return text with byte order mark (BOM) removed."""
    try:
        return text.encode('utf-8').decode('utf-8-sig')
    except UnicodeError:
        return text


@classmethod
def list(cls, options=None):
    """List PaaS instances."""
    return cls.call('paas.list', options)


def quantity_to_tuple(quantity, unit_str):
    """
    Splits a quantity into a tuple of (value,unit) where unit is FITS complient.

    Useful to write FITS header keywords with units in a comment.

    Parameters
    ----------
    quantity : astropy quantity
        The Astropy quantity to split.
    unit_str: str
        Unit string representation readable by astropy.units (e.g. 'm', 'TeV', ...)

    Returns
    -------
    tuple
        A tuple containing the value and the quantity.
    """
    return quantity.to(unit_str).value, quantity.to(unit_str).unit.to_string(
        format='FITS')


def tileset_info(filename):
    """

    Return the bounds of this tileset. The bounds should encompass the entire
    width of this dataset.

    So how do we know what those are if we don't know chromsizes? We can assume
    that the file is enormous (e.g. has a width of 4 trillion) and rely on the
    browser to pass in a set of chromsizes
    """
    pass


@classmethod
def fetch(cls, channel, start, end, host=None, port=None, verbose=False,
    connection=None, verify=False, pad=None, allow_tape=None, scaled=None,
    type=None, dtype=None):
    """Fetch data from NDS

        Parameters
        ----------
        channel : `str`, `~gwpy.detector.Channel`
            the data channel for which to query

        start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
            GPS start time of required data,
            any input parseable by `~gwpy.time.to_gps` is fine

        end : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
            GPS end time of required data,
            any input parseable by `~gwpy.time.to_gps` is fine

        host : `str`, optional
            URL of NDS server to use, if blank will try any server
            (in a relatively sensible order) to get the data

        port : `int`, optional
            port number for NDS server query, must be given with `host`

        verify : `bool`, optional, default: `False`
            check channels exist in database before asking for data

        scaled : `bool`, optional
            apply slope and bias calibration to ADC data, for non-ADC data
            this option has no effect

        connection : `nds2.connection`, optional
            open NDS connection to use

        verbose : `bool`, optional
            print verbose output about NDS progress, useful for debugging;
            if ``verbose`` is specified as a string, this defines the
            prefix for the progress meter

        type : `int`, optional
            NDS2 channel type integer

        dtype : `type`, `numpy.dtype`, `str`, optional
            identifier for desired output data type
        """
    return cls.DictClass.fetch([channel], start, end, host=host, port=port,
        verbose=verbose, connection=connection, verify=verify, pad=pad,
        scaled=scaled, allow_tape=allow_tape, type=type, dtype=dtype)[str(
        channel)]


def display_bloch_sphere_qutrit(**kwargs):
    """
    Prints an error message.
    """
    print('display_bloch_sphere_qutrit not available on this version.')


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

        :param SignInAsSessionStartType val:
        :rtype: EventType
        """
    return cls('sign_in_as_session_start', val)


def get_str_value_from_property_value(property_value, separator):
    """ Evaluate string value of property """
    if isinstance(property_value, list):
        return separator.join(property_value)
    raise str('property value must be a list')


def forwards(apps, schema_editor):
    """
    Change all Movie objects into Work objects, and their associated
    data into WorkRole and WorkSelection models, then delete the Movie.
    """
    Movie = apps.get_model('spectator_events', 'Movie')
    Work = apps.get_model('spectator_events', 'Work')
    WorkRole = apps.get_model('spectator_events', 'WorkRole')
    WorkSelection = apps.get_model('spectator_events', 'WorkSelection')
    for m in Movie.objects.all():
        work = Work.objects.create(kind='movie', title=m.title, title_sort=
            m.title_sort, year=m.year, imdb_id=m.imdb_id)
        for role in m.roles.all():
            WorkRole.objects.create(creator=role.creator, work=work,
                role_name=role.role_name, role_order=role.role_order)
        for selection in m.events.all():
            WorkSelection.objects.create(event=selection.event, work=work,
                order=selection.order)
        m.delete()


@classmethod
def unregister_global_type(cls, type_: type) ->None:
    """
        Removes a previously registered encoder for the given type.
        """
    del cls._global_types[type_]


def p_variable_name(p):
    """variable_name : STRING
                     | LBRACE expr RBRACE"""
    if len(p) == 2:
        p[0] = p[1]
    else:
        p[0] = p[2]


def flow(args):
    """Start a Flow from a YAML file"""
    from ..flow import Flow
    if args.yaml_path:
        from threading import Event
        f = Flow.load_config(args.yaml_path)
        f._update_args(args)
        with f:
            try:
                Event().wait()
            except KeyboardInterrupt:
                pass
    else:
        from jina.logging import default_logger
        default_logger.critical(
            'start a flow from CLI requires a valid "--yaml-path"')


def p_break_stmt(p):
    """break_stmt : BREAK"""
    p[0] = ['BREAK']


def indx_where_ngram_ends(st_indx, ngram_toks, sent_toks):
    """

        Case 1: where sent_toks contains stopwords making it hard to match ngram that already has stopwords removed:
            Given st_index = 2 (sent_toks index where ngram_toks starts)
            Given ngram_toks: ['orange', 'new', 'black']
            Given sent_toks: ['best', 'is', 'orange', 'is', 'the', 'new', 'black']

            The goal of this function is return 5: length of substring (['orange', 'is', 'the', 'new', 'black']) with stopwords that encompass ngram_toks

        Negative Case 1:
            Given st_index = 5 (sent_toks index where ngram_toks starts)
            Given ngram_toks: ['convention', 'center']
            Given sent_toks: ['it', 'is', 'the', 'brown', 'r.', 'convention', 'center']

            The goal of this function is return 2: length of substring ([convention', 'center']) without stopwords that encompass ngram_toks
    """
    j = st_indx
    length = 0
    start = -1
    match_count = 0
    for i in range(len(ngram_toks)):
        while j < len(sent_toks):
            length += 1
            ngram_tok = ngram_toks[i].strip().lower()
            sent_tok = sent_toks[j].strip().lower()
            if sent_tok.find(ngram_tok) != -1:
                if start == -1:
                    start = j
                j += 1
                match_count += 1
                break
            j += 1
    if match_count == len(ngram_toks):
        return start, length
    else:
        return start, -1


def __call__(hashed_value, password):
    """
        Return True if password matches hashed_value
        """


def lprint(input_x, output, name=None):
    """Print option interface.

    This function is to stdout the shape of input layer & output layer
    in Deep Learning architecture.

    Parameters
    ----------
    input_x: numpy.ndarray
      A ``numpy.ndarray`` object of input source.

    output: numpy.ndarray
      A ``numpy.ndarray`` object of output target.

    name: str (default: None)
      An optional name you want to print out.

    """
    print(f'{str(name)}:\t{input_x.shape} -> {output.shape}')


def select_word():
    """Select word under cursor

    """
    pass


def duration(config_duration: str) ->int:
    """
    Convert the config duration to an integer.

    :param config_duration: The duration as a string
    :return: The duration as an integer
    """
    my_duration = int(config_duration)
    if my_duration < 1:
        raise ValueError('A slot must be at least 1 second long')
    return my_duration