def _parseUNIX(factory, address, mode='666', backlog=50, lockfile=True):
    """
    Internal parser function for L{_parseServer} to convert the string
    arguments for a UNIX (AF_UNIX/SOCK_STREAM) stream endpoint into the
    structured arguments.

    @param factory: the protocol factory being parsed, or L{None}.  (This was a
        leftover argument from when this code was in C{strports}, and is now
        mostly None and unused.)

    @type factory: L{IProtocolFactory} or L{None}

    @param address: the pathname of the unix socket
    @type address: C{str}

    @param backlog: the length of the listen queue
    @type backlog: C{str}

    @param lockfile: A string '0' or '1', mapping to True and False
        respectively.  See the C{wantPID} argument to C{listenUNIX}

    @return: a 2-tuple of (args, kwargs), describing  the parameters to
        L{twisted.internet.interfaces.IReactorUNIX.listenUNIX} (or,
        modulo argument 2, the factory, arguments to L{UNIXServerEndpoint}.
    """
    return (address, factory), {'mode': int(mode, 8), 'backlog': int(
        backlog), 'wantPID': bool(int(lockfile))}


def leave(roomJID):
    """
        Leave a MUC room.

        See: http://xmpp.org/extensions/xep-0045.html#exit

        @param roomJID: The Room JID of the room to leave.
        @type roomJID: L{JID<twisted.words.protocols.jabber.jid.JID>}
        """


@staticmethod
def _raise_missing_attribute(cls, query_key, missing_attribute, amend_msg=''):
    """Raises error for missing attribute in a message suitable for the REST user"""
    raise AttributeError(
        f'To query {cls._class_name} for {query_key} you must provide {missing_attribute}.'
        )


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 _latex_writeto(filename, tab, comments='%'):
    """ Write the data into a latex table format

    Parameters
    ----------
    filename: str
        file or unit to write into

    tab: SimpleTable instance
        table

    comments: str
        string to prepend header lines

    delimiter: str, optional
        The string used to separate values.  By default, this is any
        whitespace.

    commentedHeader: bool, optional
        if set, the last line of the header is expected to be the column titles
    """
    txt = '\\begin{table}\n\\begin{center}\n'
    tabname = tab.header.get('NAME', None)
    if tabname not in ['', None, 'None']:
        txt += '\\caption{{{0:s}}}\n'.format(tabname)
    txt += '\\begin{{tabular}}{{{0:s}}}\n'.format('c' * tab.ncols)
    txt += tab.pprint(delim=' & ', fields='MAG*', headerChar='', endline=
        '\\\\\n', all=True, ret=True)
    txt += '\\end{tabular}\n'
    txt += '\\end{center}\n'
    if len(tab._desc) > 0:
        txt += '\\% notes \n\\begin{scriptsize}\n'
        for e, (k, v) in enumerate(tab._desc.items()):
            if v not in (None, 'None', 'none', ''):
                txt += '{0:d} {1:s}: {2:s} \\\\\n'.format(e, k, v)
        txt += '\\end{scriptsize}\n'
    txt += '\\end{table}\n'
    if hasattr(filename, 'write'):
        filename.write(txt)
    else:
        with open(filename, 'w') as unit:
            unit.write(txt)


def list_del_indices(mylist, indices):
    """
    iteratively remove elements of a list by indices
    Parameters
    ----------
    mylist : list
        the list of elements of interest

    indices : list
        the list of indices of elements that should be removed

    Returns
    -------
    list
        the reduced mylist entry

    """
    for index in sorted(indices, reverse=True):
        del mylist[index]
    return mylist


@classmethod
def GET(cls, *n, **kw):
    """Perform a GET request using :meth:`RESTClient.request()`."""
    return cls.IMPL.GET(*n, **kw)


@classmethod
def get(cls, project_id, model_id):
    """
        Retrieve a specific frozen model.

        Parameters
        ----------
        project_id : str
            The project's id.
        model_id : str
            The ``model_id`` of the leaderboard item to retrieve.

        Returns
        -------
        model : FrozenModel
            The queried instance.
        """
    url = cls._frozen_path_template.format(project_id) + model_id + '/'
    return cls.from_location(url)


@classmethod
def serialize_item(cls, item, args=None):
    """
        Serialize a query that stored in ``item`` tuple like: (key, value)
        """
    fields = getattr(cls, 'fields', None)
    if fields and isinstance(fields, dict):
        if item[0] in fields:
            return fields[item(0)].serialize(item[1], params=args)
    return {item[0]: item[1]}


def _fpop():
    """ Returns the pop sequence of a float
    """
    output = []
    output.append('pop af')
    output.append('pop de')
    output.append('pop bc')
    return output


def integer_bit_size(n):
    """Returns the number of bits necessary to store the integer n."""
    if n == 0:
        return 1
    s = 0
    while n:
        s += 1
        n >>= 1
    return s


def get_valid_place(place):
    """ Return valid place.

    Strip spaces and check for empty value."""
    place = place.strip()
    if not place:
        raise ValueError('empty string')
    return place


def _count_of_prev(rule):
    """Count previous tokens to be present before a match in a rule."""
    return len(rule.prev_classes or []) + len(rule.prev_tokens or [])


def get_official_service_name(service_model):
    """Generate the official name of an AWS Service

    :param service_model: The service model representing the service
    """
    official_name = service_model.metadata.get('serviceFullName')
    short_name = service_model.metadata.get('serviceAbbreviation', '')
    if short_name.startswith('Amazon'):
        short_name = short_name[7:]
    if short_name.startswith('AWS'):
        short_name = short_name[4:]
    if short_name and short_name.lower() not in official_name.lower():
        official_name += ' ({0})'.format(short_name)
    return official_name


def is_subpolynomial(f, a):
    """Test if `a' is a sum of terms of the polynomial `f'.
    """
    a = f.parent()(a)
    return len(f.monomials()) == len((f - a).monomials()) + len(a.monomials())


def check_if_better(rank_one, rank_two, critical_dist):
    """Checks whether rank1 is greater than rank2 by at least critical dist"""
    is_better = rank_one - rank_two >= critical_dist
    return is_better


def __init__(context, request):
    """Adapts context and request.
        """


@classmethod
def _order(cls, x):
    """Return an integer value for character x"""
    if x == '~':
        return -1
    if cls.re_digit.match(x):
        return int(x) + 1
    if cls.re_alpha.match(x):
        return ord(x)
    return ord(x) + 256


def _process_sort_string(sort_string):
    """Returns a list of tuples: (sort condition, reverse sort)"""
    cmp = []
    for attrname in sort_string.split(','):
        attrname = attrname.strip()
        rev = False
        if attrname.endswith('+'):
            attrname = attrname[:-1]
        elif attrname.endswith('-'):
            attrname = attrname[:-1]
            rev = True
        cmp.append((attrname, rev))
    return cmp


def _tal_replaced_content(tag, attrs):
    """Will the data get replaced by tal?

    So: is there a tal:content or tal:replace?  Or is it '<tal:block
    content=.".."'?  Problem with that last one is that the lxml html
    parser strips off the 'tal:' namespace, unlike the standard lxml
    parser that is tried first.
    """
    if 'tal:content' in attrs or 'content' in attrs:
        return True
    if 'tal:replace' in attrs or 'replace' in attrs:
        return True
    return False


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


def factorial_get_prime_pow(n, p):
    """
    Return power of prime @p in @n!
    """
    count = 0
    ppow = p
    while ppow <= n:
        count += n // ppow
        ppow *= p
    return count


@staticmethod
def get_diff_number_from_list(list):
    """ 获得密度化文本中不同的行数统计号
        Input：密度化文本                     -- list类型
        Outpt:降序排列的行数统计号序列           -- list类型
        """
    number_list = []
    for i in list:
        if type(i) == int and i not in number_list:
            number_list.append(i)
    return sorted(number_list, reverse=True)


@staticmethod
def area_size(area):
    """
        Returns the size of the area, by multiplying width and height.

        CHANGELOG

        Added 05.12.2018

        :param Tuple(Tuple(int,int)) area:  THe tuple describing the two dimensional are in a x y plane
        :return:  int
        """
    width = area[0][1] - area[0][0]
    height = area[1][1] - area[1][0]
    return width * height


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 readfast(shallow=False):
    """Calls either ``read()`` or ``readdelta()``.

        The faster of the two options is called.
        """


def _tx_resource_for_name(name):
    """ Return the Transifex resource name """
    if name == 'core':
        return 'django-core.core'
    else:
        return 'django-core.contrib-%s' % 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 pad(x, l, pad_char='-'):
    """Pad x with pad_char characters until it has length l"""
    return x + pad_char * (l - len(x))


@staticmethod
def merge_entities(name, ent1, ent2):
    """
        Merge two entities making sure they do not conflict.

        Parameters
        ----------
        name : hashable

        ent1 : Entity
            First entity to have elements and properties added to new
            entity

        ent2 : Entity
            elements of ent2 will be checked against ent1.complete_registry()
            and only nonexisting elements will be added using add() method.
            Properties of ent2 will update properties of ent1 in new entity.

        Returns
        -------
        a new entity : Entity

        """
    newent = ent1.clone(name)
    newent.add_elements_from(ent2.elements.values())
    for k, v in ent2.properties.items():
        newent.__setattr__(k, v)
    return newent


def _quads_to_triangles(quads):
    """Convert a list of quads to a list of triangles.

    :param quads: The list of quads.
    :type quads: list of 4-tuples
    :returns: List of triangles.
    :rtype: list of 3-tuples

    """
    triangles = []
    for quad in quads:
        triangles.append((quad[0], quad[1], quad[2]))
        triangles.append((quad[0], quad[2], quad[3]))
    return triangles


@classmethod
def load_image(cls, filename, height=1, array=False, bounds=None, bare=
    False, **kwargs):
    """
        Returns an raster element or raw numpy array from a PNG image
        file, using matplotlib.

        The specified height determines the bounds of the raster
        object in sheet coordinates: by default the height is 1 unit
        with the width scaled appropriately by the image aspect ratio.

        Note that as PNG images are encoded as RGBA, the red component
        maps to the first channel, the green component maps to the
        second component etc. For RGB elements, this mapping is
        trivial but may be important for subclasses e.g. for HSV
        elements.

        Setting bare=True will apply options disabling axis labels
        displaying just the bare image. Any additional keyword
        arguments will be passed to the Image object.
        """
    try:
        from matplotlib import pyplot as plt
    except:
        raise ImportError('RGB.load_image requires matplotlib.')
    data = plt.imread(filename)
    if array:
        return data
    h, w, _ = data.shape
    if bounds is None:
        f = float(height) / h
        xoffset, yoffset = w * f / 2, h * f / 2
        bounds = -xoffset, -yoffset, xoffset, yoffset
    rgb = cls(data, bounds=bounds, **kwargs)
    if bare:
        rgb = rgb(plot=dict(xaxis=None, yaxis=None))
    return rgb


@classmethod
def from_image(klass, img):
    """ Class method to create new instance of own class from `img`

        Parameters
        ----------
        img : instance
            In fact, an object with the API of :class:`DataobjImage`.

        Returns
        -------
        cimg : instance
            Image, of our own class
        """
    if isinstance(img, klass):
        return img
    raise NotImplementedError


def CRRAutilityPPP(c, gam):
    """
    Evaluates constant relative risk aversion (CRRA) marginal marginal marginal
    utility of consumption c given risk aversion parameter gam.

    Parameters
    ----------
    c : float
        Consumption value
    gam : float
        Risk aversion

    Returns
    -------
    (unnamed) : float
        Marginal marginal marginal utility
    """
    return (gam + 1.0) * gam * c ** (-gam - 2.0)


def calculate_fuel_consumptions(co2_emissions, fuel_carbon_content):
    """
    Calculates the instantaneous fuel consumption vector [g/s].

    :param co2_emissions:
        CO2 instantaneous emissions vector [CO2g/s].
    :type co2_emissions: numpy.array

    :param fuel_carbon_content:
        Fuel carbon content [CO2g/g].
    :type fuel_carbon_content: float

    :return:
        The instantaneous fuel consumption vector [g/s].
    :rtype: numpy.array
    """
    return co2_emissions / fuel_carbon_content


def get_domain(request):
    """
    Get the domain name parsed from a hostname:port string

    >>> class FakeRequest(object):
    ...     def __init__(self, url):
    ...         self.url = url
    ...     def get_host(self):
    ...         return self.url
    >>> req = FakeRequest("example.com:5984")
    >>> get_domain(req)
    'example.com'
    """
    return request.get_host().split(':')[0]


def duplicate_move(GPENCIL_OT_duplicate=None, TRANSFORM_OT_translate=None):
    """Make copies of the selected Grease Pencil strokes and move them

    :param GPENCIL_OT_duplicate: Duplicate Strokes, Duplicate the selected Grease Pencil strokes
    :param TRANSFORM_OT_translate: Move, Move selected items
    """
    pass


def setbox(x, y, mbox, xmax, ymax):
    """
    Create a box of length mbox around a position x,y. If the box will
    be out of [0,len] then reset the edges of the box to be within the
    boundaries.

    Parameters
    ----------
    x : int
        Central x-position of box.

    y : int
        Central y-position of box.

    mbox : int
        Width of box.

    xmax : int
        Maximum x value.

    ymax : int
        Maximum y value.

    Returns
    -------
    x1 : int
        Lower x corner of box.

    x2 : int
        Upper x corner of box.

    y1 : int
        Lower y corner of box.

    y2 : int
        Upper y corner of box.
    """
    mbox = max(int(0.5 * mbox), 1)
    y1 = max(0, y - mbox)
    y2 = min(y + mbox + 1, ymax - 1)
    x1 = max(0, x - mbox)
    x2 = min(x + mbox + 1, xmax - 1)
    return x1, x2, y1, y2


def list_placeholder(length, is_pg=False):
    """Returns a (?,?,?,?...) string of the desired length"""
    return '(' + '?,' * (length - 1) + '?)'


def get_line_by_content(text, key):
    """Get line of `text` containing `key`."""
    for line in text.split('\n'):
        if key in line:
            return line
    return


def get_pixel(pic, x, y):
    """Return the Pixel object at the coordinates (x, y) in Picture pic."""
    return pic.get_pixel(x, y)


def _read_string_array(data):
    """
    Helper function taking a string data set and preparing it so it can be
    read to a BytesIO object.
    """
    return data[()].tostring().strip(b'\x00 ').strip()


def midi_to_frequency(midi_note):
    """ Converts a midi note to a frequency.

    ::Examples::

    >>> midi_to_frequency(21)
    27.5
    >>> midi_to_frequency(26)
    36.7
    >>> midi_to_frequency(108)
    4186.0
    """
    return round(440.0 * 2 ** ((midi_note - 69) * (1.0 / 12.0)), 1)


@classmethod
def reset(cls):
    """
        Reset the dispatcher so the queue is cleared, and it is reset into
        queueing mode.
        """
    cls._queue_initial_tasks = True
    cls._preinit_task_queue = []
    cls._overflow_count = 0


def create_icosphere(bm: 'bmesh.types.BMesh', subdivisions: int, diameter:
    float, matrix: 'mathutils.Matrix', calc_uvs: bool) ->dict:
    """Creates a grid with a variable number of subdivisions

    :param bm: The bmesh to operate on.
    :type bm: 'bmesh.types.BMesh'
    :param subdivisions: how many times to recursively subdivide the sphere
    :type subdivisions: int
    :param diameter: diameter
    :type diameter: float
    :param matrix: matrix to multiply the new geometry with
    :type matrix: 'mathutils.Matrix'
    :param calc_uvs: calculate default UVs
    :type calc_uvs: bool
    :return:  verts: output vertstype list of (bmesh.types.BMVert)
    """
    pass


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

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


def apply_data(context, form_fields, data, adapters=None, update=False):
    """Save form data (``data`` dict) on a ``context`` object.

    This is a beefed up version of zope.formlib.form.applyChanges().
    It allows you to specify whether values should be compared with
    the attributes on already existing objects or not, using the
    ``update`` parameter.

    Unlike zope.formlib.form.applyChanges(), it will return a
    dictionary of interfaces and their fields that were changed.  This
    is necessary to appropriately send IObjectModifiedEvents.
    """
    if adapters is None:
        adapters = {}
    changes = {}
    for form_field in form_fields:
        field = form_field.field
        interface = form_field.interface
        adapter = adapters.get(interface)
        if adapter is None:
            if interface is None:
                adapter = context
            else:
                adapter = interface(context)
            adapters[interface] = adapter
        name = form_field.__name__
        newvalue = data.get(name, form_field)
        if update:
            if newvalue is not form_field and field.get(adapter) != newvalue:
                field.set(adapter, newvalue)
                changes.setdefault(interface, []).append(name)
        elif newvalue is not form_field:
            field.set(adapter, newvalue)
            changes.setdefault(interface, []).append(name)
    return changes


def process_choice_data(dict_, data):
    """This functions processes the inputs for the
    decision equation"""
    indicator = dict_['ESTIMATION']['indicator']
    D = data[indicator].values
    Z = data[dict_['CHOICE']['order']]
    return indicator, D, Z


def add_all(array, other):
    """
    Append all items of the second array into the first one.

    :param array:
    :param other:
    :return:
    """
    for item in other:
        array.append(item)
    return array


def restrict_datafunc(n):
    """Use the function in the Data class."""
    return n._data_class(coords=n.coords)


def setQualifiedContributors(qualified_contributors):
    """Set the qualified Contributors elements.

        The argument must be a sequence of Contributor `IDublinCoreElementItem`.
        """


def parse_cachecontrol(header):
    """Parse Cache-Control header

    http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9

    >>> parse_cachecontrol(b'public, max-age=3600') == {b'public': None,
    ...                                                 b'max-age': b'3600'}
    True
    >>> parse_cachecontrol(b'') == {}
    True

    """
    directives = {}
    for directive in header.split(b','):
        key, sep, val = directive.strip().partition(b'=')
        if key:
            directives[key.lower()] = val if sep else None
    return directives


def clamp(value, min_value, max_value):
    """
    Return *value* clipped to the range *min_value* to *max_value* inclusive.
    """
    return min(max_value, max(min_value, value))


def read_encrypted(length, hash_only):
    """This behaves just like IUploadable.read(), but returns crypttext
        instead of plaintext. If hash_only is True, then this discards the
        data (and returns an empty list); this improves efficiency when
        resuming an interrupted upload (where we need to compute the
        plaintext hashes, but don't need the redundant encrypted data)."""


def annuity(capex, n, wacc, u=None, cost_decrease=0):
    """Calculates the annuity of an initial investment 'capex', considering
    the cost of capital 'wacc' during a project horizon 'n'

    In case of a single initial investment, the employed formula reads:

    .. math::
        \\text{annuity} = \\text{capex} \\cdot
            \\frac{(\\text{wacc} \\cdot (1+\\text{wacc})^n)}
            {((1 + \\text{wacc})^n - 1)}

    In case of repeated investments (due to replacements) at fixed intervals
    'u', the formula yields:

    .. math::
        \\text{annuity} = \\text{capex} \\cdot
                  \\frac{(\\text{wacc} \\cdot (1+\\text{wacc})^n)}
                  {((1 + \\text{wacc})^n - 1)} \\cdot \\left(
                  \\frac{1 - \\left( \\frac{(1-\\text{cost\\_decrease})}
                  {(1+\\text{wacc})} \\right)^n}
                  {1 - \\left(\\frac{(1-\\text{cost\\_decrease})}{(1+\\text{wacc})}
                  \\right)^u} \\right)

    Parameters
    ----------
    capex : float
        Capital expenditure for first investment. Net Present Value (NPV) or
        Net Present Cost (NPC) of investment
    n : int
        Horizon of the analysis, or number of years the annuity wants to be
        obtained for (n>=1)
    wacc : float
        Weighted average cost of capital (0<wacc<1)
    u : int
        Lifetime of the investigated investment. Might be smaller than the
        analysis horizon, 'n', meaning it will have to be replaced.
        Takes value 'n' if not specified otherwise (u>=1)
    cost_decrease : float
        Annual rate of cost decrease (due to, e.g., price experience curve).
        This only influences the result for investments corresponding to
        replacements, whenever u<n.
        Takes value 0, if not specified otherwise (0<cost_decrease<1)
    Returns
    -------
    float
        annuity
    """
    if u is None:
        u = n
    if n < 1 or (wacc < 0 or wacc > 1) or u < 1 or (cost_decrease < 0 or
        cost_decrease > 1):
        raise ValueError("Input arguments for 'annuity' out of bounds!")
    return capex * (wacc * (1 + wacc) ** n) / ((1 + wacc) ** n - 1) * ((1 -
        ((1 - cost_decrease) / (1 + wacc)) ** n) / (1 - ((1 - cost_decrease
        ) / (1 + wacc)) ** u))


def view_all():
    """Show the entire playable frame range

    """
    pass


def prefer_first(*vals):
    """
  This idiom is used so often...
  Pick fist value unles it's None.

  Usage::

      >>> prefer_first( True, 42 )
      True
      >>> prefer_first( None, 42 )
      42

      ## Still pick 1st one if it's not None
      >>> prefer_first( False, 42 )
      False

      >>> prefer_first( 1, 2, 3 )
      1
      >>> prefer_first( None, 2, 3 )
      2
      >>> prefer_first( None, None, 3 )
      3
      >>> prefer_first( None, None, None ) is None
      True

  """
    for val in vals:
        if val is not None:
            return val
    return val


def set_default_to_meta(meta, key, default_value):
    """
    Set default value to dict of meta
    """
    if callable(default_value):
        default_value = default_value()
    meta.setdefault(key, default_value)


def addBuildDirOptions(parser):
    """
    Add build directory specific options to the parser.
    """
    from optparse import OptionGroup
    group = OptionGroup(parser, 'Build Dir Options')
    group.add_option('--clean', action='store_true', help=
        'purge the build directory before building')
    group.add_option('--no-clean', action='store_false', dest='clean', help
        ='do not purge the build directory before building')
    group.add_option('--no-unpack', action='store_true', help=
        'assume that the sources are already present')
    parser.add_option_group(group)
    parser.set_defaults(clean=False, no_unpack=False)
    return parser


def formula_2016_01_01(foyer_fiscal, period, parameters):
    """
        Investissements OUTRE-MER dans le secteur du logement et autres secteurs d’activité
        2016
        """
    fhod = foyer_fiscal('fhod', period)
    fhoe = foyer_fiscal('fhoe', period)
    fhof = foyer_fiscal('fhof', period)
    fhog = foyer_fiscal('fhog', period)
    fhox = foyer_fiscal('fhox', period)
    fhoy = foyer_fiscal('fhoy', period)
    fhoz = foyer_fiscal('fhoz', period)
    fhqb = foyer_fiscal('fhqb', period)
    fhqc = foyer_fiscal('fhqc', period)
    fhqd = foyer_fiscal('fhqd', period)
    fhql = foyer_fiscal('fhql', period)
    fhqm = foyer_fiscal('fhqm', period)
    fhqt = foyer_fiscal('fhqt', period)
    fhoa = foyer_fiscal('fhoa', period)
    fhob = foyer_fiscal('fhob', period)
    fhoc = foyer_fiscal('fhoc', period)
    fhoh = foyer_fiscal('fhoh', period)
    fhoi = foyer_fiscal('fhoi', period)
    fhoj = foyer_fiscal('fhoj', period)
    fhok = foyer_fiscal('fhok', period)
    fhol = foyer_fiscal('fhol', period)
    fhom = foyer_fiscal('fhom', period)
    fhon = foyer_fiscal('fhon', period)
    fhoo = foyer_fiscal('fhoo', period)
    fhop = foyer_fiscal('fhop', period)
    fhoq = foyer_fiscal('fhoq', period)
    fhor = foyer_fiscal('fhor', period)
    fhos = foyer_fiscal('fhos', period)
    fhot = foyer_fiscal('fhot', period)
    fhou = foyer_fiscal('fhou', period)
    fhov = foyer_fiscal('fhov', period)
    fhow = foyer_fiscal('fhow', period)
    fhua = foyer_fiscal('fhua', period)
    fhub = foyer_fiscal('fhub', period)
    fhuc = foyer_fiscal('fhuc', period)
    fhud = foyer_fiscal('fhud', period)
    fhue = foyer_fiscal('fhue', period)
    fhuf = foyer_fiscal('fhuf', period)
    fhug = foyer_fiscal('fhug', period)
    fhuh = foyer_fiscal('fhuh', period)
    fhui = foyer_fiscal('fhui', period)
    fhuj = foyer_fiscal('fhuj', period)
    fhuk = foyer_fiscal('fhuk', period)
    fhul = foyer_fiscal('fhul', period)
    fhum = foyer_fiscal('fhum', period)
    fhun = foyer_fiscal('fhun', period)
    fhuo = foyer_fiscal('fhuo', period)
    fhup = foyer_fiscal('fhup', period)
    fhuq = foyer_fiscal('fhuq', period)
    fhur = foyer_fiscal('fhur', period)
    fhus = foyer_fiscal('fhus', period)
    fhut = foyer_fiscal('fhut', period)
    fhuu = foyer_fiscal('fhuu', period)
    return (fhqb + fhqc + fhqd + fhql + fhqm + fhqt + fhoa + fhob + fhoc +
        fhoh + fhoi + fhoj + fhok + fhol + fhom + fhon + fhoo + fhop + fhoq +
        fhor + fhos + fhot + fhou + fhov + fhow + fhod + fhoe + fhof + fhog +
        fhox + fhoy + fhoz + fhua + fhub + fhuc + fhud + fhue + fhuf + fhug +
        fhuh + fhui + fhuj + fhuk + fhul + fhum + fhun + fhuo + fhup + fhuq +
        fhur + fhus + fhut + fhuu)


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

    """
    pass


def convertValueOrNone(value, convert=int):
    """Convert a value to a type unless NoneType.

    Parameters
    ----------
    value : anything
        The value to possibly convert.
    convert : TYPE, optional
        The type for conversion.

    Returns
    -------
    convert type
        The converted value.
    """
    return value if value is None else convert(value)


def dimshuffle(x, pattern):
    """
    Reorders the dimensions of this variable, optionally inserting broadcasted dimensions.
    Inspired by `Theano's dimshuffle`_.

    .. _Theano's dimshuffle:
        https://github.com/Theano/Theano/blob/d395439aec5a6ddde8ef5c266fd976412a5c5695/theano/tensor/var.py#L323-L356

    :param x:
        Input tensor.
    :param pattern:
        List/tuple of int mixed with 'x' for broadcastable dimensions.
    :return:
        a tensor whose shape matches `pattern`.

    Examples
    --------
    To create a 3D view of a [2D] matrix, call ``dimshuffle(x, [0,'x',1])``.
    This will create a 3D view such that the
    middle dimension is an implicit broadcasted dimension.  To do the same
    thing on the transpose of that matrix, call ``dimshuffle(x, [1, 'x', 0])``.

    See Also
    --------
    :func:`~neuralnet_pytorch.utils.shape_padleft`
    :func:`~neuralnet_pytorch.utils.shape_padright`
    """
    assert isinstance(pattern, (list, tuple)), 'pattern must be a list/tuple'
    no_expand_pattern = [x for x in pattern if x != 'x']
    y = x.permute(*no_expand_pattern)
    shape = list(y.shape)
    for idx, e in enumerate(pattern):
        if e == 'x':
            shape.insert(idx, 1)
    return y.view(*shape)


@staticmethod
def _record_size(name, dimensions):
    """Calculate size of array record in bytes."""
    return 1 + max(3, len(name)) + 3 + 2 * len(dimensions)


def calculate_radial_reduction(dmu_code, category, data, efficiency_score,
    orientation):
    """ Calculates radial reduction for a given DMU and category.

        Args:
            dmu_code (str): DMU code.
            category (str): category name.
            data (InputData): object that stores input data.
            efficiency_score (double): efficiency spyDEA.core.
            orientation (str): problem orientation, can take values
                input or output.

        Returns:
            double: radial reduction value.
    """
    if orientation == 'input':
        if category in data.output_categories:
            return 0
        objective_value = efficiency_score
    elif orientation == 'output':
        if category in data.input_categories:
            return 0
        objective_value = 1 / efficiency_score
    return (objective_value - 1) * data.coefficients[dmu_code, category]


@staticmethod
def quantity_to_string(quantity):
    """
        Helper function to convert a quantity identifier from the schema to a consistent
        string for in RST documentation

        :param quantity: Quantity string used in the format specification
        :return: String describing the quantity
        """
    qdict = {'*': '0 or more', 'zero_or_more': '0 or more', '+':
        '1 or more', 'one_or_more': '1 or more', '?': '0 or 1',
        'zero_or_one': '0 or 1'}
    if isinstance(quantity, int):
        return str(quantity)
    else:
        return qdict[quantity]


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


@classmethod
def fromdata(cls, data, header=None, bps=2):
    """Encode data as a payload.

        Parameters
        ----------
        data : `~numpy.ndarray`
            Data to be encoded. The last dimension is taken as the number of
            channels.
        header : header instance, optional
            If given, used to infer the bps.
        bps : int, optional
            Bits per elementary sample, i.e., per channel and per real or
            imaginary component, used if header is not given.  Default: 2.
        """
    sample_shape = data.shape[1:]
    complex_data = data.dtype.kind == 'c'
    if header:
        bps = header.bps
    try:
        encoder = cls._encoders[bps]
    except KeyError:
        raise ValueError('{0} cannot encode data with {1} bits'.format(cls.
            __name__, bps))
    if complex_data:
        data = data.view((data.real.dtype, (2,)))
    words = encoder(data).ravel().view(cls._dtype_word)
    return cls(words, sample_shape=sample_shape, bps=bps, complex_data=
        complex_data)


def mergeDicts(*dict_args):
    """
    Given any number of dicts, shallow copy and merge into a new dict,
    precedence goes to key value pairs in latter dicts.
    """
    result = {}
    for dictionary in dict_args:
        result.update(dictionary)
    return result


@staticmethod
def p_daq_list_can_id_type_variable(p):
    """daq_list_can_id_type_variable : VARIABLE"""
    p[0] = p[1]


def table_entry_size(name, value):
    """
    Calculates the size of a single entry

    This size is mostly irrelevant to us and defined
    specifically to accommodate memory management for
    lower level implementations. The 32 extra bytes are
    considered the "maximum" overhead that would be
    required to represent each entry in the table.

    See RFC7541 Section 4.1
    """
    return 32 + len(name) + len(value)


@classmethod
def get_name(cls):
    """
        Return the name of this command.

        The default implementation strips any leading underscores and replaces
        all other underscores with dashes.
        """
    return cls.__name__.lstrip('_').replace('_', '-')


def string_y_n(string, default=None):
    """
    Strict mapping of a given string to a boolean.

    If it is `'y'` or `'Y'`, `True` is returned.
    If it is `'n'` or `'N'`, `True` is returned.
    If it is empty or None (evaluates to False), and `default` is set, `default` is returned.
    Else a `ValueError` is raised.

    :param string: The input
    :type  string: str

    :param default: default result for empty input
    :type  default: None | bool

    :raises ValueError: If it is not any of ['y', 'Y', 'n', 'N']
    :return: result (True/False/default)
    :rtype:  bool
    """
    if not string and default is not None:
        return default
    if string not in ['y', 'Y', 'n', 'N']:
        raise ValueError('Please enter y or n.')
    if string == 'y' or string == 'Y':
        return True
    if string == 'n' or string == 'N':
        return False


@property
def invert_mask(cls):
    """
        Mask for sign bit
        """
    return 2 ** cls.bits >> 1


def pype_return_f_args(accum, *fArgs):
    """
    FArgs is a tuple, but we want it to be a list - it's just neater.
    """
    return list(fArgs)


@staticmethod
def set_fragment_temporary_id(fragment, temporary_id, P1_array,
    index_individual_fragment):
    """Given a P1 array relative to a global fragment sets to 0 the row relative to fragment
        which is temporarily identified with identity temporary_id

        Parameters
        ----------
        fragment : Fragment
            Fragment object containing images associated with a single individual
        temporary_id : int
            temporary identifier associated to fragment
        P1_array  : nd.array
            P1 vector of fragment
        index_individual_fragment : int
            Index of fragment with respect to a global fragment in which it is contained

        Returns
        -------
        P1_array  : nd.array
            updated P1 array
        """
    fragment._temporary_id = int(temporary_id)
    P1_array[(index_individual_fragment), :] = 0.0
    P1_array[:, (temporary_id)] = 0.0
    return P1_array


def is_multitarget_regressor(clf):
    """
    Return True if a regressor is multitarget
    or False if it predicts a single target.
    """
    return len(clf.coef_.shape) > 1 and clf.coef_.shape[0] > 1


def check_key(key, expected_chr):
    """Checks the key against the expected_chr. Specifically running ord() on the expected_chr"""
    if key == ord(expected_chr.upper()) or key == ord(expected_chr.lower()):
        return True
    return False


def valid_chunk_size(chunk_size):
    """Checks whether chunk size is multiple of 256 KiB.

    Args:
        chunk_size (int): Input chunk_size to be validated.

    Returns:
        bool: True if chunk_size is multiple of 256 KiB, False otherwise.
    """
    return not bool(chunk_size % 262144)


def _linear_conversion(vector, cc_val):
    """ apply linear conversion to data

    Parameters
    ----------------
    vector : numpy 1D array
        raw data to be converted to physical value
    cc_val : mdfinfo4.info4 conversion block ('CCBlock') dict

    Returns
    -----------
    converted data to physical value
    """
    p1 = cc_val[0]
    p2 = cc_val[1]
    if p2 == 1.0 and p1 in (0.0, -0.0):
        return vector
    else:
        return vector * p2 + p1


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 reactivate_workflow_transitions(cr, transition_conditions):
    """
    Reactivate workflow transition previously deactivated by
    deactivate_workflow_transitions.

    :param transition_conditions: a dictionary returned by     deactivate_workflow_transitions

    .. versionadded:: 7.0
    .. deprecated:: 11.0
       Workflows were removed from Odoo as of version 11.0
    """
    for transition_id, condition in transition_conditions.iteritems():
        cr.execute('update wkf_transition set condition = %s where id = %s',
            (condition, transition_id))


def calculate_segment_name(host_name, recorder):
    """
    Returns the segment name based on recorder configuration and
    input host name. This is a helper generally used in web framework
    middleware where a host name is available from incoming request's headers.
    """
    if recorder.dynamic_naming:
        return recorder.dynamic_naming.get_name(host_name)
    else:
        return recorder.service


def StringProperty(name: str='', description: str='', default: str='',
    maxlen: int=0, options: set={'ANIMATABLE'}, subtype: str='NONE', update
    =None, get=None, set=None):
    """Returns a new string property definition.

    :param name: Name used in the user interface.
    :type name: str
    :param description: Text used for the tooltip and api documentation.
    :type description: str
    :param default: initializer string.
    :type default: str
    :param maxlen: maximum length of the string.
    :type maxlen: int
    :param options: Enumerator in [‘HIDDEN’, ‘SKIP_SAVE’, ‘ANIMATABLE’, ‘LIBRARY_EDITABLE’, ‘PROPORTIONAL’,’TEXTEDIT_UPDATE’].
    :type options: set
    :param subtype: Enumerator in [‘FILE_PATH’, ‘DIR_PATH’, ‘FILE_NAME’, ‘BYTE_STRING’, ‘PASSWORD’, ‘NONE’].
    :type subtype: str
    :param update: Function to be called when this value is modified, This function must take 2 values (self, context) and return None. Warning there are no safety checks to avoid infinite recursion.
    :param get: Function to be called when this value is ‘read’, This function must take 1 value (self) and return the value of the property.
    :param set: Function to be called when this value is ‘written’, This function must take 2 values (self, value) and return None.
    """
    pass


@staticmethod
def __map(index, interval):
    """
        update for CIRCexplorer particularly.
        """
    tmp_fragment = []
    if not interval:
        return index
    for dex in index:
        while True:
            try:
                fragment = interval.pop(0)
            except IndexError:
                if tmp_fragment:
                    interval.extend(tmp_fragment)
                    tmp_fragment = []
                    break
                else:
                    return index
            if fragment[0] < dex[0]:
                continue
            elif fragment[0] >= dex[1]:
                interval.insert(0, fragment)
                interval[0:0] = tmp_fragment
                tmp_fragment = []
                break
            elif fragment[1] > dex[1]:
                tmp_fragment.append(fragment)
                continue
            else:
                dex += fragment[2:]
    else:
        return index


def keyconfig_export(filepath: str='keymap.py', filter_folder: bool=True,
    filter_text: bool=True, filter_python: bool=True):
    """Export key configuration to a python script

    :param filepath: filepath
    :type filepath: str
    :param filter_folder: Filter folders
    :type filter_folder: bool
    :param filter_text: Filter text
    :type filter_text: bool
    :param filter_python: Filter python
    :type filter_python: bool
    """
    pass


def serialize_graftpoints(graftpoints):
    """Convert a dictionary of grafts into string

    The graft dictionary is:
        <commit sha1>: [<parent sha1>*]

    Each line is formatted as:
        <commit sha1> <parent sha1> [<parent sha1>]*

    https://git.wiki.kernel.org/index.php/GraftPoint

    """
    graft_lines = []
    for commit, parents in graftpoints.items():
        if parents:
            graft_lines.append(commit + b' ' + b' '.join(parents))
        else:
            graft_lines.append(commit)
    return b'\n'.join(graft_lines)


def _parse_names(last_name_dict):
    """Helper function to unpack the data when grouped by last name letter
    """
    big_list = []
    for last_letter, people_with_last in last_name_dict.items():
        for person in people_with_last:
            big_list.append(person)
    return big_list


def cmp(a, b):
    """Built in in python 2, but defined for python 3"""
    return (a > b) - (a < b)


def merge_dict(d: dict, defaults: dict) ->dict:
    """Merges a dictionary with a set of default values.

    This will combine the entries in two dictionaries, with the first
    argument taking preference.

    Args:
        d: The dictionary of specified values.
        default: The dictionary of default values.

    Returns:
        The merged dictionary.
    """
    return {**defaults, **d}


def create_path(segments):
    """Builds a path from a list of segments.

    :param stack: a list of segments
    :return: a path
    """
    return '/' + '/'.join(segments)


def authGSSClientUnwrap(context, challenge):
    """
    Perform the client side GSSAPI unwrap step

    @param challenge: a string containing the base64-encoded server data.
    @return: a result code (see above)
    """


@classmethod
def create(cls, obj=None, attrs=None, id=None, **kwargs):
    """ creates an instance of class, given an object and the
        attributes to take from it. (if attrs is None, tries to get
        cls.attrs next. If an attribute is not on object,
        stores None instead.
        kwargs are passed through, but are overwritten by attributes
        on object if in `attrs`.

        If obj is None, just creates with kwargs.
        Note that id is a primary key, so be careful with passing it!"""
    attrs = attrs or cls.attrs
    if object:
        for k in attrs:
            v = getattr(obj, k, None)
            if v is not None:
                kwargs[k] = v
    return cls(id=id, **kwargs)


@classmethod
def fromkeys(cls, iterable, value=None):
    """
        Similar to :meth:`dict.fromkeys`--creates a new `Header` from an
        iterable of keywords and an optional default value.

        This method is not likely to be particularly useful for creating real
        world FITS headers, but it is useful for testing.

        Parameters
        ----------
        iterable
            Any iterable that returns strings representing FITS keywords.

        value : optional
            A default value to assign to each keyword; must be a valid type for
            FITS keywords.

        Returns
        -------
        header
            A new `Header` instance.
        """
    d = cls()
    if not isinstance(value, tuple):
        value = value,
    for key in iterable:
        d.append((key,) + value)
    return d


def week():
    """
    Return millis for a week
    :return: 7 * 24 * 60 * 60 * 1000
    """
    return 604800000


def psds_from_job_length(timing_params, t):
    """
	Return the number of PSDs that can fit into a job of length t
	seconds.  In general, the return value is a non-integer.
	"""
    if t < 0:
        raise ValueError(t)
    t = t * timing_params.resample_rate - 2 * timing_params.filter_corruption
    if t < timing_params.psd_length:
        return 0
    return (t - timing_params.psd_length) / timing_params.psd_shift + 1


def duplicate_metaelems():
    """Duplicate selected metaelement(s)

    """
    pass


def get_num_rows(ai_settings, ship_height, alien_height):
    """determine the number of rows of aliens to fit the screen"""
    available_space_y = (ai_settings.screen_height - 3 * alien_height -
        ship_height)
    num_rows = int(available_space_y / (2 * alien_height))
    return num_rows


@classmethod
def get(cls, id):
    """Retrieve submission corresponding to specified id"""
    return cls._store.objects[id]


@classmethod
def _nest_reset(cls):
    """
        Reset the _to_nest bool and potential parent networks.
        """
    for pop in cls.__pops.valuerefs():
        if pop() is not None:
            pop()._to_nest = False
            for g in pop().values():
                g._to_nest = False
            if pop().parent is not None:
                pop().parent._nest_gids = None


def _getRequestNumEvents(propertyValue):
    """
    WMStats server can return this argument in three different data types.
    If there are multiple values, return only the first one.
    """
    if not propertyValue:
        return 0
    elif isinstance(propertyValue, list):
        return propertyValue[0]
    return propertyValue


def _name_to_agent_class(name: str):
    """
    Convert agent name to class.

    This adds "Agent" to the end of the name and uppercases the first letter
    and the first letter appearing after each underscore (underscores are
    removed).

    :param name:
        name of agent, e.g. local_human

    :return:
        class of agent, e.g. LocalHumanAgent.
    """
    words = name.split('_')
    class_name = ''
    for w in words:
        class_name += w[0].upper() + w[1:]
    class_name += 'Agent'
    return class_name


def fix_pid_for_jython_popen(gw):
    """
    fix for jython 2.5.1
    """
    spec, io = gw.spec, gw._io
    if spec.popen and not spec.via:
        if io.popen.pid is None:
            io.popen.pid = gw.remote_exec(
                'import os; channel.send(os.getpid())').receive()


def t_CPP_COMMENT1(t):
    """(/\\*(.|\\n)*?\\*/)"""
    ncr = t.value.count('\n')
    t.lexer.lineno += ncr
    return t


def dottedQuadToNum(ip):
    """
    Convert decimal dotted quad string to long integer

    >>> int(dottedQuadToNum('1 '))
    1
    >>> int(dottedQuadToNum(' 1.2'))
    16777218
    >>> int(dottedQuadToNum(' 1.2.3 '))
    16908291
    >>> int(dottedQuadToNum('1.2.3.4'))
    16909060
    >>> dottedQuadToNum('255.255.255.255')
    4294967295
    >>> dottedQuadToNum('255.255.255.256')
    Traceback (most recent call last):
    ValueError: Not a good dotted-quad IP: 255.255.255.256
    """
    import socket, struct
    try:
        return struct.unpack('!L', socket.inet_aton(ip.strip()))[0]
    except socket.error:
        raise ValueError('Not a good dotted-quad IP: %s' % ip)
    return


def __getattr__(cls, item):
    """
        Special warning for attribute errors.
        Its likely that user may have wanted to use a model interface
        instead of the Base class.
        """
    raise AttributeError(
        "'{0}' has no attribute '{1}'. Method may be a ModelInterface method. Did you mean '<yoursession>.{0}.{1}'?"
        .format(cls.__name__, item))


def getChildObjects():
    """Return a sequence of child objects
        """


@staticmethod
def _get_atoms(linkage, element):
    """
        Getting the atoms included in an element from a linkage object

        Atoms are the basic assets in a portfolio and not clusters.

        :param linkage: (np.array) Global linkage object
        :param element: (int) Element id to get atoms from
        :return: (list) Set of atoms
        """
    element_list = [element]
    while True:
        item_ = max(element_list)
        if item_ > linkage.shape[0]:
            element_list.remove(item_)
            element_list.append(linkage['i0'][item_ - linkage.shape[0] - 1])
            element_list.append(linkage['i1'][item_ - linkage.shape[0] - 1])
        else:
            break
    return element_list


def loadLocale(language=None, country=None, variant=None):
    """Load the locale with the specs that are given by the arguments of
        the method. Note that the LocaleProvider must know where to get the
        locales from."""


def get_certificate(ctx):
    """Get certificates from Certbot for HTTPS using webroot plugin.

    :param ctx:

    """
    project = ctx.project
    domain = project.domain
    email = project.email or ''
    webroot = ctx.paths.remote.project.state.certbot
    if email:
        email = '--email %s' % email
    command = (
        'certbot --agree-tos --no-eff-email %s certonly --webroot -d %s -w %s'
         % (email, domain, webroot))
    ctx.sudo(command)


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 emit_db_sequence_updates(engine):
    """Set database sequence objects to match the source db

       Relevant only when generated from SQLAlchemy connection.
       Needed to avoid subsequent unique key violations after DB build."""
    if engine and engine.name == 'postgresql':
        conn = engine.connect()
        qry = """SELECT 'SELECT last_value FROM ' || n.nspname ||
                         '.' || c.relname || ';' AS qry,
                        n.nspname || '.' || c.relname AS qual_name
                 FROM   pg_namespace n
                 JOIN   pg_class c ON (n.oid = c.relnamespace)
                 WHERE  c.relkind = 'S'"""
        for qry, qual_name in list(conn.execute(qry)):
            lastval, = conn.execute(qry).first()
            nextval = int(lastval) + 1
            yield 'ALTER SEQUENCE %s RESTART WITH %s;' % (qual_name, nextval)


def _docker_friendly_version(version):
    """
    Some untagged versions may have a '+' in which case is not a valid
    docker tag
    """
    return version.replace('+', '_')


def iterlen(iterator):
    """returns length of iterator"""
    return sum(1 for _ in iterator)


@staticmethod
def _convert_coefficients(coef):
    """
        Convert 'x', and '-x' into ('x', 1) and ('x', -1), respectively.

        Args:
            coef (list[(int, float) or int]): coef
        Returns:
            tuple: ind, val
        Raises:
            RuntimeError: unsupported type
        """
    ind = []
    val = []
    for e in coef:
        if isinstance(e, tuple):
            assert len(e) == 2
            ind.append(e[0])
            val.append(e[1])
        elif isinstance(e, int):
            if e >= 0:
                ind.append(e)
                val.append(1)
            else:
                ind.append(-e)
                val.append(-1)
        else:
            raise RuntimeError('unsupported type:' + str(e))
    return ind, val


def _convert_matmul(builder, node, graph, err):
    """
    convert to CoreML BatchedMatMul Layer:
    https://github.com/apple/coremltools/blob/655b3be5cc0d42c3c4fa49f0f0e4a93a26b3e492/mlmodel/format/NeuralNetwork.proto#L3473
    """
    weight_name = node.inputs[1]
    W = None
    weight_as_layer_parameter = False
    if weight_name in node.input_tensors:
        W = node.input_tensors[weight_name]
    if W is not None:
        if len(W.shape) != 2:
            builder.add_load_constant_nd(node.name + '_const_weight_input',
                weight_name, constant_value=W, shape=W.shape)
        else:
            weight_as_layer_parameter = True
    if weight_as_layer_parameter:
        builder.add_batched_mat_mul(name=node.name, input_names=[node.
            inputs[0]], output_name=node.outputs[0], weight_matrix_rows=W.
            shape[0], weight_matrix_columns=W.shape[1], W=W)
    else:
        builder.add_batched_mat_mul(name=node.name, input_names=[node.
            inputs[0], weight_name], output_name=node.outputs[0])


def _guess(kwargs):
    """
    Adds types, actions, etc. to given argument specification.
    For example, ``default=3`` implies ``type=int``.

    :param arg: a :class:`argh.utils.Arg` instance
    """
    guessed = {}
    TYPE_AWARE_ACTIONS = 'store', 'append'
    value = kwargs.get('default')
    if value is not None:
        if isinstance(value, bool):
            if kwargs.get('action') is None:
                guessed['action'] = 'store_false' if value else 'store_true'
        elif kwargs.get('type') is None:
            if kwargs.get('action', 'store') in TYPE_AWARE_ACTIONS:
                guessed['type'] = type(value)
    if kwargs.get('choices') and 'type' not in list(guessed) + list(kwargs):
        guessed['type'] = type(kwargs['choices'][0])
    return dict(kwargs, **guessed)


def identify():
    """Retrieve information about the repository.

        Returns an Identify object describing the repository.
        """


def deleteObject(cursor, oid_int, tid_int):
    """
        Delete the revision of *oid_int* in transaction *tid_int*.

            This method marks an object as deleted via a new object
            revision. Subsequent attempts to load current data for the
            object will fail with a POSKeyError, but loads for
            non-current data will suceed if there are previous
            non-delete records. The object will be removed from the
            storage when all not-delete records are removed.

            The serial argument must match the most recently committed
            serial for the object. This is a seat belt.

            --- Documentation for ``IExternalGC``

        In history-free databases there is no such thing as a delete record, so
        this should remove the single
        revision of *oid_int* (which *should* be checked to verify it
        is at *tid_int*), leading all access to *oid_int* in the
        future to throw ``POSKeyError``.

        In history preserving databases, this means to set the state for the object
        at the transaction to NULL, signifying that it's been deleted. A subsequent
        pack operation is required to actually remove these deleted items.
        """


def dictFromList(data_list):
    """Returns a dict given a list.

        - Dict created from a list where list contains alternating key, value
        pairs.
        - ex: [key1, value1, key2, value2] returns: {key1:value1, key2:value2}
    """
    data_dict = {}
    for i in range(0, len(data_list) - 1, 2):
        if data_list[i] in data_dict:
            data_dict[data_list[i]] = data_dict[data_list[i]
                ] + ' ' + data_list[i + 1]
        else:
            data_dict[data_list[i]] = data_list[i + 1]
    return data_dict


def test_DNA_from_seq():
    """ Test correct DNA initialization from sequence files"""
    pass


def showDifferences(seq1, seq2):
    """Returns a string highligthing differences between seq1 and seq2:

	* Matches by '-'

	* Differences : 'A|T'

	* Exceeded length : '#'

	"""
    ret = []
    for i in range(max(len(seq1), len(seq2))):
        if i >= len(seq1):
            c1 = '#'
        else:
            c1 = seq1[i]
        if i >= len(seq2):
            c2 = '#'
        else:
            c2 = seq2[i]
        if c1 != c2:
            ret.append('%s|%s' % (c1, c2))
        else:
            ret.append('-')
    return ''.join(ret)


def _prefix_empty_lines(lines, goal_empty_count):
    """
	Internal function to prepend empty lines (no prefix considerations).
	"""
    """ find current empty line count """
    current_empty_count = 0
    for line in lines:
        if line.strip():
            break
        current_empty_count += 1
    """ insert newlines if too few """
    lines = [''] * (goal_empty_count - current_empty_count) + lines
    """ remove newlines if too many """
    if current_empty_count > goal_empty_count:
        lines = lines[current_empty_count - goal_empty_count:]
    """ done! """
    return lines


@staticmethod
def is_point(line):
    """ Returns true if the specified line is in fact a point.

        'line' is a line segment of form [x0,y0,x1,y1].

        Edge.is_point(np.arr[float(x4)]) -> bool

        """
    x0, y0, x1, y1 = line
    return x0 == x1 and y0 == y1


def transform_padding(pad_width):
    """Helper function to convert padding format for pad operator.
    """
    num_pad_values = len(pad_width)
    onnx_pad_width = [0] * num_pad_values
    start_index = 0
    end_index = int(num_pad_values / 2)
    for idx in range(0, num_pad_values):
        if idx % 2 == 0:
            onnx_pad_width[start_index] = pad_width[idx]
            start_index += 1
        else:
            onnx_pad_width[end_index] = pad_width[idx]
            end_index += 1
    return onnx_pad_width


def debug(result):
    """
    Function to debug output using the console / ipython.

    USAGE:::

    from dnsdb.utils import debug
    r = dnsdb.search(name="www.fsi.io")
    debug(r)

    :param result: object
    :return: text: stdout
    """
    if result.status_code:
        print('Status Code: {}'.format(result.status_code))
    else:
        print('Status Code: None')
    if result.error:
        print('Error: {}'.format(result.error))
    else:
        print('Error: None')
    if result.quota:
        print('Quota: {}'.format(result.quota))
    else:
        print('Quota: None')
    if result.cached:
        print('Cached: {}'.format(result.cached))
    else:
        print('Cached: None')
    if result.records:
        print('Records exist: True')
        print('Number of records: {}'.format(len(result.records)))
    else:
        print('Records exist: False')


def set(object, value):
    """Set the value of the field for the object

        Raises a type error if the field is a read-only field.
        """


@staticmethod
def importAllTasks():
    """ import all available tasks in qbackup/tasks folder

            the ./tasks/__init__.py will dynamically import all sub-packages
        """
    from . import tasks


def get_border():
    """Returns the border.

    :return:  A tuple of 4 numbers (xmin, ymin, xmax, ymax).
    """
    pass


@property
def label(cls):
    """Returns the label of the hasher"""
    return cls.name if not cls._weak else '{} (weak)'.format(cls.name)


def _add_approx_entity_index_var(es, target_entity_id, cutoffs, path):
    """
    Add a variable to the cutoff df linking it to the entity at the end of the
    path.

    Return the updated cutoff df and the name of this variable. The name will
    consist of the variables which were joined through.
    """
    last_child_var = 'instance_id'
    last_parent_var = es[target_entity_id].index
    for _, relationship in path:
        child_vars = [last_parent_var, relationship.child_variable.id]
        child_df = es[relationship.child_entity.id].df[child_vars]
        new_var_name = '%s.%s' % (last_child_var, relationship.
            child_variable.id)
        to_rename = {relationship.child_variable.id: new_var_name}
        child_df = child_df.rename(columns=to_rename)
        cutoffs = cutoffs.merge(child_df, left_on=last_child_var, right_on=
            last_parent_var)
        last_child_var = new_var_name
        last_parent_var = relationship.parent_variable.id
    return cutoffs, new_var_name


def download_tanzil_translations():
    """  http://tanzil.net/trans/ """
    pass


def custom_function(func, input_files, output_file):
    """
    Calls a custom function which must create the output file.

    The custom function takes 3 parameters: ``input_files``,
    ``output_file`` and a boolean ``release``.
    """
    from .modules import utils
    return {'dependencies_fn': utils.no_dependencies, 'compiler_fn': func,
        'input': input_files, 'output': output_file, 'kwargs': {}}


def selector(zelf, want=[]):
    """ see if this objects has the desired attributes. """
    go = False
    for arg in want:
        if arg in zelf and zelf[arg]:
            go = True
            break
    return go


def end_frame_set():
    """Set the end frame

    """
    pass


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


def count_execution_frequency(rl, scale=None):
    """Build resource profiles based on how frequently resources
    originated events of execution modes.

    Each column in the result profiles corresponds with an execution
    mode captured in the given resource log.

    Parameters
    ----------
    rl : DataFrame
        A resource log.
    scale : {None, 'normalize', log'}, optional, default None
        Options for deciding how to scale the values of frequency
        counting. Could be one of the following:

            - ``None``, no scaling will be performed.
            - ``'normalize'``, scale the frequency values by the total
              count of executions by each resource.
            - ``'log'``, scale the frequency values by logarithm.

    Returns
    -------
    DataFrame
        The constructed resource profiles.

    Raises
    ------
    ValueError
        If the specified option for scaling is invalid.
    """
    from collections import defaultdict
    mat = defaultdict(lambda : defaultdict(lambda : 0))
    for res, trace in rl.groupby('resource'):
        for event in trace.itertuples():
            exec_mode = event.case_type, event.activity_type, event.time_type
            mat[res][exec_mode] += 1
    from pandas import DataFrame
    df = DataFrame.from_dict(mat, orient='index').fillna(0)
    if scale is None:
        return df
    elif scale == 'normalize':
        return df.div(df.sum(axis=1), axis=0)
    elif scale == 'log':
        from numpy import log
        return df.apply(lambda x: log(x + 1))
    else:
        raise ValueError('Invalid value for parameter `{}`: {}'.format(
            'scale', scale))


def get_cdata(text):
    """wrap the text in cdata escaping"""
    return '<![CDATA[{}]]>'.format(text)


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

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


def remove_options(options, names):
    """Removes options from the dictionary.

    Modifies options.

    Args:
        options: dict
        names: list of keys
    """
    for name in names:
        if name in options:
            del options[name]


def validate(key):
    """Check that the key is a string or bytestring.

    That's the only valid type of key.
    """
    if not isinstance(key, (str, bytes)):
        raise KeyError('Key must be of type str or bytes, found type {}'.
            format(type(key)))


def send_task_heartbeat(taskToken=None):
    """
    Used by workers to report to the service that the task represented by the specified taskToken is still making progress. This action resets the Heartbeat clock. The Heartbeat threshold is specified in the state machine's Amazon States Language definition. This action does not in itself create an event in the execution history. However, if the task times out, the execution history will contain an ActivityTimedOut event.
    See also: AWS API Documentation

    :example: response = client.send_task_heartbeat(
        taskToken='string'
    )

    :type taskToken: string
    :param taskToken: [REQUIRED]
            The token that represents this task. Task tokens are generated by the service when the tasks are assigned to a worker (see GetActivityTask::taskToken).

    :rtype: dict
    :return: {}

    """
    pass


def _normalize_dataframe(dataframe, index):
    """Take a pandas DataFrame and count the element present in the
    given columns, return a hierarchical index on those columns
    """
    data = dataframe[index].dropna()
    grouped = data.groupby(index, sort=False)
    counted = grouped[index].count()
    averaged = counted.mean(axis=1)
    averaged = averaged.fillna(0.0)
    return averaged


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


def intersect(list1, list2):
    """ Returns intersection of two lists """
    return list(set(list1) & set(list2))


def _get_locus(cluster):
    """get the bigger locus"""
    return True


def transduce(transformer, reducer, seed, iterable):
    """
    transformer is (a -> b)
    reducer is (b -> a -> b)
    seed is b
    iterable is [a]
    """
    transformedReducer = transformer(reducer)
    accumulation = seed
    for value in iterable:
        accumulation = transformedReducer(accumulation, value)
    return accumulation


def where_which(path):
    """
    Backwards compatibility wrapper for approximating which/where.

    :param path: Path to a file.
    :type path: str
    """
    try:
        from shutil import which
    except ImportError:
        from shutilwhich import which
    finally:
        thepath = which(path)
    return thepath


def output_as_percentage(num, fractional_digits=1):
    """Output a percentage neatly.

    fractional_digits = number of digits to output as fractions of a percent.
    If None is supplied, there is no reduction in precision."""
    if fractional_digits is not None:
        format_str = '%%.%.df' % fractional_digits
    else:
        format_str = '%f'
    return '%s%%' % (format_str % num)


def stabilize_2d_add():
    """Add selected tracks to 2D translation stabilization

    """
    pass


def getDefaultConfiguration(requestor, service, nodeType):
    """
        Called when a default node configuration 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 nodeType: The type of node for which the configuration is
                         retrieved, C{'leaf'} or C{'collection'}.
        @type nodeType: C{str}
        @return: A deferred that fires with a C{dict} representing the default
                 node configuration. Keys are C{str}s that represent the
                 field name. Values can be of types C{unicode}, C{int} or
                 C{bool}.
        @rtype: L{Deferred<twisted.internet.defer.Deferred>}
        """


def _(s):
    """Placeholder for gettext; we may internationalize this library later."""
    return s


@staticmethod
def metadata_updated_on(item):
    """Extracts and coverts the update time from a Docker Hub item.

        The timestamp is extracted from 'fetched_on' field. This field
        is not part of the data provided by Docker Hub. It is added
        by this backend.

        :param item: item generated by the backend

        :returns: a UNIX timestamp
        """
    return item['fetched_on']


@classmethod
def find(cls, key):
    """Look up user database entry"""
    query = cls.db.query(cls.model.orm)
    attr = getattr(cls.model.orm, cls.model.key)
    row = query.filter(attr == key).one_or_none()
    return cls(row) if row is not None else None


def bump_version(version, abi_break):
    """
    Bump a version depending if the ABI was broken or not

    If the ABI was broken, CUR is bumped; AGE and REV are set to zero.
    Otherwise, CUR is kept, AGE is bumped, and REV is set to zero.
    This also works with versions without the REV component (e.g. [1, 4, None])

    :param version:     A list in format [CUR, AGE, REV]
    :param abi_break:   A boolean indication if the ABI was broken
    :returns:           A list in format [CUR, AGE, REV]
    """
    new_version = []
    if abi_break:
        if version[0] is not None:
            new_version.append(version[0] + 1)
        new_version.extend([0] * len(version[1:]))
    else:
        if version[0] is not None:
            new_version.append(version[0])
        if version[1] is not None:
            new_version.append(version[1] + 1)
        new_version.extend([0] * len(version[2:]))
    return new_version


def normalize(config):
    """
    Given a configuration dict, apply particular hard-coded rules to normalize its contents to
    adhere to the configuration schema.
    """
    exclude_if_present = config.get('location', {}).get('exclude_if_present')
    if isinstance(exclude_if_present, str):
        config['location']['exclude_if_present'] = [exclude_if_present]


@classmethod
def get_factory(cls, *args, **kw):
    """
        A class function which returns a runnable which calls the factory function (i.e. the
        constructor) of the class with the arguments provided.
        This should makes it easy to bind GrowlerProtocol construction explicitly. All
        arguments are forwarded to the constructor.
        """
    return lambda : cls.factory(*args, **kw)


def send_batman(person, model):
    """Returns whether or not the person Batman should be called on this
    person based on a statistical model

    Args:
        person (str): the target's name
        model (code.Model): model to perform inference with

    Returns:
        bool: blabla
    """
    print(person, model)
    return person in model


@staticmethod
def check_classes_balance(counts):
    """Checks that the dataset contains enough samples of each class"""
    for item1 in counts:
        for item2 in counts:
            if item1 > item2 * 3:
                return (
                    'Provided classes are very unbalanced, predictions may not be accurate.'
                    )
    return False


def div_with_small_value(n, d, eps=1e-08):
    """
    Small values are replaced by 1e-8 to prevent it from exploding.

    :param n: tensor
    :param d: tensor
    :return: n/d: tensor
    """
    d = d * (d > eps).float() + eps * (d <= eps).float()
    return n / d


def verify_paired(record1, record2):
    """Check if the two sequence records belong to the same fragment.

    In an matching pair the records are left and right pairs
    of each other, respectively.  Returns True or False as appropriate.

    Handles both Casava formats: seq/1 and seq/2, and 'seq::... 1::...'
    and 'seq::... 2::...'.
    """
    l_name, l_desc = record1.id, record1.description
    r_name, r_desc = record2.id, record2.description
    if l_name.endswith('/1') and r_name.endswith('/2'):
        subpart1 = l_name.split('/', 1)[0]
        subpart2 = r_name.split('/', 1)[0]
        if subpart1 and subpart1 == subpart2:
            return True
    elif l_name == r_name and l_desc.startswith('1:') and r_desc.startswith(
        '2:'):
        return True
    elif l_name == r_name:
        return True
    return False


def _build_datacenter_groups(hostvars):
    """
    Return a dictionary of groups, one for each datacenter, containing all
    of the servers in that datacenter
    :param hostvars: The hostvars dictionary to parse
    :return: Dictionary of dynamically built Datacenter groups
    """
    result = {}
    hostvars = hostvars.get('hostvars')
    for server in hostvars:
        datacenter = hostvars[server]['clc_data']['locationId']
        if datacenter not in result:
            result[datacenter] = []
        result[datacenter] += [server]
    return result


def name_equality_check(setup_deps, pipfile_deps):
    """
    Checks that all names present in either dependency file are present
    in both dependency files

    Args:
        setup_deps (dict<str, list<tuple<str, str>>>):
            Dictionary from setup.py dependency name keys to a list of
            tuples as a value, with the tuples containing
            a comparision operator and a version specification.
        pipfile_deps (dict<str, list<tuple<str, str>>>):
            Dictionary from Pipfile dependency name keys to a list of
            tuples as a value, with the tuples containing
            a comparision operator and a version specification.
    Returns:
        bool:
            Whether the check passes - will always be true, otherwise the
            function will not reach this line.
    Raises:
        ValueError:
            If there are discrepancies between version names
    """
    in_setup_not_pipfile = set(setup_deps.keys()).difference(set(
        pipfile_deps.keys()))
    in_pipfile_not_setup = set(pipfile_deps.keys()).difference(set(
        setup_deps.keys()))
    if len(in_setup_not_pipfile) or len(in_pipfile_not_setup):
        err_msg = 'Dependency name mismatch!\n'
        if len(in_setup_not_pipfile):
            err_msg += 'Dependencies in setup.py but not in Pipfile: ' + str(
                in_setup_not_pipfile) + '\n'
        if len(in_pipfile_not_setup):
            err_msg += 'Dependencies in Pipfile but not in setup.py: ' + str(
                in_pipfile_not_setup) + '\n'
        raise ValueError(err_msg)
    return True


def separate_loop_head_tail_slab(kernel, iname, head_it_count, tail_it_count):
    """Mark *iname* so that the separate code is generated for
    the lower *head_it_count* and the upper *tail_it_count*
    iterations of the loop on *iname*.
    """
    iname_slab_increments = kernel.iname_slab_increments.copy()
    iname_slab_increments[iname] = head_it_count, tail_it_count
    return kernel.copy(iname_slab_increments=iname_slab_increments)


def block_level_page_name(sibling_before, sibling_after):
    """Return the next page name when siblings don't have the same names."""
    before_page = sibling_before.page_values()[1]
    after_page = sibling_after.page_values()[0]
    if before_page != after_page:
        return after_page


def _name_add(name):
    """Add '+' to the front of positive values. Also keeps the '-' in front of negative values.
    """
    name = str(float(name))
    if name[0] != '-':
        name = '+' + name
    return name


def _parse_index_file(filename):
    """Parse index file."""
    index = []
    for line in open(filename):
        index.append(int(line.strip()))
    return index


def get_bucket_logging(Bucket=None):
    """
    Returns the logging status of a bucket and the permissions users have to view and modify that status. To use GET, you must be the bucket owner.
    See also: AWS API Documentation

    :example: response = client.get_bucket_logging(
        Bucket='string'
    )

    :type Bucket: string
    :param Bucket: [REQUIRED]

    :rtype: dict
    :return: {
        'LoggingEnabled': {
            'TargetBucket': 'string',
            'TargetGrants': [
                {
                    'Grantee': {
                        'DisplayName': 'string',
                        'EmailAddress': 'string',
                        'ID': 'string',
                        'Type': 'CanonicalUser'|'AmazonCustomerByEmail'|'Group',
                        'URI': 'string'
                    },
                    'Permission': 'FULL_CONTROL'|'READ'|'WRITE'
                },
            ],
            'TargetPrefix': 'string'
        }
    }

    """
    pass


def format_aemo_url(url, year, month, filename):
    """This fills in the missing information in the AEMO url so data for the right month, year and file name are
    downloaded"""
    year = str(year)
    return url.format(year, year, month, filename[:-4])


@classmethod
def stopPreciseCoverage(cls):
    """Disable precise code coverage. Disabling releases unnecessary execution count records and allows
executing optimized code.
        """
    return cls.build_send_payload('stopPreciseCoverage', {}), None


@staticmethod
def rotate_shift_mask_simplifier(a, b):
    """
        Handles the following case:
            ((A << a) | (A >> (_N - a))) & mask, where
                A being a BVS,
                a being a integer that is less than _N,
                _N is either 32 or 64, and
                mask can be evaluated to 0xffffffff (64-bit) or 0xffff (32-bit) after reversing the rotate-shift
                operation.

        It will be simplified to:
            (A & (mask >>> a)) <<< a
        """
    if b.op != 'BVV':
        return None
    if a.op != '__or__' or len(a.args) != 2:
        return None
    a_0, a_1 = a.args
    if a_0.op != '__lshift__':
        return None
    if a_1.op != 'LShR':
        return None
    a_00, a_01 = a_0.args
    a_10, a_11 = a_1.args
    if not a_00 is a_10:
        return None
    if a_01.op != 'BVV' or a_11.op != 'BVV':
        return None
    lshift_ = a_01.args[0]
    rshift_ = a_11.args[0]
    bitwidth = lshift_ + rshift_
    if bitwidth not in (32, 64):
        return None
    if bitwidth == 32:
        m = b.args[0] << rshift_ & 4294967295 | b.args[0] >> lshift_
        if m != 65535:
            return None
    else:
        m = b.args[0] << rshift_ & 18446744073709551615 | b.args[0] >> lshift_
        if m != 4294967295:
            return None
    masked_a = a_00 & m
    expr = masked_a << lshift_ | masked_a >> rshift_
    return expr


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 batch_start(tags=(), **metadata):
    """
        Create a new message batch.

        :param tags:
            Sequence of tags to add to the new batch.
        :param **metadata:
            Keyword parameters containing batch metadata.

        :returns:
            The batch identifier for the new batch.
            If async, a Deferred is returned instead.
        """


def get_str_arg(r, name, default=None):
    """
    Retrieve argument from :attr:`flask:flask.request` and convert to string

    :param r: :attr:`flask:flask.request`
    :param name: argument name
    :type: str
    :param default: default value if parameter is non-existent, defaults to None
    :return: string argument value
    """
    val = r.args.get(name)
    if val is None or val == '':
        return default
    else:
        try:
            return str(val)
        except BaseException:
            return default


def set_config(THREAD_LIMIT=None, PORT=None, PORT_RANGE=None, GROUP=None,
    IS_HUB=None):
    """
    Set a configuration value. These are configuration values that can be set at
    runtime to modify your net configuration.

    :return:
    """


@staticmethod
def emotes(tags) ->list:
    """ parse emotes to list"""
    try:
        if 'emotes' in tags and type(tags['emotes']) == str:
            emoticons = tags['emotes'].split('/')
            emotes = {}
            for emoticon in emoticons:
                part = emoticon.split(':')
                if part[1] == None:
                    return
                emotes[part[0]] = part[1].split(',')
            tags['emotes-raw'] = tags['emotes']
            tags['emotes'] = emotes
        if 'emotes' in tags and type(tags['emotes']) == bool:
            tags['emotes-raw'] = None
        return tags
    except:
        pass


def unregisterProducer():
    """
        Stop consuming data from a producer, without disconnecting.
        """


def textbox_add():
    """Add a new text box

    """
    pass


@classmethod
def get_by_username(cls, username):
    """
        Return a User by email address
        """
    return cls.query().filter(cls.username == username).first()


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

    Like 'git describe --tags --dirty --always -long'.
    The distance/hash is unconditional.

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


@classmethod
def query(cls):
    """
        Begin querying the model.

        :return: A Builder instance
        :rtype: eloquent.orm.Builder
        """
    return cls().new_query()


def check_primitive_type(stmt):
    """i_type_spec appears to indicate primitive type.
    """
    return True if getattr(stmt, 'i_type_spec', None) else False


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


@classmethod
def from_evt(cls, evt):
    """
        Initializes a new instance of given class by copying all current data.

        Args:
            evt: pero.PropertyChangedEvt
                Source event from which to copy the data.

        Returns:
            cls instance
                New instance of requested class.
        """
    return cls(name=evt.name, old_value=evt.old_value, new_value=evt.new_value)


def _get_sample_names(input_vcf):
    """Returns list of sample names from input VCF"""
    with open(input_vcf, 'r') as input_file:
        column_header = None
        sample_names = []
        for line in input_file.readlines():
            if not line.startswith('##'):
                if line.startswith('#'):
                    column_header = line.rstrip()
                    column_fields = column_header.split('\t')
                    n = len(column_fields)
                    sample_names = column_fields[9:n + 1]
        return sample_names


def _get_block_length(lines, k):
    """ Calculates the length (in number of lines) of a edit of added/deleted lines starting in a
        given line k.

    Args:
        lines: dictionary of added or deleted lines
        k: line number to check for

    Returns:
        block_size: number of lines in the contiguously block that was modified
    """
    if k not in lines or k > 1 and k - 1 in lines:
        edit = False
        block_size = 0
    else:
        edit = True
        block_size = 1
    while edit:
        if k + block_size in lines:
            block_size += 1
        else:
            edit = False
    return block_size


def print_netlist_line(dic):
    """
    Return the line of the pyphs netlist associated to
    > dic.comp label nodes parameters

    Parameters
    ----------

    item : dict

        Dictionary that encodes the component with keys:

            * 'dictionary': str

                module in 'pyphs/dicitonary/'

            * 'component':

                component in 'dictionary'

            * 'label':

                component label

            * 'nodes':

                tuple of nodes identifiers

            * 'arguments': dict

                Dictionary of parameters. Keys are parameters labels in dic.comp, and values are float (parameter value), str (new parameter label) or tuple (str, float).

    Output
    -------

    line : str

        Formated string that corresponds to a single line in the netlist         (includes end cariage return).
    """
    component = '{0}.{1} {2} {3}:'.format(dic['dictionary'], dic[
        'component'], dic['label'], dic['nodes'])
    pars = ''
    if dic['arguments'] is not None:
        for par in dic['arguments'].keys():
            pars += ' {}={};'.format(par, str(dic['arguments'][par]))
    line = component + pars + '\n'
    return line


def validate_requirements_ok():
    """Validate requirements, returns True of ok."""
    from gen_requirements_all import main as req_main
    return req_main(True) == 0


@classmethod
def _parse_trace_logging(cls, trace_def):
    """Parse tracing by Python's logging facilities.

        :param trace_def: definition of tracing as supplied in the YAML file
        """
    if trace_def is True:
        cls._trace_logging.append(trace_def)


def registerUpgradePath(oldversion, newversion, function):
    """ Basic register func """
    pass


def get_options(db, prefix=None):
    """
    for coretable in CORETABLES:
        table_group.add_argument('--' + coretable.name,
                            default=None,
							metavar='owner.tablename',
							dest=coretable.name)
    """
    options = {'url': 'sqlite:///' + db, 'prefix': prefix}
    return options


def float_if_float(float_string):
    """
    Given a float string, returns the float value.
    On value error returns the original string.
    """
    try:
        float_val = float(float_string)
        return float_val
    except ValueError:
        return float_string


@classmethod
def is_intersecting(cls):
    """Present to fulfill the contract with Abstractlocus, but
        it only raises a NotImplementedError"""
    raise NotImplementedError()


@classmethod
def GetParsersInformation(cls):
    """Retrieves the parsers information.

    Returns:
      list[tuple[str, str]]: parser names and descriptions.
    """
    parsers_information = []
    for _, parser_class in cls._GetParsers():
        description = getattr(parser_class, 'DESCRIPTION', '')
        parsers_information.append((parser_class.NAME, description))
    return parsers_information


def human_bytes(n):
    """
    return the number of bytes 'n' in more human readable form
    """
    if n < 1024:
        return '%i B' % n
    k = (n - 1) / 1024 + 1
    if k < 1024:
        return '%i KB' % k
    return '%.2f MB' % (float(n) / 2 ** 20)


@staticmethod
def __get_options(cache, key, override_options, pool_options):
    """Gets the options for the specified key."""
    options = cache.get(key)
    if not options:
        options = pool_options.get('*').copy()
        options_form_config = pool_options.get(key)
        if options_form_config:
            options.update(options_form_config)
        cache[key] = options
    if override_options:
        options = options.copy()
        options.update(override_options)
    return options


def prtOptions():
    """Print a list of command-line options and arguments."""
    print('The command-line arguments are:')
    print('  -h (print help)')
    print('  --help (print help)')
    print('  -r (print the full version string)')
    print('  --version (print the version number)')
    print('  -v (print messages)')
    print('  input:  input corrtag file name')
    print("  output:  output corrtag file name, or '' or none")
    print('      if output was not specified, the input file will be modified')
    print('      in-place (unless filter was also not specified, equivalent to'
        )
    print("      filter='info')")
    print('  filter:  column name, relation, cutoff value')
    print("      e.g. 'sun_alt > -0.5 or ly_alpha > 2'")
    print("      or 'info' or 'reset' ('clear' is synonymous with 'reset')")


def floor(value, size, offset=200):
    """Floor of `value` given `size` and `offset`.

    The floor function is best understood with a diagram of the number line::

         -200  -100    0    100   200
        <--|--x--|-----|--y--|--z--|-->

    The number line shown has offset 200 denoted by the left-hand tick mark at
    -200 and size 100 denoted by the tick marks at -100, 0, 100, and 200. The
    floor of a value is the left-hand tick mark of the range where it lies. So
    for the points show above: ``floor(x)`` is -200, ``floor(y)`` is 0, and
    ``floor(z)`` is 100.

    >>> floor(10, 100)
    0.0
    >>> floor(120, 100)
    100.0
    >>> floor(-10, 100)
    -100.0
    >>> floor(-150, 100)
    -200.0
    >>> floor(50, 167)
    -33.0

    """
    return float((value + offset) // size * size - offset)


def descope_queue_name(scoped_name):
    """Returns the unscoped queue name, given a fully-scoped name."""
    return scoped_name.partition('/')[2] or None


def get_gain(row):
    """Finds the gain of the row

    Parameters
    ----------
    row : pandas row
       Row obtained by merging a transaction with a
       bid dataframe

    Returns
    -------
    gain
        The gain obtained by the row

    """
    gap = row.price_y - row.price_x
    if not row.buying:
        gap = -gap
    return gap * row.quantity


def set_gpu_device_id(did: int):
    """
        Set the gpu device id we are using.
    """
    global gpu_device_id
    gpu_device_id = did


def remove(name):
    """
        Remove all header name/value pairs for the given header name.

        If the given name is L{Text}, it will be encoded as ISO-8859-1 before
        comparing to the (L{bytes}) header names.

        @param name: The name of the header to remove.
        """


@classmethod
def empty(cls, width=0, height=0):
    """
        Creates an empty :class:`Image`
        """
    return cls(width=width, height=height)


def to_bool(string):
    """Returns a boolean from a string.

    string -- string in format yes|no|true|false
    """
    if string.lower() in ('yes', 'y', 'true', '1'):
        return True
    elif string.lower() in ('no', 'n', 'false', '0'):
        return False
    raise ValueError(str(string) +
        ' not in ["yes", "y", "true", "1", "no", "n", "false", "0"].')


def update_label2(label2, isubcase):
    """strips off SUBCASE from the label2 to simplfify the output keys (e.g., displacements)"""
    label2 = label2.split('$')[0].strip()
    if label2:
        subcase_expected = 'SUBCASE %i' % isubcase
        subcase_equal_expected = 'SUBCASE = %i' % isubcase
        if subcase_expected == label2:
            label2 = ''
        elif label2 == 'NONLINEAR':
            pass
        elif subcase_expected in label2:
            nchars = len(subcase_expected)
            ilabel_1 = label2.index(subcase_expected)
            ilabel_2 = ilabel_1 + nchars
            label2_prime = label2[:ilabel_1] + label2[ilabel_2:]
            label2 = label2_prime.strip()
        elif subcase_equal_expected in label2:
            slabel = label2.split('=')
            assert len(slabel) == 2, slabel
            label2 = ''
        elif label2.startswith('NONLINEAR '):
            sline = label2.split('NONLINEAR ', 1)
            label2 = 'NONLINEAR ' + sline[1].strip()
        elif 'PVAL ID=' in label2 and 'SUBCASE=' in label2:
            ilabel2 = label2.index('SUBCASE')
            slabel = label2[:ilabel2].strip().split('=')
            assert slabel[0] == 'PVAL ID', slabel
            label2 = slabel[0].strip() + '=' + slabel[1].strip()
        elif 'SUBCASE' in label2:
            slabel = label2.split('$')[0].strip().split()
            if len(slabel) == 2:
                label2 = ''
            elif len(slabel) == 3 and slabel[1] == '=':
                label2 = ''
            else:
                assert slabel[0] == 'SUBCASE', slabel
                label2 = slabel[3] + '=' + slabel[5]
        elif 'SUBCOM' in label2:
            subcom, isubcase = label2.split()
            label2 = ''
        elif 'SYM' in label2 or 'REPCASE' in label2:
            pass
    return label2


def p_idfobjectlist_multiple(p):
    """idfobjectlist : idfobject idfobjectlist"""
    p[0] = [p[1]] + p[2]


def sequence(value):
    """Return tuple containing value if value is not a tuple or list.

    >>> sequence(1)
    (1,)
    >>> sequence([1])
    [1]
    >>> sequence('ab')
    ('ab',)

    """
    return value if isinstance(value, (tuple, list)) else (value,)


def mute_toggle():
    """Mute or un-mute selected strips

    """
    pass


def unmap_trigger(library, session, trigger_source, trigger_destination):
    """Undo a previous map from the specified trigger source line to the specified destination line.

    Corresponds to viUnmapTrigger function of the VISA library.

    :param library: the visa library wrapped by ctypes.
    :param session: Unique logical identifier to a session.
    :param trigger_source: Source line used in previous map. (Constants.TRIG*)
    :param trigger_destination: Destination line used in previous map. (Constants.TRIG*)
    :return: return value of the library call.
    :rtype: :class:`pyvisa.constants.StatusCode`
    """
    return library.viUnmapTrigger(session, trigger_source, trigger_destination)


def fourth_bashforth(state, tendencies_list, timestep):
    """Return the new state using fourth-order Adams-Bashforth. tendencies_list
    should be a list of dictionaries whose values are tendencies in
    units/second (from oldest to newest), and timestep should be a timedelta
    object."""
    return_state = {}
    for key in tendencies_list[0].keys():
        return_state[key] = state[key] + timestep.total_seconds() * (55.0 /
            24 * tendencies_list[-1][key] - 59.0 / 24 * tendencies_list[-2]
            [key] + 37.0 / 24 * tendencies_list[-3][key] - 3.0 / 8 *
            tendencies_list[-4][key])
    return return_state


def lambd_NH3_OH_CB89(T, P):
    """n-a: ammonia hydroxide [CB89]."""
    lambd = 0.103
    valid = T == 298.15
    return lambd, valid


def has_active_relation(model_instance):
    """
    Returns True if at least one other model instance has a relationship with this instance
    Intended to be used to determine if this object can safely be deleted without any consequential cascade deletions
    Customised version of https://stackoverflow.com/questions/26659023/deletion-objects-that-is-used-as-foreign-key and https://gist.github.com/vonorm/8617378
    """
    for field in model_instance._meta.get_fields():
        if field.related_model:
            related = field.related_model.objects.filter(**{field.field.
                name: model_instance})[:1].values_list('pk', flat=True)
            if len(related) > 0:
                return True
    return False


@classmethod
def block_header(cls, block, height):
    """Returns the block header given a block and its height."""
    return block[:cls.static_header_len(height)]


def _parse_percentage(val):
    """
    Convert a percentage string into a Python float.
    The percent sign at the end is optional::

    >>> _parse_percentage('10')
    10.0
    >>> _parse_percentage('10%')
    10.0
    >>> _parse_percentage('0.25%')
    0.25
    """
    return float(val[:-1]) if val.endswith('%') else float(val)


def autoCert(cn, caName, name):
    """Create a certificate signed by caName for cn into name."""
    import ca
    cac, cak = ca.loadOrDie(caName)
    c, k = ca.makeCert(cn, ca=cac, cak=cak)
    ca.saveOrDie(c, k, name)


@staticmethod
def p_attribute_value_type(p):
    """attribute_value_type : attribute_value_type_int
                                | attribute_value_type_hex
                                | attribute_value_type_float
                                | attribute_value_type_string
                                | attribute_value_type_enum"""
    p[0] = p[1]


@classmethod
def get_instance(cls):
    """ Singleton getter """
    return cls._instance


@classmethod
def from_name(cls, name: str, *args, **kwargs):
    """
        Creates a new Block from the format: ``namespace:block_id``

        Parameters
        ----------
        name
            Block in said format
        , args, kwargs
            Will be passed on to the main constructor
        """
    namespace, block_id = name.split(':')
    return cls(namespace, block_id, *args, **kwargs)


def _doNothing(canvas, doc):
    """Dummy callback for onPage"""
    pass


def jaccard_distance(set1, set2):
    """Calculate Jaccard distance between two sets.

    Parameters
    ----------
    set1 : set
        Input set.
    set2 : set
        Input set.

    Returns
    -------
    float
        Jaccard distance between `set1` and `set2`.
        Value in range `[0, 1]`, where 0 is min distance (max similarity) and 1 is max distance (min similarity).
    """
    union_cardinality = len(set1 | set2)
    if union_cardinality == 0:
        return 1.0
    return 1.0 - float(len(set1 & set2)) / float(union_cardinality)