def mean(data):
    """Returns the mean of data.

    Notes
    -----
    The function ignores all non-numerical elements in the data and returns
    None if no numerical element has been found. In contrast to standard math
    and numpy functions, this function is robust against type violations.

    Parameters
    ----------
    data : list
        list of numerical data

    Returns
    -------
    out : float or None

    """
    s = 0
    cnt = 0
    for v in data:
        try:
            s += v
            cnt += 1
        except:
            pass
    if cnt == 0:
        return None
    else:
        return float(s) / float(cnt)


def absolute_date(resolution, start, end, last_seen=False):
    """Select an absolute date range for a location selector.

    :keyword resolution: Time resolution specifier, e.g. ``hours`` or ``days``.
    :keyword start: UTC start time in ISO 8601 format.
    :keyword end: UTC end time in ISO 8601 format.
    :keyword last_seen: Select only devices last seen in this location.
        Defaults to False.

    >>> from pprint import pprint
    >>> d = absolute_date(resolution='months', start='2013-01', end='2013-06')
    >>> pprint(d)
    {'months': {'end': '2013-06', 'start': '2013-01'}}
    >>> d = absolute_date(resolution='minutes', start='2012-01-01 12:00',
    ...         end='2012-01-01 12:45', last_seen=True)
    >>> pprint(d, width=76)
    {'last_seen': True,
     'minutes': {'end': '2012-01-01 12:45', 'start': '2012-01-01 12:00'}}

    """
    if resolution not in 'minuteshoursdaysweeksmonthsyears':
        raise ValueError('Invalid date resolution: %s' % resolution)
    payload = {resolution: {'start': start, 'end': end}}
    if last_seen:
        payload['last_seen'] = True
    return payload


def seq_for_table_attr(table, attribute, offset, seq_for, table_config):
    """Generate or update sequence numbers for each attribute that has a sequence

    >>> table_config = {'calls': {'attrs': {'id': {'seq': {'start': 300}}}}}
    >>> seq_for_table_attr('calls', 'id', 200, {}, table_config)
    (500, {'calls': {'id': 300}})
    >>> seq_for_table_attr('calls', 'id', 400, {'calls': {'id': 630}}, table_config)
    (1031, {'calls': {'id': 631}})
    """
    if seq_for == {}:
        for t in table_config:
            seq_for[t] = {}
    if seq_for[table].get(attribute):
        seq_for[table][attribute] = seq_for[table][attribute] + 1
    else:
        start = table_config[table]['attrs'][attribute]['seq']['start']
        seq_for[table][attribute] = start
    result_without_offset = seq_for[table][attribute]
    result_with_offset = result_without_offset + offset
    return result_with_offset, seq_for


def nonce(request):
    """ Pass the nonce cases to their respective template calls.

    Args:
        request (:obj:) Django request object

    Returns:
        bool: False in template if settings are not activated
        dict:
            script_nonce (str): Cryptographic nonce for use in <script> tags.
            style_nonce (str): Cryptographic nonce for use in <style> tags.

    """
    script = getattr(request, 'script_nonce', False)
    style = getattr(request, 'style_nonce', False)
    return {'script_nonce': 'nonce={}'.format(script), 'style_nonce':
        'nonce={}'.format(style)}


def naive_log_ctz(x: int) ->int:
    """Count trailing zeros, in a O(log(zeros)) steps.

    Args:
        x: An int.

    Returns:
        The number of trailing zeros in x, as an int.

    This implementation is much faster than the naive linear implementation,
    as it performs a logarithmic number of steps relative to the number of
    trailing zeros in x. Unlike the linear implementation, this one avoids
    looking at the high bits of x if it can, so it only returns the number
    of zeros, not the remaining significant bits of x.

    We still say this implementation is "naive" because it does not try
    to use any specific optimization tricks besides the logarithmic algorithm.

    >>> naive_log_ctz(0)
    0
    >>> naive_log_ctz(1)
    0
    >>> naive_log_ctz(-1)
    0
    >>> naive_log_ctz(2)
    1
    >>> naive_log_ctz(-2)
    1
    >>> naive_log_ctz(40) # 0b101000 = 2**3 * 5
    3
    >>> naive_log_ctz(-40) # 0b1..1011000
    3
    >>> naive_log_ctz(37 << 100)
    100

    # Of course the behavior should match for all integers...
    >>> all(naive_ctz2(x)[0] == naive_log_ctz(x) for x in range(1024))
    True
    """
    if x == 0:
        return 0
    else:
        zmask = 1
        zscale = 1
        low_bits = x & zmask
        while low_bits == 0:
            zmask = zmask << zscale | zmask
            zscale <<= 1
            low_bits = x & zmask
        zscale >>= 1
        zmask >>= zscale
        zeros: int = 0
        while zscale > 0:
            if low_bits & zmask == 0:
                low_bits >>= zscale
                zeros += zscale
            zscale >>= 1
            zmask >>= zscale
        return zeros


def rshift(val, n):
    """python port for '>>>'(right shift with padding)
    """
    return val % 4294967296 >> n


def sqrt(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise square-root value of the input.

    .. math::
       \\textrm{sqrt}(x) = \\sqrt{x}

    Example::

       sqrt([4, 9, 16]) = [2, 3, 4]

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

       - sqrt(default) = default
       - sqrt(row_sparse) = row_sparse
       - sqrt(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L142

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

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

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


def list_logfile(flist):
    """ this read from file list of instances from download log file and return the ones matching constraints """
    keys = ['variable', 'mip', 'model', 'experiment', 'ensemble', 'realm',
        'version', 'dataset_id', 'path', 'cks_type', 'files']
    file_keys = ['filename', 'tracking_id', 'checksum']
    f = open(flist, 'r')
    inst_list = []
    file_list = []
    lines = f.readlines()
    values = lines[0].replace('\n', '').split(',')
    ds_dict = dict(zip(keys[:-1], values))
    for line in lines[1:]:
        values = line.replace('\n', '').split(',')
        if len(values) < 5:
            file_list.append(dict(zip(file_keys, values)))
        else:
            ds_dict['files'] = file_list
            inst_list.append(ds_dict)
            file_list = []
            ds_dict = dict(zip(keys[:-1], values))
    ds_dict['files'] = file_list
    inst_list.append(ds_dict)
    f.close()
    return inst_list


@staticmethod
def _sort_interactions(all_interactions):
    """
        Returns keys in interactions sorted by (number_of_atoms, name). Keys
        with no interactions are skipped.
        """
    sort_keys = {}
    for interaction_type, interactions in all_interactions.items():
        if not interactions:
            continue
        sort_keys[interaction_type] = len(interactions[0].atoms
            ), interaction_type
    return sorted(sort_keys, key=lambda k: sort_keys[k])


def get_max_strand(filter_id, dat_fwd, dat_rc):
    """Get max motif activation data over both strands"""
    for seq_id in range(dat_fwd[0].shape[0]):
        if dat_fwd[0][seq_id, filter_id] >= dat_rc[0][seq_id, filter_id]:
            dat_rc[0][seq_id, filter_id] = 0.0
        else:
            dat_fwd[0][seq_id, filter_id] = 0.0


@classmethod
def requestMemoryDump(cls):
    """Request a global memory dump.
        """
    return cls.build_send_payload('requestMemoryDump', {}
        ), cls.convert_payload({'dumpGuid': {'class': str, 'optional':
        False}, 'success': {'class': bool, 'optional': False}})


def _while_loop(*data, **kwargs):
    """Run a while loop over with user-defined condition and computation

    From:src/operator/control_flow.cc:1151

    Parameters
    ----------
    cond : Symbol
        Input graph for the loop condition.
    func : Symbol
        Input graph for the loop body.
    data : NDArray[]
        The input arrays that include data arrays and states.
    num_outputs : int, required
        The number of outputs of the subgraph.
    num_out_data : int, required
        The number of outputs from the function body.
    max_iterations : int, required
        Maximum number of iterations.
    cond_input_locs : tuple of <long>, required
        The locations of cond's inputs in the given inputs.
    func_input_locs : tuple of <long>, required
        The locations of func's inputs in the given inputs.
    func_var_locs : tuple of <long>, required
        The locations of loop_vars among func's inputs.

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

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


def set_bs4_parser(parser: str) ->None:
    """
    Sets the parser used by BeautifulSoup

    :param parser: BeautifulSoup parser
    :return: None
    """
    if parser:
        global bs4_parser
        bs4_parser = parser


def compose(s1, s2):
    """Construct a value of Compose value type.

    s1, s2 -- serialised form of a property value

    (This is only needed if the type of the first value permits colons.)

    """
    return s1.replace(b':', b'\\:') + b':' + s2


def is_stage_validated(stage: dict) ->bool:
    """
    Check if stage has special validation key
    and is validated.
    """
    for key in stage.keys():
        if key == 'validation' and stage['validation']['validation'
            ] == 'valid':
            return True
    return False


def _listify(data, key_name):
    """recast data from dict to list, compress keys into sub-dict

    Args:
        data (:obj:`dict`): data to transform (dict(dict))
        key_name (str): name to recast key to

    Returns:
        (:obj:`list`): fixed data

    """
    listified_data = []
    for key, value in data.items():
        row = dict(value)
        row[key_name] = key
        listified_data.append(row)
    return listified_data


@classmethod
def remove_field(cls, field):
    """Remove the given field and and update the slots cache"""
    with cls._fields_lock:
        cls.FIELDS = list(cls.FIELDS)
        cls.FIELDS.remove(field)


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


@classmethod
def _from_sequence(cls, scalars, dtype=None, copy=False):
    """Construct a new ExtensionArray from a sequence of scalars."""
    return cls(scalars)


def calculate_per_unit_commission(order, transaction, cost_per_unit,
    initial_commission, min_trade_cost):
    """
    If there is a minimum commission:
        If the order hasn't had a commission paid yet, pay the minimum
        commission.

        If the order has paid a commission, start paying additional
        commission once the minimum commission has been reached.

    If there is no minimum commission:
        Pay commission based on number of units in the transaction.
    """
    additional_commission = abs(transaction.amount * cost_per_unit)
    if order.commission == 0:
        return max(min_trade_cost, additional_commission + initial_commission)
    else:
        per_unit_total = abs(order.filled * cost_per_unit
            ) + additional_commission + initial_commission
        if per_unit_total < min_trade_cost:
            return 0
        else:
            return per_unit_total - order.commission


def cbrt(data=None, name=None, attr=None, out=None, **kwargs):
    """Returns element-wise cube-root value of the input.

    .. math::
       cbrt(x) = \\sqrt[3]{x}

    Example::

       cbrt([1, 8, -125]) = [1, 2, -5]

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

       - cbrt(default) = default
       - cbrt(row_sparse) = row_sparse
       - cbrt(csr) = csr

    Defined in src/operator/tensor/elemwise_unary_op_pow.cc:L216

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

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

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


@classmethod
def validate(cls, value: str) ->None:
    """Value validation method.

    Valid values are ``INCREASE`` and ``DECREASE``.

    Args:
      value (str): The value to validate.

    Raises:
      ValueError: Raises ValueError if an invalid value has been specified.
    """
    super().validate(value)
    if value not in ['INCREASE', 'DECREASE']:
        raise ValueError()


@staticmethod
def change_contact_modhattr(contact, value):
    """Change contact modified host attribute value
        Format of the line that triggers function call::

        CHANGE_CONTACT_MODHATTR;<contact_name>;<value>

        :param contact: contact to edit
        :type contact: alignak.objects.contact.Contact
        :param value: new value to set
        :type value:str
        :return: None
        """
    contact.modified_host_attributes = int(value)


@staticmethod
def pt_to_mm(measure):
    """Convert points to millimeters."""
    return measure * 0.352778


def post_process_request(req, template, data, metadata=None, method=None):
    """Do any post-processing the request might need

        This typically means adding values to the template `data`
        dictionary, or changing the Jinja2 template.

        `data` and `metdata` may be updated in place.

        Always returns a tuple of ``(template, data)`` or ``(template,
        data, metadata)``, even if unchanged.

        Be aware that returning a ``(template, data, None)`` triple
        will be interpreted as using the legacy API and will indicate
        that the template is a legacy Genshi template. The same will
        happen if the third value of the tuple is a string.

        The `method` last parameter is deprecated and is now supposed
        to be passed as `'method'` in the `metadata` dict. Even
        better, use directly the `'text'` indication (`True` or
        `False`).

        Note that `template`, `data`, `content_type` will be `None` if:
         - called when processing an error page
         - the default request handler did not return any result

        :Since 1.0: Clearsilver templates are no longer supported.

        :Since 1.1.2: the rendering `method` will be passed if it is returned
           by the request handler, otherwise `method` will be `None`. For
           backward compatibility, the parameter is optional in the
           implementation's signature.

        :Since 1.3.2: Genshi templates are still supported, and if
           `process_request` used the old API (`(template, data,
           content_type)`), the `metadata` parameter passed to
           `post_process_request` will actually be the `content_type`
           value (`String` or `None`).  This support for the old API
           will be removed in Trac 1.5.1, in which `metadata` will
           always be a `dict` or `None`.

        """


@classmethod
def get_all_field_names_verbose(cls):
    """
        Obtiene los nombres de los campos de un modelo dado
        :return:
        """
    fields = {}
    for f in cls._meta.get_fields():
        if hasattr(f, 'verbose_name'):
            fields[f.name] = '{} ({})'.format(f.verbose_name, cls._meta.
                verbose_name.title())
    return fields


def ip_for_request(request):
    """
    Returns ip address for request - first checks ``HTTP_X_FORWARDED_FOR``
    header, since app will generally be behind a public web server.
    """
    meta = request.META
    return meta.get('HTTP_X_FORWARDED_FOR', meta['REMOTE_ADDR']).split(',')[0]


def get_loggable_url(url):
    """Strip out secrets from taskcluster urls.

    Args:
        url (str): the url to strip

    Returns:
        str: the loggable url

    """
    loggable_url = url or ''
    for secret_string in ('bewit=', 'AWSAccessKeyId=', 'access_token='):
        parts = loggable_url.split(secret_string)
        loggable_url = parts[0]
    if loggable_url != url:
        loggable_url = '{}<snip>'.format(loggable_url)
    return loggable_url


def norm_float(value):
    """Converts a float (whose decimal part is zero) to integer"""
    if isinstance(value, float) and value.is_integer():
        return int(value)
    return value


def shift_hue(image, hue):
    """
    Shifts the hue of an image in HSV format.
    :param image: PIL Image to perform operation on
    :param hue: value between 0 and 2.0
    """
    hue = (hue - 1.0) * 180
    img = image.copy().convert('HSV')
    pixels = img.load()
    for i in range(img.width):
        for j in range(img.height):
            h, s, v = pixels[i, j]
            h = abs(int(h + hue))
            if h > 255:
                h -= 255
            pixels[i, j] = h, s, v
    return img.convert('RGBA')


def doWrite():
    """
        Some data can be written to your descriptor.

        @return: If an error is encountered which causes the descriptor to
            no longer be valid, a L{Failure} should be returned.  Otherwise,
            L{None}.
        """


def remove():
    """Delete current cache

    """
    pass


def first_true(pred, iterable, default=None):
    """Returns the first true value in the iterable.

    If no true value is found, returns *default*

    source: https://docs.python.org/3/library/itertools.html
    """
    return next(filter(pred, iterable), default)


def roundaggmip(a):
    """Reasonably round aggregated MIP results for printing."""
    return a.round({'ub_mean': 6, 'ub_sd': 6, 'lb_mean': 6, 'lb_sd': 6,
        'ttot_med': 1, 'gap_mean': 1})


def isinstance_str(inv, cls):
    """
    checks if an object is of a certain type by looking at the class name (not the class object)
    This is useful to circumvent the need to load import Python modules.

    :param inv: object of which to check the class

    :param cls: string or list of string with the name of the class(es) to be checked

    :return: True/False
    """
    if isinstance(cls, str):
        cls = [cls]
    if hasattr(inv, '__class__') and hasattr(inv.__class__, '__name__'
        ) and inv.__class__.__name__ in cls:
        return True
    return False


def getGatkContigCheckString():
    """ For Gatk contig style wrappers. Will create a bash sctring to
    determine if the contig is 'unmapped' and if so will set the contig
    param accordingly """
    return """# Check for the unmapped as the contig
# If not, write no_mapped_reads to outBam
if [ "$contig" == "unmapped" ]; then
	contigParam=""
else
	contigParam="-L $contig"
fi

"""


@classmethod
def get_ewald_energy(cls, calc, **kwargs):
    """Return Ewald energy in eV."""
    return cls._get_pw_energy_value(calc, 'energy_ewald')


def click_insert(frame: float=1.0, value: float=1.0, extend: bool=False):
    """Insert new keyframe at the cursor position for the active F-Curve

    :param frame: Frame Number, Frame to insert keyframe on
    :type frame: float
    :param value: Value, Value for keyframe on
    :type value: float
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def get_valid_language(record, field):
    """
    Takes languages codes and returns the first in a valid form.
    """
    languages = record.field(field, alt='')
    if '$$' in languages:
        languages = languages.split('$$')
    elif ';' in languages:
        languages = languages.split(' ; ')
    else:
        languages = languages.split('$')
    return languages[0]


def crossfade_sounds():
    """Do cross-fading volume animation of two selected sound strips

    """
    pass


def removeReliableListener(listener):
    """
        Remove a previously added listener.
        """


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = '$Format:%d$'
    git_full = '$Format:%H$'
    git_date = '$Format:%ci$'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def change_frame(frame: int=0):
    """Interactively change the current frame number

    :param frame: Frame
    :type frame: int
    """
    pass


def make_filter(shape):
    """Create a mapping, which can be used to identify documents with the
    specified shape."""
    return {'shape_id': shape.id}


@staticmethod
def process_sink_covariates(covariates):
    """Process sink covariates before saving them.

        This method is applied to the sink covariates before they are saved.
        The method can be used to compute derived covariates

        Parameters
        ----------
        covariates : float[]
            Covariates describing the attractiveness of sinks

        """
    return covariates


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


@staticmethod
def __check_config(config):
    """Check whether the configuration information is valid.

        :param config: The configuration information, including 11 configuration fields.
        :return: None.
        """
    keys = ['capacity', 'state_dim', 'action_dim', 'nodes', 'connections',
        'depths', 'batch_size', 'memory']
    for item in keys:
        if item not in config:
            raise Exception('Invalid configuration.')
    if 'evolution' not in config:
        config['evolution'] = 0
    if 'verbose' not in config:
        config['verbose'] = False
    if 'gamma' not in config:
        config['gamma'] = 0.9


def get_keywords():
    """Get the keywords needed to look up the version information."""
    git_refnames = ' (HEAD -> master, tag: v0.9.1)'
    git_full = 'f793fe95a4666f2ffcde02c38b7ef82105dd329d'
    git_date = '2019-05-21 08:38:06 +0100'
    keywords = {'refnames': git_refnames, 'full': git_full, 'date': git_date}
    return keywords


def add_keys(apps, schema_editor):
    """
    We can't import the Post model directly as it may be a newer
    version than this migration expects. We use the historical version.
    """
    Setting = apps.get_model('settings', 'Setting')
    key = ''
    try:
        key = 'LOGO_PROJECT_ICON'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='لوگو', key=key, value=
            'https://cdn.aparnik.com/static/website/img/logo-persian.png',
            value_type='s', is_show=True, is_variable_in_home=True)
    try:
        key = 'SERVER_NAME'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='آدرس سایت', key=key, value=
            'api.aparnik.com', value_type='s', is_show=False,
            is_variable_in_home=False)
    try:
        key = 'SERVER_PORT'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='پورت سایت', key=key, value='80',
            value_type='s', is_show=False, is_variable_in_home=False)
    try:
        key = 'PRODUCT_WALLET_ID'
        Setting.objects.get(key=key)
    except Exception:
        Product = apps.get_model('products', 'Product')
        ContentType = apps.get_model('contenttypes', 'ContentType')
        product = Product.objects.create(price_fabric=1, title='شارژ کیف پول')
        new_ct = ContentType.objects.get_for_model(Product)
        Product.objects.filter(polymorphic_ctype__isnull=True).update(
            polymorphic_ctype=new_ct)
        Setting.objects.create(title='شارژ کیف پول', key=key, value=str(
            product.id), value_type='i', is_show=False, is_variable_in_home
            =False)
    try:
        key = 'COURSE_LEVEL'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='سطح دوره', key=key, value='2',
            value_type='i', is_show=False, is_variable_in_home=False)
    try:
        key = 'INVITER_GIFT_CREDITS_PER_PURCHASE'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title=
            'درصد اعتبار هدیه برای دعوت کننده به ازای هر خرید', key=key,
            value='0', value_type='i', is_show=False, is_variable_in_home=False
            )
    try:
        key = 'INVITER_GIFT_CREDITS'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title=
            'اعتبار هدیه برای دعوت کننده در بدو قبول دعوت تومان', key=key,
            value='0', value_type='i', is_show=False, is_variable_in_home=False
            )
    try:
        key = 'INVITED_GIFT_CREDITS'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title=
            'اعتبار هدیه برای دعوت شونده در بدو قبول دعوت تومان', key=key,
            value='0', value_type='i', is_show=False, is_variable_in_home=False
            )
    try:
        key = 'PRICE_FORMAT'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title=
            'اعتبار هدیه برای دعوت کننده در بدو قبول دعوت تومان', key=key,
            value='%ic=t:%se=,:%cu=t:%gr=3:%tr=True:%abbr=True', value_type
            ='s', is_show=False, is_variable_in_home=False)
    try:
        key = 'PRICE_PRODUCT_FREE_DESCRIPTION'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='عنوان کالاهای رایگان', key=key, value
            ='رایگان', value_type='s', is_show=False, is_variable_in_home=False
            )
    try:
        key = 'PRICE_PRODUCT_SHARING_DESCRIPTION'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='عنوان کالاهایی که دعوت شده اند', key=
            key, value='دعوت شده', value_type='s', is_show=False,
            is_variable_in_home=False)
    try:
        key = 'PRICE_PRODUCT_BUY_DESCRIPTION'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='عنوان کالاهای خریداری شده', key=key,
            value='خریداری شده', value_type='s', is_show=False,
            is_variable_in_home=False)
    try:
        key = 'AWS_ACTIVE'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='آمازون', key=key, value='AWS_ACTIVE',
            value_type='fr', is_show=False, is_variable_in_home=True)
    try:
        key = 'USER_LOGIN_WITH_PASSWORD'
        Setting.objects.get(key=key)
    except Exception:
        Setting.objects.create(title='ورود با رمز عبور', key=key, value=
            'USER_LOGIN_WITH_PASSWORD', value_type='fr', is_show=False,
            is_variable_in_home=True)


def int_to_bin_str(value, max_bits=8192):
    """Convert an int to a string representation of a bitmask (binary number)"""
    mask = value
    bits = 1
    while 1 << bits < value or bits < 16 and bits < max_bits:
        bits *= 2
    rep = ''
    while bits:
        rep = ('1' if mask & 1 else '0') + rep
        bits = bits - 1
        mask = mask >> 1
    return '0b' + rep


@classmethod
def IsConnected(cls, request):
    """The connection status is determined by the session cookie."""
    connection_cookie = request.cookie(cls.COOKIE_CONNECTION)
    if connection_cookie and len(connection_cookie) > 64:
        connection_cookie = connection_cookie[:64]
        return connection_cookie == cls.CreateSessionCookie(request)[:64]
    else:
        return False


def _verify_token_binding_id(client_data):
    """The tokenBinding member contains information about the state of the
    Token Binding protocol used when communicating with the Relying Party.
    The status member is one of:

        not-supported: when the client does not support token binding.

            supported: the client supports token binding, but it was not
                       negotiated when communicating with the Relying
                       Party.

              present: token binding was used when communicating with the
                       Relying Party. In this case, the id member MUST be
                       present and MUST be a base64url encoding of the
                       Token Binding ID that was used.
    """
    token_binding_status = client_data['tokenBinding']['status']
    token_binding_id = client_data['tokenBinding'].get('id', '')
    if token_binding_status in ('supported', 'not-supported'):
        return True
    return False


def replace_list(s, character_list, replace_char):
    """ should work with CaseInsensitiveString also and replace replace_list_insensitive"""
    for find_char in character_list:
        s = s.replace(find_char, replace_char)
    return s


def isunauthenticated(func):
    """Checks if the function does not require authentication.

    Mark such functions with the `@unauthenticated` decorator.

    :returns: bool
    """
    return getattr(func, 'unauthenticated', False)


def sign(x):
    """
    Returns 1 or -1 depending on the sign of x
    """
    if x >= 0:
        return 1
    else:
        return -1


def getAvailableCountries():
    """
        Return a sequence or view of unicode country tags for available
        countries.
        """


def parse_size(s):
    """
    s: <number>[<k|m|g|t>]
    Returns the number of bytes.
    """
    try:
        if s[-1].isdigit():
            return int(s)
        n, unit = float(s[0:-1]), s[-1].lower()
        if unit == 'k':
            return int(n * 1024)
        if unit == 'm':
            return int(n * 1024 * 1024)
        if unit == 'g':
            return int(n * 1024 * 1024 * 1024)
        if unit == 't':
            return int(n * 1024 * 1024 * 1024 * 1024)
    except (IndexError, ValueError):
        pass
    raise ValueError('Invalid size: %s, expected <number>[<k|m|g|t>]' % s)


def code_to_line(code, cursor_pos):
    """Turn a multiline code block and cursor position into a single line
    and new cursor position.

    For adapting ``complete_`` and ``object_info_request``.
    """
    if not code:
        return '', 0
    for line in code.splitlines(True):
        n = len(line)
        if cursor_pos > n:
            cursor_pos -= n
        else:
            break
    return line, cursor_pos


@classmethod
def from_text(cls, data):
    """Construct an instance from text format.

        Parameters
        ----------
            data : Sequence[str]
                list of texts as ``item_class.from_text`` input.
        """
    return cls(map(cls._item_from_text, data))


def apply_masks(time, flux, flux_err, transit_masks):
    """
    Apply transit masks to the unflattened light curve.

    Args:
        time (array): The time array.
        flux (array): The flux array
        flux_err (array): The flux_err array.
        transit_masks (list): A list of transit masks.

    Returns:
        masked_time (array): The masked time array.
        masked_flux (array): The masked flux array.
        masked_flux_err (array): The masked flux_err array.

    """
    masked_time = time * 1
    masked_flux, masked_flux_err = flux * 1, flux_err * 1
    for i in range(len(transit_masks)):
        masked_time = masked_time[~transit_masks[i]]
        masked_flux = masked_flux[~transit_masks[i]]
        masked_flux_err = masked_flux_err[~transit_masks[i]]
    return masked_time, masked_flux, masked_flux_err


def reset_next_msg_id(msg_id: int):
    """Only used for unittest

    :param msg_id:
    :return:
    """
    global _next_msg_id
    _next_msg_id = msg_id


def _source(name, field):
    """Translate field name to instance source name with respect to source=*.

    .. deprecated::
        This function will be removed in 1.0.0.
    """
    if field.source == '*':
        return name
    else:
        return field.source or name


def _check_histories(history1, history2):
    """Check if two histories are the same."""
    if history1.replace('\n', '').replace(' ', '') == history2.replace('\n', ''
        ).replace(' ', ''):
        return True
    else:
        return False


def read_vx(pointdata):
    """Read a variable-length index."""
    if pointdata[0] != 255:
        index = pointdata[0] * 256 + pointdata[1]
        size = 2
    else:
        index = pointdata[1] * 65536 + pointdata[2] * 256 + pointdata[3]
        size = 4
    return index, size


def start_on_demand_replication_run(replicationJobId=None, description=None):
    """
    The StartOnDemandReplicationRun API is used to start a ReplicationRun on demand (in addition to those that are scheduled based on your frequency). This ReplicationRun will start immediately. StartOnDemandReplicationRun is subject to limits on how many on demand ReplicationRuns you may call per 24-hour period.
    See also: AWS API Documentation

    :example: response = client.start_on_demand_replication_run(
        replicationJobId='string',
        description='string'
    )

    :type replicationJobId: string
    :param replicationJobId: [REQUIRED] The unique identifier for a Replication Job.

    :type description: string
    :param description: The description for a Replication Job/Run.

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

    :returns:
    (dict) --
    replicationRunId (string) -- The unique identifier for a Replication Run.

    """
    pass


@staticmethod
def get_steps_num():
    """Return number of algorithm steps if your algorithm report progress, else should return 0"""
    return 0


def chunks(iterable, size=50):
    """Break an iterable into lists of size"""
    batch = []
    for n in iterable:
        batch.append(n)
        if len(batch) % size == 0:
            yield batch
            batch = []
    if batch:
        yield batch


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

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


def graph_select_box(xmin: int=0, xmax: int=0, ymin: int=0, ymax: int=0,
    wait_for_input: bool=True, deselect: bool=False, extend: bool=True):
    """Select curve points using box selection

    :param xmin: X Min
    :type xmin: int
    :param xmax: X Max
    :type xmax: int
    :param ymin: Y Min
    :type ymin: int
    :param ymax: Y Max
    :type ymax: int
    :param wait_for_input: Wait for Input
    :type wait_for_input: bool
    :param deselect: Deselect, Deselect rather than select items
    :type deselect: bool
    :param extend: Extend, Extend selection instead of deselecting everything first
    :type extend: bool
    """
    pass


def sync_seller_v2_stats_report(config, state, stream, sdk_client, token):
    """Sync a stream which is backed by the Criteo SellerV2Stats endpoint."""
    pass


def get_exception_info(exception):
    """
    Format exception information for display on the debug page using the
    structure described in the template API documentation.
    """
    context_lines = 10
    lineno = exception.lineno
    lines = list(enumerate(exception.source.strip().split('\n'), start=1))
    during = lines[lineno - 1][1]
    total = len(lines)
    top = max(0, lineno - context_lines - 1)
    bottom = min(total, lineno + context_lines)
    return {'name': exception.filename, 'message': exception.message,
        'source_lines': lines[top:bottom], 'line': lineno, 'before': '',
        'during': during, 'after': '', 'total': total, 'top': top, 'bottom':
        bottom}


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

    The storage type of ``arccosh`` output is always dense

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

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

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

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


def blend(img_under, img_over, img_alpha):
    """
    Blend together two images using an alpha channel image

    Parameters:

    - img_under -- The base image (underneath the overlay)
    - img_over  -- The overlay image
    - img_alpha -- Transparency/alpha value to use when blending
    """
    return img_under * (1 - img_alpha[:, :, (None)]) + img_over * img_alpha[:,
        :, (None)]


@classmethod
def _getKind(cls):
    """Return an human readable kind of ROI

        :rtype: str
        """
    return cls._kind


def _get_all_gnupg_options():
    """Get all GnuPG options and flags.

    This is hardcoded within a local scope to reduce the chance of a tampered
    GnuPG binary reporting falsified option sets, i.e. because certain options
    (namedly the ``--no-options`` option, which prevents the usage of gpg.conf
    files) are necessary and statically specified in
    :meth:`gnupg._meta.GPGBase._make_args`, if the inputs into Python are
    already controlled, and we were to summon the GnuPG binary to ask it for
    its options, it would be possible to receive a falsified options set
    missing the ``--no-options`` option in response. This seems unlikely, and
    the method is stupid and ugly, but at least we'll never have to debug
    whether or not an option *actually* disappeared in a different GnuPG
    version, or some funny business is happening.

    These are the options as of GnuPG 1.4.12; the current stable branch of the
    2.1.x tree contains a few more -- if you need them you'll have to add them
    in here.

    :type gnupg_options: frozenset
    :ivar gnupg_options: All known GPG options and flags.
    :rtype: frozenset
    :returns: ``gnupg_options``
    """
    three_hundred_eighteen = (
        """
--allow-freeform-uid              --multifile
--allow-multiple-messages         --no
--allow-multisig-verification     --no-allow-freeform-uid
--allow-non-selfsigned-uid        --no-allow-multiple-messages
--allow-secret-key-import         --no-allow-non-selfsigned-uid
--always-trust                    --no-armor
--armor                           --no-armour
--armour                          --no-ask-cert-expire
--ask-cert-expire                 --no-ask-cert-level
--ask-cert-level                  --no-ask-sig-expire
--ask-sig-expire                  --no-auto-check-trustdb
--attribute-fd                    --no-auto-key-locate
--attribute-file                  --no-auto-key-retrieve
--auto-check-trustdb              --no-batch
--auto-key-locate                 --no-comments
--auto-key-retrieve               --no-default-keyring
--batch                           --no-default-recipient
--bzip2-compress-level            --no-disable-mdc
--bzip2-decompress-lowmem         --no-emit-version
--card-edit                       --no-encrypt-to
--card-status                     --no-escape-from-lines
--cert-digest-algo                --no-expensive-trust-checks
--cert-notation                   --no-expert
--cert-policy-url                 --no-force-mdc
--change-pin                      --no-force-v3-sigs
--charset                         --no-force-v4-certs
--check-sig                       --no-for-your-eyes-only
--check-sigs                      --no-greeting
--check-trustdb                   --no-groups
--cipher-algo                     --no-literal
--clearsign                       --no-mangle-dos-filenames
--command-fd                      --no-mdc-warning
--command-file                    --no-options
--comment                         --no-permission-warning
--completes-needed                --no-pgp2
--compress-algo                   --no-pgp6
--compression-algo                --no-pgp7
--compress-keys                   --no-pgp8
--compress-level                  --no-random-seed-file
--compress-sigs                   --no-require-backsigs
--ctapi-driver                    --no-require-cross-certification
--dearmor                         --no-require-secmem
--dearmour                        --no-rfc2440-text
--debug                           --no-secmem-warning
--debug-all                       --no-show-notation
--debug-ccid-driver               --no-show-photos
--debug-level                     --no-show-policy-url
--decrypt                         --no-sig-cache
--decrypt-files                   --no-sig-create-check
--default-cert-check-level        --no-sk-comments
--default-cert-expire             --no-strict
--default-cert-level              --notation-data
--default-comment                 --not-dash-escaped
--default-key                     --no-textmode
--default-keyserver-url           --no-throw-keyid
--default-preference-list         --no-throw-keyids
--default-recipient               --no-tty
--default-recipient-self          --no-use-agent
--default-sig-expire              --no-use-embedded-filename
--delete-keys                     --no-utf8-strings
--delete-secret-and-public-keys   --no-verbose
--delete-secret-keys              --no-version
--desig-revoke                    --openpgp
--detach-sign                     --options
--digest-algo                     --output
--disable-ccid                    --override-session-key
--disable-cipher-algo             --passphrase
--disable-dsa2                    --passphrase-fd
--disable-mdc                     --passphrase-file
--disable-pubkey-algo             --passphrase-repeat
--display                         --pcsc-driver
--display-charset                 --personal-cipher-preferences
--dry-run                         --personal-cipher-prefs
--dump-options                    --personal-compress-preferences
--edit-key                        --personal-compress-prefs
--emit-version                    --personal-digest-preferences
--enable-dsa2                     --personal-digest-prefs
--enable-progress-filter          --pgp2
--enable-special-filenames        --pgp6
--enarmor                         --pgp7
--enarmour                        --pgp8
--encrypt                         --photo-viewer
--encrypt-files                   --pipemode
--encrypt-to                      --preserve-permissions
--escape-from-lines               --primary-keyring
--exec-path                       --print-md
--exit-on-status-write-error      --print-mds
--expert                          --quick-random
--export                          --quiet
--export-options                  --reader-port
--export-ownertrust               --rebuild-keydb-caches
--export-secret-keys              --recipient
--export-secret-subkeys           --recv-keys
--fast-import                     --refresh-keys
--fast-list-mode                  --remote-user
--fetch-keys                      --require-backsigs
--fingerprint                     --require-cross-certification
--fixed-list-mode                 --require-secmem
--fix-trustdb                     --rfc1991
--force-mdc                       --rfc2440
--force-ownertrust                --rfc2440-text
--force-v3-sigs                   --rfc4880
--force-v4-certs                  --run-as-shm-coprocess
--for-your-eyes-only              --s2k-cipher-algo
--gen-key                         --s2k-count
--gen-prime                       --s2k-digest-algo
--gen-random                      --s2k-mode
--gen-revoke                      --search-keys
--gnupg                           --secret-keyring
--gpg-agent-info                  --send-keys
--gpgconf-list                    --set-filename
--gpgconf-test                    --set-filesize
--group                           --set-notation
--help                            --set-policy-url
--hidden-encrypt-to               --show-keyring
--hidden-recipient                --show-notation
--homedir                         --show-photos
--honor-http-proxy                --show-policy-url
--ignore-crc-error                --show-session-key
--ignore-mdc-error                --sig-keyserver-url
--ignore-time-conflict            --sign
--ignore-valid-from               --sign-key
--import                          --sig-notation
--import-options                  --sign-with
--import-ownertrust               --sig-policy-url
--interactive                     --simple-sk-checksum
--keyid-format                    --sk-comments
--keyring                         --skip-verify
--keyserver                       --status-fd
--keyserver-options               --status-file
--lc-ctype                        --store
--lc-messages                     --strict
--limit-card-insert-tries         --symmetric
--list-config                     --temp-directory
--list-key                        --textmode
--list-keys                       --throw-keyid
--list-only                       --throw-keyids
--list-options                    --trustdb-name
--list-ownertrust                 --trusted-key
--list-packets                    --trust-model
--list-public-keys                --try-all-secrets
--list-secret-keys                --ttyname
--list-sig                        --ttytype
--list-sigs                       --ungroup
--list-trustdb                    --update-trustdb
--load-extension                  --use-agent
--local-user                      --use-embedded-filename
--lock-multiple                   --user
--lock-never                      --utf8-strings
--lock-once                       --verbose
--logger-fd                       --verify
--logger-file                     --verify-files
--lsign-key                       --verify-options
--mangle-dos-filenames            --version
--marginals-needed                --warranty
--max-cert-depth                  --with-colons
--max-output                      --with-fingerprint
--merge-only                      --with-key-data
--min-cert-level                  --yes
"""
        .split())
    three_hundred_eighteen.append('--export-ownertrust')
    three_hundred_eighteen.append('--import-ownertrust')
    three_hundred_eighteen.append('--pinentry-mode')
    three_hundred_eighteen.append('--allow-loopback-pinentry')
    gnupg_options = frozenset(three_hundred_eighteen)
    return gnupg_options


def publish_data(data):
    """publish a data_message on the IOPub channel

    Parameters
    ----------

    data : dict
        The data to be published. Think of it as a namespace.
    """
    from ipykernel.zmqshell import ZMQInteractiveShell
    ZMQInteractiveShell.instance().data_pub.publish_data(data)


def http_code_2_return_code(code):
    """Tranform http status code to system return code."""
    return (code - 301) % 255 + 1


def get_facts(device):
    """
    Doesn't get any facts.
    """
    return {}


@classmethod
def get(cls, pid, session):
    """Get an idle, unused connection from the pool. Once a connection has
        been retrieved, it will be marked as in-use until it is freed.

        :param str pid: The pool ID
        :param queries.Session session: The session to assign to the connection
        :rtype: psycopg2.extensions.connection

        """
    with cls._lock:
        cls._ensure_pool_exists(pid)
        return cls._pools[pid].get(session)


def basis_function_one(degree, knot_vector, span, knot):
    """ Computes the value of a basis function for a single parameter.

    Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller.

    :param degree: degree, :math:`p`
    :type degree: int
    :param knot_vector: knot vector
    :type knot_vector: list, tuple
    :param span: knot span, :math:`i`
    :type span: int
    :param knot: knot or parameter, :math:`u`
    :type knot: float
    :return: basis function, :math:`N_{i,p}`
    :rtype: float
    """
    if span == 0 and knot == knot_vector[0] or span == len(knot_vector
        ) - degree - 2 and knot == knot_vector[len(knot_vector) - 1]:
        return 1.0
    if knot < knot_vector[span] or knot >= knot_vector[span + degree + 1]:
        return 0.0
    N = [(0.0) for _ in range(degree + span + 1)]
    for j in range(0, degree + 1):
        if knot_vector[span + j] <= knot < knot_vector[span + j + 1]:
            N[j] = 1.0
    for k in range(1, degree + 1):
        saved = 0.0
        if N[0] != 0.0:
            saved = (knot - knot_vector[span]) * N[0] / (knot_vector[span +
                k] - knot_vector[span])
        for j in range(0, degree - k + 1):
            Uleft = knot_vector[span + j + 1]
            Uright = knot_vector[span + j + k + 1]
            if N[j + 1] == 0.0:
                N[j] = saved
                saved = 0.0
            else:
                temp = N[j + 1] / (Uright - Uleft)
                N[j] = saved + (Uright - knot) * temp
                saved = (knot - Uleft) * temp
    return N[0]


def validate_sam(path):
    """
    Validate SAM file

    Parameters
    ----------
    path : str
        File to check
    """
    raise NotImplementedError()


@classmethod
def cql_parameterized_type(cls):
    """
        There is no CQL notation for Composites, so we override this.
        """
    typestring = cls.cass_parameterized_type(full=True)
    return "'%s'" % (typestring,)


def name_generator(master_name, preset):
    """Generate the output name for slave file.

    :param master_name: string with the name of the master file.
    :param preset: dictionary with the preset information.
    :returns: string with the slave name for this preset.
    """
    return (
        '{master_name}-{video_bitrate}-kbps-{width}x{height}-audio-{audio_bitrate}-kbps-stereo.mp4'
        .format(master_name='master_name', **preset))


def isconsonant(char):
    """isconsonant(string) -> bool

    Returns true if string is a consonant.
    """
    if len(char) == 1 and char in 'ckgszjtdhfpbmyrwxnv':
        return True
    return False


def default_converter(o):
    """Implement this function such that it returns
    a serializable object for ``o`` or raises a ``TypeError``.

    For example, to support arbitrary iterators, you could
    implement default like this::

        def default(o):
            try:
                iterable = iter(o)
            except TypeError:
                pass
            else:
                return list(iterable)
            raise TypeError(repr(o) + " is not JSON serializable")

    """
    raise TypeError(repr(o) + ' is not PBJSON serializable')


def keep_arg(i, arg_name, typ):
    """
    Return whether `arg_name` should be included in the type annotation.

    Parameters
    ----------
    i : int
        position within the arg list

    arg_name : str
    typ : Optional[str]
        type of the arg

    Returns
    -------
    bool
    """
    return not (i == 0 and arg_name in {'self', 'cls'} and typ is None)


def set_default_connection(io_type, variant):
    """Set connection to use as default when requesting 'device' without connection specification"""
    global default_connection
    default_connection = {'io_type': io_type, 'variant': variant}


def add_missing_optional_args_with_value_none(args, optional_args):
    """
    Adds key-value pairs to the passed dictionary, so that
        afterwards, the dictionary can be used without needing
        to check for KeyErrors.

    If the keys passed as a second argument are not present,
        they are added with None as a value.

    :args: The dictionary to be completed.
    :optional_args: The keys that need to be added, if
        they are not present.
    :return: The modified dictionary.
    """
    for name in optional_args:
        if not name in args.keys():
            args[name] = None
    return args


def set_auth_credentials(auth_id=None, auth_token=None):
    """sets the auth_id and auth_token globally"""
    if auth_id is not None and auth_token is not None:
        global AUTH_ID
        global AUTH_TOKEN
        AUTH_ID = auth_id
        AUTH_TOKEN = auth_token
        return 0
    print('Function takes two arguments, auth_id and auth_token as strings')
    return None


def _convert_meth(fun):
    """hide obj-address from functions."""
    return 'meth: ', fun.__qualname__


@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 calculate_size():
    """ Calculates the request payload size"""
    data_size = 0
    return data_size


def rstrip_punctuation(value):
    """strip punctuation from the end of a label or title"""
    if not value:
        return value
    return value.rstrip('.:')


def get_stack_outputs(heat_cli, stack_id):
    """
    Returns a domain Stack object for a given ID
    :param heat_cli: the OpenStack heat client
    :param stack_id: the ID of the heat stack to retrieve
    :return: the Stack domain object else None
    """
    stack = heat_cli.stacks.get(stack_id)
    return stack.outputs


def human_m(v):
    """Returns a distance autoselected for mm, cm, m, and km
    """
    if v < 0.01:
        return v * 1000.0, 'mm'
    if v < 1:
        return v * 100.0, 'cm'
    if v < 1000:
        return v, 'm'
    return v / 1000.0, 'km'


def is_cover(set_of_sets, alphabet):
    """
    Determine whether `set_of_sets` is a cover of `alphabet`; that is,
    is every element of `alphabet` represented somewhere in `set_of_sets`?

    Parameters
    ----------
    set_of_sets : a (frozen)set of (frozen)sets
        The potential covering.
    alphabet : set
        The full alphabet.

    Returns
    -------
    cover : bool
        Whether set_of_sets is a cover or not.
    """
    return set().union(*set_of_sets) == set(alphabet)


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 cast_down(value):
    """Convert an object to an integer if no rounding is required.

    If the object is a float, which can be converted to an integer
    without rounding int(`value`) is returned. Otherwise `value` is returned.

    Args:
        value (object): An object to possibly converted

    Returns:
       (object or int) Either `value` or its integer representation.
    """
    return int(value) if isinstance(value, float) and int(value
        ) == value else value


def frange(start, stop=None, step=None):
    """Like xrange(), but returns list of floats instead
    All numbers are generated on-demand using generators
    """
    if stop is None:
        stop = float(start)
        start = 0.0
    if step is None:
        step = 1.0
    numiter = int((stop - start) / step)
    for i in range(numiter):
        yield start + step * i


def _parse_memory(s):
    """
    Parse a memory string in the format supported by Java (e.g. 1g, 200m) and
    return the value in MB

    >>> _parse_memory("256m")
    256
    >>> _parse_memory("2g")
    2048
    """
    units = {'g': 1024, 'm': 1, 't': 1 << 20, 'k': 1.0 / 1024}
    if s[-1].lower() not in units:
        raise ValueError('invalid format: ' + s)
    return int(float(s[:-1]) * units[s[-1].lower()])


def sanitize_labels(labels, number):
    """Sanitizes the labels for the channels of data sets such as signals, spectrums
    or filters:

    * the returned labels are stored in a tuple
    * the length of the tuple will be the same as the given number
    * for missing labels, empty strings are added
    * surplus labels are cropped

    :param labels: a possibly incomplete sequence of string labels or None to
                   generate a tuple of empty strings
    :param number: the desired length of the returned tuple, which should e.g.
                   be the number of channels of the signal or spectrum
    :returns: a tuple of string labels
    """
    if labels is None:
        return ('',) * number
    elif len(labels) < number:
        return tuple(labels) + ('',) * (number - len(labels))
    elif len(labels) > number:
        return tuple(labels[0:number])
    else:
        return tuple(labels)


@staticmethod
def result_sorter(result):
    """
        Method to sort the results for the refmap. Order:
        - CCode does not contain "x", "P", "p" (i.e. fragments on opposite strand or
        polymerase run-on fragments)
        - Exonic F1 (e_f1)
        - Junction F1 (j_f1)
        - "f" in ccode (i.e. transcript is a fusion)
        - Nucleotide F1 (n_f1)

        :param result: a resultStorer object
        :type result: ResultStorer
        :return: (int, float, float, float)
        """
    bad_ccodes = ['x', 'X', 'P', 'p']
    bad_ccodes = set(bad_ccodes)
    orderer = len(set.intersection(bad_ccodes, set(result.ccode))
        ) == 0, result.j_f1, result.e_f1, result.n_f1, 'f' in result.ccode
    return orderer


def get_journal_filename(response):
    """Extracts the name of the file submitted from the response"""
    return response['attachments'][0]['filename']


def square(x, y, size, name):
    """Draw square at `(x, y)` with side length `size` and fill color `name`.

    The square is oriented so the bottom left corner is at (x, y).

    """
    import turtle
    turtle.up()
    turtle.goto(x, y)
    turtle.down()
    turtle.color(name)
    turtle.begin_fill()
    for count in range(4):
        turtle.forward(size)
        turtle.left(90)
    turtle.end_fill()


def say_print(text: str, silent: bool, silent_text: str='Say: ') ->None:
    """
    Print text to say.
    :param text: str: Text to say.
    :param silent: bool: Silent status.
    :param silent_text: str:  (Default value = "Say: ")

    """
    if silent:
        silent_status = 'Silent: True'
    else:
        silent_status = 'Silent: False'
    print(f'{silent_text} ({silent_status}) > {text}')
    return None


def decrease_time_resolution_of_regular_cumulative_data(dict_info, start_lo,
    end_lo, time_delta_lo, time_delta_hi):
    """ Use the high resolution to create the low resolution """
    my_dt_lo = start_lo
    divisor, remainder = divmod(int(time_delta_lo.total_seconds()), int(
        time_delta_hi.total_seconds()))
    if remainder != 0:
        raise Exception(
            'Decrease Resolution: Time Deltas are not multiples of each other.'
            )
    elif divisor < 1:
        raise Exception(
            'Decrease Resolution: Low resolution lower than higher resolution {} < {}.'
            .format(time_delta_lo, time_delta_hi))
    new_dict_info = dict()
    while start_lo <= my_dt_lo and my_dt_lo <= end_lo:
        my_portion = 0.0
        for my_sub_step in range(0, -divisor, -1):
            my_portion += dict_info[my_dt_lo + my_sub_step * time_delta_hi]
        new_dict_info[my_dt_lo] = my_portion
        my_dt_lo += time_delta_lo
    return new_dict_info


def draw_strings(draw, instrument, image_height, palette):
    """Add the strings onto the image"""
    for string_num in list(range(instrument.number_of_strings)):
        string_pos_x = (string_num * instrument.string_spacing + instrument
            .first_string_gap + instrument.margin)
        string_pos_y = instrument.top_gap + instrument.nut_width
        draw.line((string_pos_x, string_pos_y, string_pos_x, image_height),
            palette.string_colour, width=instrument.string_width)
    return draw


def p_compound_stmt_1(p):
    """compound_stmt : if_stmt"""
    p[0] = [p[1]]


def _bs_classname(type_, context=None):
    """string formatting to make simple bootstrap classnames"""
    return '{}{}'.format(type_, ' {}-{}'.format(type_, context) if context
         is not None else '')


def fix_thinspaces(text):
    """
    Replaces thin spaces with non-breakable thin spaces
    """
    return text.replace('\u2009', '\u202f')


def correct_negative_bg(y_bg_rm, bg):
    """
    function to shift the bg and the y data with the bg removed up if there are negative values.
    :param y_bg_rm: the y data with bg removed
    :param bg: the bg as an np array
    :return:
    """
    y_min = y_bg_rm.min()
    if y_min < 0:
        y_bg_rm += abs(y_min)
        bg -= abs(y_min)
    return y_bg_rm, bg


def multiply_vectors_xy(u, v):
    """Element-wise multiplication of two vectors assumed to lie in the XY plane.

    Parameters
    ----------
    u : list
        The XY(Z) components of the first vector.
    v : list
        The XY(Z) components of the second vector.

    Returns
    -------
    list
        Resulting vector in the XY plane.

    Examples
    --------
    >>>

    """
    return [u[0] * v[0], u[1] * v[1], 0.0]


def find_dataset(dataset_id: str):
    """Find a dataset given its id"""
    from .definitions import DatasetDefinition
    return DatasetDefinition.find(dataset_id)


def display(cnpj):
    """
    Will format an adequately formatted numbers-only CNPJ string,
    adding in standard formatting visual aid symbols for display.
    """
    if not cnpj.isdigit() or len(cnpj) != 14 or len(set(cnpj)) == 1:
        return None
    return '{}.{}.{}/{}-{}'.format(cnpj[:2], cnpj[2:5], cnpj[5:8], cnpj[8:
        12], cnpj[12:])


def forward(apps, schema_editor):
    """
    corrects wrong openvpn "mode"
    TODO: delete this migration in future releases
    """
    if not schema_editor.connection.alias == 'default':
        return
    Config = apps.get_model('django_netjsonconfig', 'Config')
    Template = apps.get_model('django_netjsonconfig', 'Template')
    for model in [Config, Template]:
        for obj in model.objects.filter(config__contains='"openvpn"'):
            for v in obj.config['openvpn']:
                if 'mode' in v and v['mode'] == 'client':
                    v['mode'] = 'p2p'
            obj.save()


def type_to_str(type_object) ->str:
    """
    convert a type object to class path in str format
    :param type_object: type
    :return: class path
    """
    cls_name = str(type_object)
    assert cls_name.startswith("<class '"), 'illegal input'
    cls_name = cls_name[len("<class '"):]
    assert cls_name.endswith("'>"), 'illegal input'
    cls_name = cls_name[:-len("'>")]
    return cls_name


def rpr(s):
    """Create a representation of a Unicode string that can be used in both
    Python 2 and Python 3k, allowing for use of the u() function"""
    if s is None:
        return 'None'
    seen_unicode = False
    results = []
    for cc in s:
        ccn = ord(cc)
        if ccn >= 32 and ccn < 127:
            if cc == "'":
                results.append('\\')
                results.append(cc)
            elif cc == '\\':
                results.append('\\')
                results.append(cc)
            else:
                results.append(cc)
        else:
            seen_unicode = True
            if ccn <= 65535:
                results.append('\\u')
                results.append('%04x' % ccn)
            else:
                results.append('\\U')
                results.append('%08x' % ccn)
    result = "'" + ''.join(results) + "'"
    if seen_unicode:
        return 'u(' + result + ')'
    else:
        return result


def installResolver(resolver):
    """
        Set the internal resolver to use to for name lookups.

        @type resolver: An object implementing the L{IResolverSimple} interface
        @param resolver: The new resolver to use.

        @return: The previously installed resolver.
        """


def select_circle(x: int=0, y: int=0, radius: int=1, gesture_mode: int=0):
    """Select keyframe points using circle selection

    :param x: X
    :type x: int
    :param y: Y
    :type y: int
    :param radius: Radius
    :type radius: int
    :param gesture_mode: Event Type
    :type gesture_mode: int
    """
    pass


@staticmethod
def _decode(**fetches):
    """ Performs decoding on the output (value model)
            :param fetches: A dictionary of fetches from the model.
            :return: A dictionary of decoded results, including various keys for evaluation
        """
    if 'value_loss' not in fetches:
        return {}
    return {'value_loss': fetches['value_loss']}


def parse_string(element):
    """parser of vRa data of string type

    Args:
        element (dict): vRa data

    Returns:
        tuple: key,value of vRa data
    """
    return element['key'], element['value']['value']


def combine_bytes(bytearr):
    """Given some bytes, join them together to make one long binary

    (e.g. 00001000 00000000   ->    0000100000000000)

    :param bytearr:
    :return:
    """
    bytes_count = len(bytearr)
    result = 0
    for index, byt in enumerate(bytearr):
        offset_bytes = bytes_count - index - 1
        result += byt << 8 * offset_bytes
    return result


def GetGPXtreeDataNames(G2frame, dataTypes):
    """Finds all items in tree that match a 4 character prefix

    :param wx.Frame G2frame: Data tree frame object
    :param list dataTypes: Contains one or more data tree item types to be matched
      such as ['IMG '] or ['PWDR','HKLF']
    :returns: a list of tree item names for the matching items
    """
    names = []
    item, cookie = G2frame.GPXtree.GetFirstChild(G2frame.root)
    while item:
        name = G2frame.GPXtree.GetItemText(item)
        if name[:4] in dataTypes:
            names.append(name)
        item, cookie = G2frame.GPXtree.GetNextChild(G2frame.root, cookie)
    return names


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

        :param DomainVerificationAddDomainSuccessType val:
        :rtype: EventType
        """
    return cls('domain_verification_add_domain_success', val)


def implemented(module, func):
    """
  Function to check if a function func exists in module.

  Arguments
  ---------
  module : any
           The module where the presence of function needs
           to be checked.
  func : str
         The name of the function in str whose presence
         needs to be confirmed.

  Raises
  ------
  NotImplementedError : If the function is not present in module.
  """
    imp = getattr(module, func)
    if not callable(imp):
        raise NotImplementedError


def _a_decode_long(stream, offset, count, _):
    """
    'a2J42',3,2 --> 5,42
    """
    return offset + count, int(stream[offset:offset + count])


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


def p_filetype(t):
    """filetype : BINARY
                | MOTOROLA
                | AIFF
                | WAVE
                | MP3
                | FLAC"""
    t[0] = t[1]


def remove():
    """Delete current cache

    """
    pass


def has_changes(statements):
    """ See if a list of SQL statements has any lines that are not just comments """
    for stmt in statements:
        if not stmt.startswith('--') and not stmt.startswith('\n\n--'):
            return True
    return False


def is_select(status):
    """Returns true if the first word in status is 'select'."""
    if not status:
        return False
    return status.split(None, 1)[0].lower() == 'select'


def remove_tags(ResourceId=None, TagsList=None):
    """
    Removes the specified tags from a trail.
    See also: AWS API Documentation

    :example: response = client.remove_tags(
        ResourceId='string',
        TagsList=[
            {
                'Key': 'string',
                'Value': 'string'
            },
        ]
    )

    :type ResourceId: string
    :param ResourceId: [REQUIRED]
            Specifies the ARN of the trail from which tags should be removed. The format of a trail ARN is:
            arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail

    :type TagsList: list
    :param TagsList: Specifies a list of tags to be removed.
            (dict) --A custom key-value pair associated with a resource such as a CloudTrail trail.
            Key (string) -- [REQUIRED]The key in a key-value pair. The key must be must be no longer than 128 Unicode characters. The key must be unique for the resource to which it applies.
            Value (string) --The value in a key-value pair of a tag. The value must be no longer than 256 Unicode characters.

    :rtype: dict
    :return: {}

    """
    pass


def strings_to_services(strings, string_to_service):
    """Convert service strings to SUPPORT_* service bitmask."""
    services = 0
    for string in strings:
        services |= string_to_service[string]
    return services


@classmethod
def parse(cls, string):
    """Parse an ebuild |Version| from a string."""
    return cls.parse_parts(string.split('-'))


def _ordered_edges(face_edges):
    """Returns "srce", "trgt" and "face" indices
    organized clockwise for each face.

    Parameters
    ----------
    face_edges: `pd.DataFrame`
        exerpt of an edge_df for a single face

    Returns
    -------
    edges: list of 3 ints
        srce, trgt, face indices, ordered
    """
    srces, trgts, faces = face_edges[['srce', 'trgt', 'face']].values.T
    srce, trgt, face_ = srces[0], trgts[0], faces[0]
    edges = [[srce, trgt, face_]]
    for face_ in faces[1:]:
        srce, trgt = trgt, trgts[srces == trgt][0]
        edges.append([srce, trgt, face_])
    return edges


def t_quotedvar_ENCAPSED_AND_WHITESPACE(t):
    """( [^"\\\\${] | \\\\(.|\\n) | \\$(?![A-Za-z_{]) | \\{(?!\\$) )+"""
    t.lexer.lineno += t.value.count('\n')
    t.lexer.pop_state()
    return t


@classmethod
def from_formula(cls, formula, data, subset=None):
    """
        Not implemented for state space models
        """
    raise NotImplementedError


def _update_params_on_kvstore(param_arrays, grad_arrays, kvstore, param_names):
    """Perform update of param_arrays from grad_arrays on kvstore."""
    for index, pair in enumerate(zip(param_arrays, grad_arrays)):
        arg_list, grad_list = pair
        if grad_list[0] is None:
            continue
        name = param_names[index]
        kvstore.push(name, grad_list, priority=-index)
        kvstore.pull(name, arg_list, priority=-index)


@classmethod
def spend(cls, txo: 'BaseOutput') ->'BaseInput':
    """ Create an input to spend the output."""
    assert txo.script.is_pay_pubkey_hash, 'Attempting to spend unsupported output.'
    script = cls.script_class.redeem_pubkey_hash(cls.NULL_SIGNATURE, cls.
        NULL_PUBLIC_KEY)
    return cls(txo.ref, script)


def _get_type(pob):
    """
    randomly decide if is small rna or degradation
    """
    return 0


def _neurite_name(neurite, prefix, names):
    """The neurite name used for the legend"""
    name = str(neurite.type).replace('NeuriteType.', '').replace('_', ' ')
    return '{} {} {}'.format(prefix, name, names[neurite.type])


def actuator_remove(actuator: str='', object: str=''):
    """Remove an actuator from the active object

    :param actuator: Actuator, Name of the actuator to edit
    :type actuator: str
    :param object: Object, Name of the object the actuator belongs to
    :type object: str
    """
    pass


def pos(df, class_feat, pos_class):
    """Return subset of instances that are labeled positive."""
    return df[df[class_feat] == pos_class]


def center(x, xo, intens, width):
    """
    the centroid definition, used to fit the spectrum
    x can be a nparray
    FWMH is   sqrt(2) x width.
    """
    return intens * (1 - ((x - xo) / width) ** 2)


def get_config(request):
    """Return a dictionary with config options."""
    config = {}
    options = ['logsdir', 'host', 'port', 'server', 'ctl', 'node']
    for option in options:
        option_name = 'rabbitmq_' + option
        conf = request.config.getoption(option_name) or request.config.getini(
            option_name)
        config[option] = conf
    return config


def put(item):
    """Put an item on the end of the queue.

        Item must be persistable (picklable)."""


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

        :param WebSessionLogInfo val:
        :rtype: AccessMethodLogInfo
        """
    return cls('admin_console', val)


def length(x):
    """Returns the number of elements in the array by returning list.length"""
    return len(x)


def shade_flat():
    """Render and display faces uniform, using Face Normals

    """
    pass


def find_end_index(start_index, lines):
    """
    Given a start index and lines of data, finds the first line that
    contains only '' and returns the index for that line.
    """
    end_index = None
    for line in lines[start_index:]:
        if line == '':
            end_index = lines.index(line, start_index)
            break
    return end_index


@staticmethod
def cook(raw_item, **params):
    """
        If it's convenient to cache a modified version of the item that was
        fetched, it can be transformed here.
        :param raw_item: item to be cooked
        :param params: other parameters that may be required
        :return: cooked item
        """
    return raw_item


def ancestors(node):
    """
    Returns the list of all nodes dominating the given tree node.
    This method will not work with leaf nodes, since there is no way
    to recover the parent.
    """
    results = []
    try:
        current = node.parent()
    except AttributeError:
        return results
    while current:
        results.append(current)
        current = current.parent()
    return results


def shade_smooth():
    """Render and display faces smooth, using interpolated Vertex Normals

    """
    pass


def sample_to_orbit(sample: list) ->list:
    """Provides the orbit corresponding to a given sample.

    **Example usage:**

    >>> sample = [1, 2, 0, 0, 1, 1, 0, 3]
    >>> sample_to_orbit(sample)
    [3, 2, 1, 1, 1]

    Args:
        sample (list[int]): a sample from GBS

    Returns:
        list[int]: the orbit of the sample
    """
    return sorted(filter(None, sample), reverse=True)


def slide(align: bool=False, select: bool=True):
    """Select and slide paint curve point

    :param align: Align Handles, Aligns opposite point handle during transform
    :type align: bool
    :param select: Select, Attempt to select a point handle before transform
    :type select: bool
    """
    pass


def expand_NDIG(w):
    """Expand digit sequences to a series of words."""
    try:
        numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        num_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six',
            'seven', 'eight', 'nine']
        str2 = ''
        for n in w:
            if n.isdigit():
                str2 += num_words[numbers.index(n)]
                str2 += ' '
            elif n == '.':
                str2 += 'dot'
                str2 += ' '
            else:
                str2 += ''
        return str2[:-1]
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        return w


def bech32_polymod(values):
    """Internal function that computes the Bech32 checksum."""
    generator = [996825010, 642813549, 513874426, 1027748829, 705979059]
    chk = 1
    for value in values:
        top = chk >> 25
        chk = (chk & 33554431) << 5 ^ value
        for i in range(5):
            chk ^= generator[i] if top >> i & 1 else 0
    return chk


@classmethod
def like(cls, arr, eta=0):
    """Creates a new PDMA object with its shape and dtype like the specified NumPy array.

        :param arr: The array to take the shape and data type from.
        :type arr: numpy.ndarray
        :param eta: The polynomial decay factor. Must be >= 0. The default of 0 corresponds to the
            simple average. Higher values of eta correspond to a polynomially decaying window of
            degree eta.
        :type eta: float
        :returns: The new polynomial-decay moving average object.
        :rtype: average.PDMA
        """
    return cls(arr.shape, arr.dtype, eta)


def chunked_read(timeout):
    """Reads chunked input.

    .. warning:: Bytes are returned for Python 3.

    * http://uwsgi.readthedocs.io/en/latest/Chunked.html
    * http://uwsgi.readthedocs.io/en/latest/Changelog-1.9.13.html#chunked-input-api

    :param int timeout: Wait timeout (seconds).

    :rtype: bytes|str

    :raises IOError: If unable to receive chunked part.
    """


def hfc_zeroQuad(slow_spec, freqs, T):
    """
    Applies a correction factor to the spectrum of a slow-measured variable
    based on the response-time T. Quadrature must be analytically zero!

    Parameters
    -----------
    slow_spec: numpy.array or series
        the spectrum to be corrected (not cross-spectrum!)
    freqs: numpy.array
        frequencies
    T: float
        the response-time

    Returns
    --------
    spec: numpy.array
        the recovered array
    """
    import numpy as np
    assert len(slow_spec) == len(freqs)
    return slow_spec * (1.0 + 4.0 * np.pi ** 2.0 * freqs ** 2.0 * T ** 2.0)


@classmethod
def create(cls, name, encoding=None, collation=None):
    """Query to create a database."""
    statement = 'CREATE DATABASE "{name}"'.format(name=name)
    if encoding is not None:
        statement += " ENCODING = '{encoding}'".format(encoding=encoding)
    if collation is not None:
        statement += " LC_COLLATE = '{collation}'".format(collation=collation)
    return statement


def display_value_prompt(setting, setting_help):
    """display function for setting a value"""
    print('\t>> %s: %s' % (setting, setting_help))
    if setting != 'Password':
        return input('\t>> Enter a new value for %s: ' % setting)
    else:
        import getpass
        return getpass.getpass('\t>> Enter a new value for %s: ' % setting)


def has_newline(value):
    """Check if given node value contains newlines"""
    return '\r' in value or '\n' in value if isinstance(value, str) else False


def _gen_single(img, gdata, mdata, btype, show_btype=False):
    """Generate tuple for a single output to adjust it to provided style."""
    if show_btype:
        return img, gdata, mdata, btype
    else:
        return img, gdata, mdata


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

    .. math::
        C_D = 0.5\\left\\{16\\left[(\\frac{24}{Re})^{1.6} + (\\frac{130}{Re})^{0.72}
        \\right]^{2.5}+ \\left[\\left(\\frac{40000}{Re}\\right)^2 + 1\\right]^{-0.25}
        \\right\\}^{0.25}

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

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

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

    Examples
    --------
    >>> Swamee_Ojha(200.)
    0.8490012397545713

    References
    ----------
    .. [1] Swamee, P. and Ojha, C. (1991). "Drag Coefficient and Fall Velocity
       of nonspherical particles." J. Hydraul. Eng., 117(5), 660-667.
    .. [2] Barati, Reza, Seyed Ali Akbar Salehi Neyshabouri, and Goodarz
       Ahmadi. "Development of Empirical Models with High Accuracy for
       Estimation of Drag Coefficient of Flow around a Smooth Sphere: An
       Evolutionary Approach." Powder Technology 257 (May 2014): 11-19.
       doi:10.1016/j.powtec.2014.02.045.
    """
    Cd = 0.5 * (16 * ((24.0 / Re) ** 1.6 + (130.0 / Re) ** 0.72) ** 2.5 + (
        (40000.0 / Re) ** 2 + 1) ** -0.25) ** 0.25
    return Cd


def linker(name: str) ->str:
    """Return inner link format."""
    return name.lower().replace('.', '')


def convert_pixel_wcs(ccd_image, lon_or_ra, lat_or_dec, is_pix=True, origin=0):
    """
    Takes either pixel or World Coordinate System (RA/Dec)
    coordinates and converts to the other type.

    Parameters
    ----------
    ccd_image: CCDData object
        Image which has the coordinates to convert.

    lon_or_ra: `numpy.ndarray' (or float)
        An array of coordinates (or a single coordinate).
        Represents the lon/ra axis, depending on what is
        passed in.

    lat_or_dec: `numpy.ndarray' (or float)
        An array of coordinates (or a single coordinate).
        Represents the lat/dec axis, depending on what is
        passed in.

    is_pix: bool
        Used to determine what coordinates are being inputted.
        Assumes pixel coordinates by default.

    origin: int
        The coordinate in the upper left corner of the image.
        Generally, this is 1 in FITS and Fortran standards,
        or 0 in Numpy and C standards. Defaults to 0.

    Returns
    -------
    Returns two `numpy.ndarray' objects, the first being lon/RA,
    and the second lat/Dec.

    """
    if is_pix:
        return ccd_image.wcs.all_pix2world(lon_or_ra, lat_or_dec, origin)
    else:
        return ccd_image.wcs.all_world2pix(lon_or_ra, lat_or_dec, origin)


@staticmethod
def format_if_rule(rule, number):
    """Support to build if-based-rules in report

        Parameters
        ----------
        rule : str
            A whip specification rule.
        number : int
            The counter of the if-statements used in the whip specification,
            counter starts at 1.
        """
    return '{}_if_{}'.format(rule, number)


def parse_file_size(s):
    """Return int from file size (1234, 55G, 1.7T)."""
    if not s:
        return int(s)
    suffix = s[-1]
    power = 1000
    try:
        factor = {'K': power, 'M': power ** 2, 'G': power ** 3, 'T': power **
            4, 'P': power ** 5}[suffix]
        s = s[:-1]
    except KeyError:
        factor = 1
    return int(float(s) * factor)


def rows_to_dict(rows, main_key_position=0, null_value='delete',
    header_line=0, contains_open_ends=False):
    """
    Convert a row of rows (e.g. csv) to dictionary

    Parameters
    ----------
    rows : list
        the row based data to convert to `dict`
    main_key_position : int, optional
        if the main_key is not on the top left, its position can be specified
    null_value : any, optional
        if an emtpy field in the lists shall be represented somehow in the dictionary
    header_line : int, optional
        if the header_line is not the first one, its position can be specified
    contains_open_ends : bool, optional
        if each row is not in the same length (due to last set entry as last element in row),
        a length check for corrupted data can be ignored

    Returns
    -------
    dict
        dictionary containing the information from row-based data

    """
    data = dict()
    header = rows[header_line]
    for row in rows[header_line + 1:]:
        sub_data = dict()
        for i in range(len(header)):
            if i == main_key_position:
                continue
            elif i >= len(row):
                if not contains_open_ends:
                    raise IndexError('not all elements are the same length')
                elif null_value != 'delete':
                    sub_data[header[i]] = null_value
            elif not row[i] and null_value != 'delete':
                sub_data[header[i]] = null_value
            elif not row[i]:
                continue
            else:
                sub_data[header[i]] = row[i]
        data[row[main_key_position]] = sub_data
    data = {header[main_key_position]: data}
    return data


def palettecolor_copy():
    """Copy current Grease Pencil palette color

    """
    pass


def is_user_context(context):
    """Indicates if the request context is a normal user."""
    if not context:
        return False
    if context.is_admin:
        return False
    if not context.user_id or not context.project_id:
        return False
    return True


def build_from_clause(sources):
    """Given a list of table names, connects them with JOINs"""
    from_clause = [sources[0]]
    for join_to in sources[1:]:
        from_clause.append('JOIN {} ON ({}. = {}.)'.format(join_to, sources
            [0], join_to))
    return '\n'.join(from_clause)


def top_screen_edge(desktop, rect):
    """ Get the y-coordinate of the effective top screen edge.

    Parameters
    ----------
    desktop : QDesktopWidget
        The desktop widget for the application.

    rect : QRect
        The rect of interest.

    Returns
    -------
    result : int
        the y-coordinate of the effective top screen edge.

    """
    p1 = rect.topLeft()
    p2 = rect.topRight()
    g1 = desktop.availableGeometry(p1)
    g2 = desktop.availableGeometry(p2)
    return max(p1.y(), g1.top(), g2.top())


def qemuopts(qemuopts):
    """
    Makes sure qemuopts is valid.
    """
    if qemuopts is None:
        return True
    if not isinstance(qemuopts, str):
        raise TypeError('qemuopts must be none or str.')
    return True


def assert_cmd_has_no_qmark(command: str, context: str='') ->None:
    """Throws Exception if the query contains a question marks."""
    if '?' not in command:
        return
    message = ''
    if context:
        message = ' ' + context
    message = (message +
        "Set commands must not contain question-marks. Sent command: '{0}'"
        .format(command.strip('\n')))
    raise Exception(message)


@classmethod
def reset(cls):
    """
        Releases the underlying CUDA driver context and resources occupied by it.
        """
    cls.invoke('cudaDeviceReset')


@classmethod
def get_time(cls, time):
    """returns time in miliseconds
           from '0:00:00,000' """
    sl = cls.time_pattern.search(time)
    return int(sl.group(4)) + 1000 * (int(sl.group(3)) + 60 * (int(sl.group
        (2)) + 60 * int(sl.group(1))))


def classification_clusters(dic_clusters):
    """dic_cluster: diccionario con las palabras por cluster generado por dic_cluster
        dic_out = diccionario con los clusters clasificados
        Recibe un diccionario de clusters generado con dict_cluster,
        entrega un diccionario con los clusters clasificados.
    """
    dic_out = {'positivo': [], 'negativo': [], 'neutro': []}
    print('p = positivo, n = negativo y a = no emocional')
    pregunta = input(
        '¿Listo para clasificar los clusters en esas categorias? y/n: ')
    if pregunta != 'y':
        return
    for i in list(dic_clusters.keys()):
        print(dic_clusters[i])
        tipo = input('¿Es del tipo p/n/a?: ')
        if tipo == 'p':
            dic_out['positivo'].append(i)
        elif tipo == 'n':
            dic_out['negativo'].append(i)
        elif tipo == 'a':
            dic_out['neutro'].append(i)
        else:
            print(f'Error, cluster {str(i)} no clasificado')
    return dic_out


def delta_qu(soil, H, D):
    """ Displacement at Qu
    """
    if 'sand' in soil:
        return min(0.01 * H, 0.1 * D)
    elif 'clay' in soil:
        return min(0.1 * H, 0.2 * D)
    else:
        raise ValueError('Unknown soil type.')


def create_rest_api(name=None, description=None, version=None, cloneFrom=
    None, binaryMediaTypes=None):
    """
    Creates a new  RestApi resource.
    See also: AWS API Documentation

    :example: response = client.create_rest_api(
        name='string',
        description='string',
        version='string',
        cloneFrom='string',
        binaryMediaTypes=[
            'string',
        ]
    )

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

    :type description: string
    :param description: The description of the RestApi .

    :type version: string
    :param version: A version identifier for the API.

    :type cloneFrom: string
    :param cloneFrom: The ID of the RestApi that you want to clone from.

    :type binaryMediaTypes: list
    :param binaryMediaTypes: The list of binary media types supported by the RestApi . By default, the RestApi supports only UTF-8-encoded text payloads.
            (string) --

    :rtype: dict
    :return: {
        'id': 'string',
        'name': 'string',
        'description': 'string',
        'createdDate': datetime(2015, 1, 1),
        'version': 'string',
        'warnings': [
            'string',
        ],
        'binaryMediaTypes': [
            'string',
        ]
    }

    :returns:
    (string) --

    """
    pass


def register_ad_error_cb(error):
    """Advertisement registration error callback."""
    print('Failed to register advertisement: ' + str(error))


def _overlaps(media_a, media_b):
    """Determines if two TrackMedia overlap."""
    a1 = media_a.start
    a2 = media_a.start + media_a.duration - 1
    b1 = media_b.start
    b2 = media_b.start + media_b.duration - 1
    return a1 <= b2 and b1 <= a2


def is_root(name, names):
    """Determine if a field is a root field."""
    dots = name.split('.')
    return not (len(dots) > 1 and dots[0] in names)


def repr_message(msg):
    """
    用于 Message 和 SentMessage 对象的 __repr__ 和 __unicode__
    """
    from wxpy.api.chats import Group
    text = str(msg.text or '').replace('\n', ' ↩ ')
    text += ' ' if text else ''
    if msg.sender == msg.bot.self:
        ret = '↪ {self.receiver.name}'
    elif isinstance(msg.chat, Group) and msg.member != msg.receiver:
        ret = '{self.sender.name} › {self.member.name}'
    else:
        ret = '{self.sender.name}'
    ret += ' : {text}({self.type})'
    return ret.format(self=msg, text=text)


@property
def count(cls):
    """
        Get count of rules defined in the class.
        :return: Count of rules.
        :raise RuleNotDefinedException: If the rule is not defined.
        :raise CantCreateSingleRuleException: If the rule consists of more rules.
        :raise NotASingleSymbolException: If number of symbols on the left is more.
        """
    return len(cls.rules)


def _format_remainder(float_time_number):
    """Format a floating point remainder of a time unit."""
    string = ',' + ('%f' % float_time_number)[2:].rstrip('0')
    if string == ',':
        return ''
    return string


def detrend_none(x, axis=None):
    """
    Return x: no detrending.

    Parameters
    ----------
    x : any object
        An object containing the data

    axis : integer
        This parameter is ignored.
        It is included for compatibility with detrend_mean

    See Also
    --------
    detrend_mean : Another detrend algorithm.
    detrend_linear : Another detrend algorithm.
    detrend : A wrapper around all the detrend algorithms.
    """
    return x


def parabolic_percent_absorption_at_time(time, absorption_time):
    """
    Find percent of absorbed carbs using a parabolic model

    Parameters:
    time -- relative time after eating (in minutes)
    absorption_time --  time for carbs to completely absorb (in minutes)

    Output:
    Percent of absorbed carbs
    """
    if time < 0:
        return 0
    if time <= absorption_time / 2:
        return 2 / pow(absorption_time, 2) * pow(time, 2)
    if time < absorption_time:
        return -1 + 4 / absorption_time * (time - pow(time, 2) / (2 *
            absorption_time))
    return 1


def exp(input):
    """Returns a new tensor with the exponential of the elements of the input tensor `input`.

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

    Returns
    -------
    Tensor
        The output tensor.
    """
    pass


def get_session(context, key):
    """Gets the key from the session."""
    session_manager = context.session_data_manager
    if not session_manager.hasSessionData():
        return None
    session = session_manager.getSessionData()
    if key not in session.keys():
        return None
    return session[key]


@staticmethod
def simple_join(loader, node):
    """
        Yaml join list of string on empty string.
        usage: !join [param, ...]

        :param obj loader: PyYaml Loader.
        :param obj node: Pyyaml node.
        :return: joined string.
        """
    seq = loader.construct_sequence(node)
    return ''.join(seq)


@classmethod
def _from_json(cls, json_dict, solver, fit_intercept, est_stderr, tol,
    max_iter, reg_method, alpha, l1_ratio, coef, stderr):
    """
        Helper function to construct the linear model used by from_json.
        This function is designed to be override by subclasses.
        Parameters
        ----------
        json_dict : the dictionary that specifies the model
        solver: specific solver for each linear model
        fit_intercept: boolean indicating fit intercept or not
        est_stderr: boolean indicating calculte std.err of coefficients (usually expensive) or not
        tol: tolerence of fitting error
        max_iter: maximum iteraration of fitting
        reg_method: method to regularize the model, one of (None, l1, l2, elstic_net).
        alpha: regularization strength
        l1_ratio: if elastic_net, the l1 alpha ratio
        coef: the coefficients
        stderr: the std.err of coefficients
        Returns
        -------
        linear model object: a linear model object specified by the json_dict and other arguments
        """
    return cls(solver=solver, fit_intercept=fit_intercept, est_stderr=
        est_stderr, tol=tol, max_iter=max_iter, reg_method=reg_method,
        alpha=alpha, l1_ratio=l1_ratio, coef=coef, stderr=stderr)


def create_mask(inputs, pad_token):
    """
    Create a binary mask to indicate whether a token is pad or not

    :param inputs: (seq_len, batch_size)
    :param pad_token: token for padding
    :return: mask: (seq_len, batch_size)
    """
    return inputs != pad_token


def onebp_substitutions(seq):
    """Generate all 1bp substitutions of the sequence.

    Assumes unambiguous IUPAC codes A, C, G, T only.
    """
    seq = seq.upper()
    variants = set()
    for i in range(len(seq)):
        for s in 'ACGT':
            variants.add(seq[:i] + s + seq[i + 1:])
    variants.remove(seq)
    return variants


def cf_var_name(field=None, dim=None):
    """
     | cf_var_name - return the name from a supplied dimension
     |               in the following order
     |               ncvar
     |               short_name
     |               long_name
     |               standard_name
     |
     | field=None - field
     | dim=None - dimension required - 'dim0', 'dim1' etc.
     |
     |
     |
     |
     |
     :Returns:
      name
     |
     |
     |
    """
    id = getattr(field.construct(dim), 'id', False)
    ncvar = field.construct(dim).nc_get_variable(False)
    short_name = getattr(field.construct(dim), 'short_name', False)
    long_name = getattr(field.construct(dim), 'long_name', False)
    standard_name = getattr(field.construct(dim), 'standard_name', False)
    name = 'No Name'
    if id:
        name = id
    if ncvar:
        name = ncvar
    if short_name:
        name = short_name
    if long_name:
        name = long_name
    if standard_name:
        name = standard_name
    return name


def backup(isamAppliance, check_mode=False, force=False):
    """
    Kickoff Backup of active partition
    """
    if check_mode is True:
        return isamAppliance.create_return_object(changed=True)
    else:
        return isamAppliance.invoke_put('Kickoff Backup of Active Partition',
            '/firmware_settings/kickoff_backup', {})


def dtt_time(averages, bandwidth, overlap, verbose=False):
    """
    Takes in number of averages, bandwidth, overlap of a FFT.
    Returns and prints the amount of data time in seconds the FFT will need.
    """
    if overlap > 1.0:
        overlap = overlap / 100.0
    if verbose:
        print('Averages = {}'.format(averages))
        print('Bandwidth = {} Hz'.format(bandwidth))
        print('Overlap = {} %'.format(overlap * 100.0))
    totalTime = (1 + (averages - 1) * (1 - overlap)) / bandwidth
    if verbose:
        print('\x1b[93m Total DTT Spectrum Time = {} seconds \x1b[0m'.
            format(totalTime))
        print('\x1b[91m Total DTT Spectrum Time = {} minutes \x1b[0m'.
            format(totalTime / 60.0))
    return totalTime


def print_pstats_list(pstats, pformat=None):
    """Print list of pstats dict formatted
    :param list pstats: pstats dicts to print
    :param str format: String.format style to show fields with keys:
        ncalls, tottime, tt_percall, cumtime, ct_percall, file, lineno, method
        rcalls, calls
    :return: Directly print of result formatted and return True"""
    if not pstats:
        return False
    if pformat is None:
        pformat = (
            '{method:<40s} {factor:>16s} {cumtime:>10s} {calls:>10s} {rcalls:>10s} {tottime:>10s} {tt_percall:>10s} {ct_percall:>10s} <{file}:{lineno}'
            )
    for pstat_line in ([dict(zip(pstats[0].keys(), pstats[0].keys()))] + pstats
        ):
        print(pformat.format(**pstat_line))
    return True