@staticmethod
def get_full_url(url, use_ssl, host):
    """Return the full URL to a DCOR resource

        Parameters
        ----------
        url: str
            Full URL or resource identifier; valid values are

            - https://dcor.mpl.mpg.de/api/3/action/dcserv?id=caab96f6-
              df12-4299-aa2e-089e390aafd5'
            - dcor.mpl.mpg.de/api/3/action/dcserv?id=caab96f6-df12-
              4299-aa2e-089e390aafd5
            - caab96f6-df12-4299-aa2e-089e390aafd5
        use_ssl: bool
            Set this to False to disable SSL (should only be used for
            testing). Defaults to None (does not force SSL if the URL
            starts with "http://").
        host: str
            Use this host if it is not specified in `url`
        """
    if use_ssl is None:
        if url.startswith('http://'):
            web = 'http'
        else:
            web = 'https'
    elif use_ssl:
        web = 'https'
    else:
        web = 'http'
    if url.count('://'):
        base = url.split('://', 1)[1]
    else:
        base = url
    if base.count('/'):
        host, api = base.split('/', 1)
    else:
        api = 'api/3/action/dcserv?id=' + base
    new_url = '{}://{}/{}'.format(web, host, api)
    return new_url


def human_time_cost(tc):
    """
    请毫秒单位的tc值，转换成人能看懂的时间字符串
    """
    tc = float(tc) / 1000
    return '{} 秒'.format(tc)


def parse(pattern, string, custom_types=None, includes=None):
    """
    Try to match the pattern to the string, returning
    a dictionary of values pulled from the string.
    This raises a SparserValueError on no match

    :param str patt:
    :param str string:
    :param {type_name: (regex, cb)} custom_types:
    :param {include_name: include_pattern, ...} includes:
    :rtype: dict
    """
    compiled = compile(pattern, custom_types, includes)
    ret = compiled.parse(string)
    return ret


def _write_content(handler, content):
    """write content to locked file"""
    handler.seek(0)
    handler.truncate()
    if content:
        handler.write(content)
    handler.flush()


def _fix_defaults(output, defaults=None):
    """
    Update the fill_value and masked data of `output`
    from the default given in a dictionary defaults.
    """
    names = output.dtype.names
    data, mask, fill_value = output.data, output.mask, output.fill_value
    for k, v in (defaults or {}).items():
        if k in names:
            fill_value[k] = v
            data[k][mask[k]] = v
    return output


def is_good_response(response):
    """Helper method to check if boto3 call was a success."""
    code = response['ResponseMetadata']['HTTPStatusCode']
    return 200 <= code < 300


@classmethod
def _has_element(cls, container, index):
    """Check to see if an index is in the container.

        Args:
            container (obj): Object that should be checked for index.
            index (obj): Index that should be checked for.

        Returns:
            bool: True if the index is in the container.

        """
    raise NotImplementedError('This must be overwritten by the subclass.')


@classmethod
def blend(cls, model, **params):
    """ Get a mixer class for model.

        :return instance:

        """
    scheme = cls.__load_cls(model)
    backend = cls.__store__.get(scheme)
    if not backend:
        if cls.__is_django_model(scheme):
            from .backend.django import mixer as backend
        elif cls.__is_sqlalchemy_model(scheme):
            from .backend.sqlalchemy import mixer as backend
        elif cls.__is_mongoengine_model(scheme):
            from .backend.mongoengine import mixer as backend
        cls.__store__[scheme] = backend
    return backend.blend(scheme, **params)


@classmethod
def _tokenize(cls, sentence):
    """
        Split a sentence while preserving tags.
        """
    while True:
        match = cls._regex_tag.search(sentence)
        if not match:
            yield from cls._split(sentence)
            return
        chunk = sentence[:match.start()]
        yield from cls._split(chunk)
        tag = match.group(0)
        yield tag
        sentence = sentence[len(chunk) + len(tag):]


@staticmethod
def bool_from_env(val):
    """
        Allow '0' and 'false' and 'no' to be False
        """
    falsey = {'0', 'false', 'no'}
    return val and val.lower() not in falsey


def case_insensitive_get(d: dict, key: str, default=None, take_first=False):
    """
    Looks up a key in a dictionary ignoring case. We use this sometimes to be
    nicer to users who don't provide perfectly sanitized data
    :param d:
    :param key:
    :param default:
    :param take_first:
    :return:
    """
    found_value = False
    value = None
    for k, v in d.items():
        if k.lower() == key.lower():
            if not take_first and found_value:
                raise ValueError('Duplicate case insensitive keys')
            value = v
            found_value = True
            if take_first:
                break
    if not found_value:
        return default
    return value


def listCreators():
    """ Return a sequence of DCMI Creator elements (resource authors).

        o Depending on the implementation, this returns the full name(s) of the
          author(s) of the content object or their ids.

        o Permission:  View
        """


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

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


@staticmethod
def to_parameter(role, suffix='ColumnName'):
    """
        Converts a role into (as per manifesrt.json) parameter name.
        ``GroupId --> RowGroupColumnName``.
        """
    if not isinstance(role, str):
        raise TypeError("Unexpected role '{0}'".format(role))
    if role == 'Weight':
        return 'ExampleWeight' + suffix
    if role == 'GroupId':
        return 'RowGroup' + suffix
    return role + suffix


def get_file_path(filepath, basedir):
    """Get all parts of the file path relative to the base directory of the torrent."""
    return list(filepath.relative_to(basedir).parts)


def is_function_pointer_stack(stack):
    """Count how many non-nested paranthesis are in the stack.  Useful for determining if a stack is a function pointer"""
    paren_depth = 0
    paren_count = 0
    star_after_first_paren = False
    last_e = None
    for e in stack:
        if e == '(':
            paren_depth += 1
        elif e == ')' and paren_depth > 0:
            paren_depth -= 1
            if paren_depth == 0:
                paren_count += 1
        elif e == '*' and last_e == '(' and paren_count == 0 and paren_depth == 1:
            star_after_first_paren = True
        last_e = e
    if star_after_first_paren and paren_count == 2:
        return True
    else:
        return False


def is_redirection(code: int) ->bool:
    """Return true if the code is aa redirection HTTP response code.

    Args:
        code (int): The HTTP response code.

    Returns:
        bool: True if the code was a redirection else false.
    """
    return code >= 300 and code < 400


def processEnded(reason):
    """
        Called when the child process exits and all file descriptors associated
        with it have been closed.

        @type reason: L{twisted.python.failure.Failure}
        @param reason: A failure giving the reason the child process
            terminated.  The type of exception for this failure is either
            L{twisted.internet.error.ProcessDone} or
            L{twisted.internet.error.ProcessTerminated}.
        """


def draw_rectangle(draw, coordinates, color, width=1, fill=30):
    """Draw a rectangle with an optional width."""
    fill = color + (fill,)
    outline = color + (255,)
    for i in range(width):
        coords = [coordinates[0] - i, coordinates[1] - i, coordinates[2] +
            i, coordinates[3] + i]
        if i == 0:
            draw.rectangle(coords, fill=fill, outline=outline)
        else:
            draw.rectangle(coords, outline=outline)


def column_sort_key(column):
    """Sort key for column names. 'id' and 'uuid' come first, then the
    top-level properties in alphabetical order, followed by the nested
    properties (identifiable by the presence of an underscore)."""
    return ('id', 'uuid', column.name).index(column.name), column.name.count(
        '_'), column.name


def refresh_trusted_advisor_check(checkId=None):
    """
    Requests a refresh of the Trusted Advisor check that has the specified check ID. Check IDs can be obtained by calling  DescribeTrustedAdvisorChecks .
    The response contains a  TrustedAdvisorCheckRefreshStatus object, which contains these fields:
    See also: AWS API Documentation

    :example: response = client.refresh_trusted_advisor_check(
        checkId='string'
    )

    :type checkId: string
    :param checkId: [REQUIRED]
            The unique identifier for the Trusted Advisor check to refresh. Note: Specifying the check ID of a check that is automatically refreshed causes an InvalidParameterValue error.

    :rtype: dict
    :return: {
        'status': {
            'checkId': 'string',
            'status': 'string',
            'millisUntilNextRefreshable': 123
        }
    }

    """
    pass


def custom_repo(**kw):
    """
    Repo files need special care in that a whole line should not be present
    if there is no value for it. Because we were using `format()` we could
    not conditionally add a line for a repo file. So the end result would
    contain a key with a missing value (say if we were passing `None`).

    For example, it could look like::

        [ceph repo]
        name= ceph repo
        proxy=
        gpgcheck=

    Which breaks. This function allows us to conditionally add lines,
    preserving an order and be more careful.

    Previously, and for historical purposes, this is how the template used
    to look::

        custom_repo =
        [{repo_name}]
        name={name}
        baseurl={baseurl}
        enabled={enabled}
        gpgcheck={gpgcheck}
        type={_type}
        gpgkey={gpgkey}
        proxy={proxy}

    """
    lines = []
    tmpl = ('reponame', '[%s]'), ('name', 'name=%s'), ('baseurl', 'baseurl=%s'
        ), ('enabled', 'enabled=%s'), ('gpgcheck', 'gpgcheck=%s'), ('_type',
        'type=%s'), ('gpgkey', 'gpgkey=%s'), ('proxy', 'proxy=%s'), ('priority'
        , 'priority=%s')
    for line in tmpl:
        tmpl_key, tmpl_value = line
        if tmpl_key in kw and kw.get(tmpl_key) not in (None, ''):
            lines.append(tmpl_value % kw.get(tmpl_key))
    return '\n'.join(lines)


def preset_add(name: str='', remove_active: bool=False):
    """Add or remove a Cloth Preset

    :param name: Name, Name of the preset, used to make the path name
    :type name: str
    :param remove_active: remove_active
    :type remove_active: bool
    """
    pass


def scipy_rebin(aa, *args):
    """ Simple script to rebin an input array to a new shape.

    Akin to IDL's routine Taken from scipy documentation:
    http://wiki.scipy.org/Cookbook/Rebinning As in IDL, the new shape
    must be a factor of the old one.  The ugly 'evList trick' builds
    and executes a python command.

    """
    raise DeprecationWarning('This function is deprecated and likely broken')
    """
    shape = aa.shape
    lenShape = len(shape)
    factor = np.asarray(shape)/np.asarray(args)
    evList = ['aa.reshape('] +              ['args[%d],factor[%d],'%(i,i) for i in range(lenShape)] +              [')'] + ['.mean(%d)'%(i+1) for i in range(lenShape)]
    #print ''.join(evList)
    return eval(''.join(evList))
    """


def fill_gaussian(df):
    """
    fill_gaussian           :function to fill missing values using Gaussian distribution with sigma and mu taken from normal_range_min, normal_range_high
    parameters              :labs DataFrame
    returns                 :labs DataFrame with missing values filled with Gaussian distribution
    """


def _import(subs, shared):
    """Configure the `doorstop import` subparser."""
    info = 'import an existing document or item'
    sub = subs.add_parser('import', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('path', nargs='?', help=
        'path to previously exported document file')
    sub.add_argument('prefix', nargs='?', help='prefix of document for import')
    group = sub.add_mutually_exclusive_group()
    group.add_argument('-d', '--document', nargs=2, metavar='ARG', help=
        'import an existing document by: PREFIX PATH')
    group.add_argument('-i', '--item', nargs=2, metavar='ARG', help=
        'import an existing item by: PREFIX UID')
    sub.add_argument('-p', '--parent', metavar='PREFIX', help=
        'parent document prefix for imported document')
    sub.add_argument('-a', '--attrs', metavar='DICT', help=
        'dictionary of item attributes to import')
    sub.add_argument('-m', '--map', metavar='DICT', help=
        'dictionary of custom item attribute names')


def delete_function(FunctionName=None, Qualifier=None):
    """
    Deletes the specified Lambda function code and configuration.
    If you are using the versioning feature and you don't specify a function version in your DeleteFunction request, AWS Lambda will delete the function, including all its versions, and any aliases pointing to the function versions. To delete a specific function version, you must provide the function version via the Qualifier parameter. For information about function versioning, see AWS Lambda Function Versioning and Aliases .
    When you delete a function the associated resource policy is also deleted. You will need to delete the event source mappings explicitly.
    This operation requires permission for the lambda:DeleteFunction action.
    See also: AWS API Documentation

    Examples
    This operation deletes a Lambda function
    Expected Output:

    :example: response = client.delete_function(
        FunctionName='string',
        Qualifier='string'
    )

    :type FunctionName: string
    :param FunctionName: [REQUIRED]
            The Lambda function to delete.
            You can specify the function name (for example, Thumbnail ) or you can specify Amazon Resource Name (ARN) of the function (for example, arn:aws:lambda:us-west-2:account-id:function:ThumbNail ). If you are using versioning, you can also provide a qualified function ARN (ARN that is qualified with function version or alias name as suffix). AWS Lambda also allows you to specify only the function name with the account ID qualifier (for example, account-id:Thumbnail ). Note that the length constraint applies only to the ARN. If you specify only the function name, it is limited to 64 characters in length.

    :type Qualifier: string
    :param Qualifier: Using this optional parameter you can specify a function version (but not the $LATEST version) to direct AWS Lambda to delete a specific function version. If the function version has one or more aliases pointing to it, you will get an error because you cannot have aliases pointing to it. You can delete any function version but not the $LATEST , that is, you cannot specify $LATEST as the value of this parameter. The $LATEST version can be deleted only when you want to delete all the function versions and aliases.
            You can only specify a function version, not an alias name, using this parameter. You cannot delete a function version using its alias.
            If you don't specify this parameter, AWS Lambda will delete the function, including all of its versions and aliases.

    :return: response = client.delete_function(
        FunctionName='myFunction',
        Qualifier='1',
    )

    print(response)

    """
    pass


def subscribe(list_id, email_address, merge_vars, email_type):
    """Do subscribe the email address to the list_id"""


def get_platform_variables(ds):
    """
    Returns a list of platform variable NAMES

    :param netCDF4.Dataset ds: An open netCDF4 Dataset
    """
    candidates = []
    for variable in ds.variables:
        platform = getattr(ds.variables[variable], 'platform', '')
        if platform and platform in ds.variables:
            if platform not in candidates:
                candidates.append(platform)
    platform = getattr(ds, 'platform', '')
    if platform and platform in ds.variables:
        if platform not in candidates:
            candidates.append(platform)
    return candidates


def _tuples_to_dict(meta, header, tagged_parts):
    """ Convert a dictionnary and list of tuples into dictionnary """
    structured_message = {}
    structured_message['meta'] = meta
    structured_message['structured_text'] = {}
    structured_message['structured_text']['header'] = header
    structured_text = []
    for part, tag in tagged_parts:
        dict_message = {}
        dict_message['part'] = part
        dict_message['tags'] = tag
        structured_text.append(dict_message)
    structured_message['structured_text']['text'] = structured_text
    return structured_message


def identity():
    """Return identity of dirstate it to detect changing in storage

        If identity of previous dirstate is equal to this, writing
        changes based on the former dirstate out can keep consistency.
        """


def get_node_text(node):
    """
    Always return string representation for node text
    """
    if not node.text:
        return ''
    return node.text


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

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


def sort_frames_by_age(quiz_report_frames):
    """Sorts the list of frames so that the newest
    is first, the oldest is last"""
    quiz_report_frames.sort(key=lambda x: x.submitted.max(), reverse=True)
    return quiz_report_frames


def read_or_raise(fin, size):
    """ Instead of returning a result smaller than `size` like `io.read()`,
		it raises and EOFError.
	"""
    data = fin.read(size)
    if len(data) != size:
        raise EOFError
    return data


def face_select_reveal(select: bool=True):
    """Reveal hidden faces

    :param select: Select
    :type select: bool
    """
    pass


@classmethod
def _convert_to_style(cls, style_dict, num_format_str=None):
    """
        converts a style_dict to an xlwt style object

        Parameters
        ----------
        style_dict : style dictionary to convert
        num_format_str : optional number format string
        """
    import xlwt
    if style_dict:
        xlwt_stylestr = cls._style_to_xlwt(style_dict)
        style = xlwt.easyxf(xlwt_stylestr, field_sep=',', line_sep=';')
    else:
        style = xlwt.XFStyle()
    if num_format_str is not None:
        style.num_format_str = num_format_str
    return style


def output(init, result):
    """
    write results to file and be done

    Parameters
    ==========
    model :

    PSDdata :

    HAp :

    Returns
    =======
    out :

    Examples
    ========
    """
    return


def is_nan(builder, val):
    """
    Return a condition testing whether *val* is a NaN.
    """
    return builder.fcmp_unordered('uno', val, val)


def stepStarted(build, step):
    """A step has just started. 'step' is a dictionary which
        represents the step: it can be queried for more information.

        This method may return an IStatusReceiver (it could even return
        'self'). If it does so, logStarted and logFinished methods will be
        invoked on the object for logs created by this one step. This
        receiver will be automatically unsubscribed when the step finishes.

        Alternatively, the method may return a tuple of an IStatusReceiver
        and an integer named 'updateInterval'."""


def is_uniq(values):
    """ Check if input items are unique

    Parameters
    ----------
    values : set
        set of all values

    Returns
    -------
    True/False, MULTI/unique value
    """
    if len(values) == 0:
        return True, ''
    elif len(values) == 1:
        return True, list(values)[0]
    else:
        return False, 'MULTI'


def PS(val):
    """PersonalNameSubject"""
    return val


def extract_temperature_value_from_thermo_file_path(file_path):
    """ does what it says, returns a float"""
    return float(file_path.split('_T')[1].split('_X')[0])


def expose(class_method):
    """
    Decorator which exposes given method into interface

    :param class_method: method to expose
    :return: given method with modifications
    """
    class_method.is_exposed = True
    return class_method


def get_identifier_name(cursor):
    """
    Retrieves the identifier name from the given clang cursor.

    :param cursor: A clang cursor from the AST.
    :return:       The identifier as string.
    """
    return cursor.displayname


def calculate_dynamic_pressure(rho, TAS):
    """Calculates the dynamic pressure.

    Parameters
    ----------
    rho : float
        Air density (kg/m³).
    TAS : float
        True Air Speed (m/s).

    Returns
    -------
    q_inf : float
        Dynamic pressure. (Pa)

    Notes
    -----
    $$ q_{inf} = 1/2  · rho · TAS² $$
    """
    return 0.5 * rho * TAS ** 2


def bind(fun, *argsfrom2, **kwbind):
    """
    bind function with first argument as a tensor
    :return: callable bound
    """
    import snipy.decotool as decotool
    _ = decotool.bind.placeholder
    argsbind = [_] + list(argsfrom2)
    return decotool.bind(fun, *argsbind, **kwbind)


@classmethod
def get_real_child_model(cls, data):
    """Returns the real base class specified by the discriminator"""
    discriminator_value = data[cls.json_discriminator_key]
    return cls.discriminator_value_class_map.get(discriminator_value)


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


def set_text(node, text):
    """Set the text of a parent"""
    node.text = text


def get_fillna_dict(df: 'pd.DataFrame') ->dict:
    """ Generate a fillna dict for columns in a df
    """
    fillna_dict = {}
    for column in df:
        if df[column].dtype.kind in {'O', 'S'}:
            fillna_dict[column] = ''
        else:
            fillna_dict[column] = 0
    return fillna_dict


@classmethod
def from_inversion_vector(cls, inversion):
    """
        Calculates the permutation from the inversion vector.

        Examples
        ========

        >>> from sympy.combinatorics.permutations import Permutation
        >>> Permutation.print_cyclic = False
        >>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
        Permutation([3, 2, 1, 0, 4, 5])

        """
    size = len(inversion)
    N = list(range(size + 1))
    perm = []
    try:
        for k in range(size):
            val = N[inversion[k]]
            perm.append(val)
            N.remove(val)
    except IndexError:
        raise ValueError('The inversion vector is not valid.')
    perm.extend(N)
    return cls._af_new(perm)


@staticmethod
def _make_doc_response_schema(schema):
    """Override this to modify schema in docs

        This can be used to document a wrapping structure.

            Example: ::

                @staticmethod
                def _doc_schema(schema):
                    if schema:
                        return {'type': 'success', 'data': schema}
                    else:
                        return None
        """
    return schema


@classmethod
def factory(cls, **kwargs):
    """ helper method to open a Database object (and optionally create the tables in that Database) """
    db = cls(**kwargs)
    if kwargs.get('create'):
        db.create()
    return db


def load():
    """
    No operations are needed to load these plugins.
    """


def str_to_numeric(s):
    """
    Convert a string to a numeric type.

    Returns either an int or a float depending on the apparent type of the
    string.
    """
    try:
        return int(s)
    except ValueError:
        return float(s)


def render():
    """
        Render the property to a XML fragment, according to the relevent
        specification.
        """


@classmethod
def load_system(cls, dict_, system_id='system'):
    """
        Create a :class:`MolecularSystem` from a python :class:`dict`.

        As the loaded :class:`MolecularSystem` is storred as a :class:`dict` in
        the :class:`MolecularSystem.system` it can also be loaded directly from
        a :class:`dict` input. This feature is used by :mod:`trajectory` that
        extracts trajectory frames as dictionaries and returns them
        as :class:`MolecularSystem` objects through this classmethod.

        Parameters
        ----------
        dict_ : :class:`dict`
           A python dictionary.

        system_id : :class:`str` or :class:'int', optional
           Inherited or user defined system id. (default='system')

        Returns
        -------
        :class:`pywindow.molecular.MolecularSystem`
            :class:`MolecularSystem`

        """
    obj = cls()
    obj.system = dict_
    obj.system_id = system_id
    return obj


def reciprocal(attrs, inputs, cls):
    """Returns the reciprocal of the argument, element-wise."""
    return 'reciprocal', attrs, inputs


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


@classmethod
def todense(cls, mx):
    """Convert matrix `mx` to dense format"""
    raise NotImplementedError


@staticmethod
def __getSetTemperatureCmd(temperature):
    """Give 'Set temperature' command

    Keyword arguments:
      temperature -- (int) Temperature percentage between 0 and 100
                           0% <=> Warm white (2700K)
                           100% <=> Cool white (6500K)

    return: (bytearray) 'Set temperature' command
    """
    temperature = int(temperature)
    if temperature < 0:
        temperature = 0
    elif temperature > 100:
        temperature = 100
    temperature &= 255
    return bytearray([49, 0, 0, 8, 5, temperature, 0, 0, 0])


def quote_if_str(something):
    """
    Put quote around if a string.

    Parameters
    ----------
    something
        Any object.
    """
    if isinstance(something, str):
        return f"'{something}'"
    return f'{something}'


def get_filters(filters):
    """Return the rsync options for the given filters."""
    arguments = []
    for filter_ in filters:
        if len(filter_) > 1:
            raise Exception('Filter must contain only one entry: {}'.format
                (filter_))
        if 'exclude' in filter_:
            arguments += ['--exclude', filter_['exclude']]
        elif 'include' in filter_:
            arguments += ['--include', filter_['include']]
        else:
            raise Exception('Filter must contain include or exclude: {}'.
                format(filter_))
    return arguments


def getfirstline(file, default):
    """
    Returns the first line of a file.
    """
    with open(file, 'rb') as fh:
        content = fh.readlines()
        if len(content) == 1:
            return content[0].decode('utf-8').strip('\n')
    return default


def Edit_String_SimulData(data):
    """
    return string object made of lines which contains laue spots properties

    Called to be Edited in LaueToolsframe.control

    params:

    data tuple of spots properties
    data =(list_twicetheta, list_chi, list_energy, list_Miller, list_posX, list_posY,
           ListName, nb of(parent) grains,
            calibration parameters list, total nb of grains)
    """
    nb_total_grains = data[9]
    lines = 'Simulation Data from LAUE Pattern Program v1.0 2009 \n'
    lines += 'Total number of grains : %s\n' % int(nb_total_grains)
    lines += 'spot# h k l E 2theta chi X Y\n'
    nb = data[7]
    if isinstance(nb, int):
        nb_grains = data[7]
        TWT, CHI, ENE, MIL, XX, YY = data[:6]
        NAME = data[6]
        calib = data[8]
        for index_grain in range(nb_grains):
            nb_of_simulspots = len(TWT[index_grain])
            startgrain = '#G %d\t%s\t%d\n' % (index_grain, NAME[index_grain
                ], nb_of_simulspots)
            lines += startgrain
            for data_index in range(nb_of_simulspots):
                linedata = '%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' % (
                    data_index, MIL[index_grain][data_index][0], MIL[
                    index_grain][data_index][1], MIL[index_grain][
                    data_index][2], ENE[index_grain][data_index], TWT[
                    index_grain][data_index], CHI[index_grain][data_index],
                    XX[index_grain][data_index], YY[index_grain][data_index])
                lines += linedata
        lines += '#calibration parameters\n'
        for param in calib:
            lines += '# %s\n' % param
        return lines
    if isinstance(nb, list):
        print('nb in Edit_String_SimulData', nb)
        gen_i = 0
        TWT, CHI, ENE, MIL, XX, YY = data[:6]
        NAME = data[6]
        calib = data[8]
        for grain_ind in range(len(nb)):
            for tt in range(nb[grain_ind][1]):
                nb_of_simulspots = len(TWT[gen_i])
                startgrain = '#G %d\t%s\t%d\t%d\n' % (grain_ind, NAME[
                    grain_ind], tt, nb_of_simulspots)
                lines += startgrain
                for data_index in range(nb_of_simulspots):
                    linedata = (
                        '%d\t%d\t%d\t%d\t%.5f\t%.4f\t%.4f\t%.4f\t%.4f\n' %
                        (data_index, MIL[gen_i][data_index][0], MIL[gen_i][
                        data_index][1], MIL[gen_i][data_index][2], ENE[
                        gen_i][data_index], TWT[gen_i][data_index], CHI[
                        gen_i][data_index], XX[gen_i][data_index], YY[gen_i
                        ][data_index]))
                    lines += linedata
                gen_i += 1
        lines += '#calibration parameters\n'
        for param in calib:
            lines += '# %s\n' % param
        return lines


def is_env_var(s):
    """Environmental variables have a '$$' prefix."""
    return s.startswith('$$')


@staticmethod
def render():
    """Returns the binary representation of the label (an empty byte-string; labels
        themselves do not appear in the output).
        """
    return b''


def addReader(reader):
    """
        I add reader to the set of file descriptors to get read events for.

        @param reader: An L{IReadDescriptor} provider that will be checked for
                       read events until it is removed from the reactor with
                       L{removeReader}.

        @return: L{None}.
        """


def to_list(val):
    """
	Converts a string argument to a list by splitting it by spaces.
	Returns the object if not a string::

		from waflib.Utils import to_list
		lst = to_list('a b c d')

	:param val: list of string or space-separated string
	:rtype: list
	:return: Argument converted to list
	"""
    if isinstance(val, str):
        return val.split()
    else:
        return val


def check_spin_polarization(Par):
    """
    The function checks if a spin-polarized system should be calculated
    and sets some default parameters.
    """
    if hasattr(Par, 'Population'):
        popu = Par.Population
        ispopu = True
        rho_0 = Par.rho_0
    else:
        popu = None
        ispopu = False
        rho_0 = None
    return popu, ispopu, rho_0


def FP_update(L, R, t0, t1, u, v):
    """
    Lu is sorted by the value of au and we analyze temporal links in temporal order.
    :param L:
    :param t0:
    :param t1:
    :param u:
    :param v:
    :return:
    """
    su, au = L[u]
    su = -su
    new_arrival = t0
    new_start = min(t1, su)
    if v in R:
        current_best_duration = max(R[v][1] - R[v][0], 0)
        if max(new_arrival - new_start, 0) < current_best_duration:
            R[v] = new_start, new_arrival
        if v in L:
            sv, av = L[v]
            sv = -sv
            if new_start > sv:
                L[v] = -new_start, new_arrival
            elif new_start < sv:
                return False
        else:
            L[v] = -new_start, new_arrival
    else:
        L[v] = -new_start, new_arrival
        R[v] = new_start, new_arrival
    return True


def mean_monthly(daily):
    """Compute monthly mean for the regime curve."""
    import calendar
    d = dict(enumerate(calendar.month_abbr))
    mean_month = daily.groupby(daily.index.month).mean()
    mean_month.index = mean_month.index.map(d)
    return mean_month


def check(ref=True, priority=None):
    """
        Create and return a watcher that fires after the event loop
        polls for IO.
        """


def reverse_num(n: int) ->int:
    """Reverses a number

    :param n: number to be reversed
    :type n: int
    :returns: reversed of a number
    :rtype: int

    .. doctest:: python

        >>> reverse_num(1)
        1
        >>> reverse_num(12345)
        54321
        >>> reverse_num(54321)
        12345
        >>> reverse_num(54321000)
        12345

    """
    reversed = 0
    while n > 0:
        reversed *= 10
        reversed += n % 10
        n //= 10
    return reversed


@staticmethod
def load_exactly_one_document(_collection, _id, _zero_error=None,
    _duplicate_error=None):
    """
        Raises provided errors if not exactly one row in result.

        :param _collection: The collection to load from
        :param _id: The _id of the document
        :param _zero_error: Error to report if no documents are found
        :param _duplicate_error: Error to report when duplicate documents are found
        :return: The document
        """
    _document_cursor = _collection.find({'_id': _id})
    if _document_cursor.count() == 0:
        if _zero_error is not None:
            raise Exception(_zero_error + '_id: ' + str(_id) +
                ' could not be found.')
        else:
            return None
    elif _document_cursor.count() > 1:
        if _duplicate_error is not None:
            raise Exception(
                'Access.save: Tried saving existing, but found duplicate documents with(try to remove either) _id: '
                 + str(_id) + '.')
        else:
            return None
    elif _document_cursor.count() == 1:
        return _document_cursor[0]


def invert_convert_cbaois_to_kpsois_(cbaois, kpsois):
    """Invert the output of :func:`convert_to_cbaois_to_kpsois` in-place.

    This function writes in-place into `cbaois`.

    Added in 0.4.0.

    Parameters
    ----------
    cbaois : list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or imgaug.augmentables.bbs.BoundingBoxesOnImage or imgaug.augmentables.bbs.PolygonsOnImage or imgaug.augmentables.bbs.LineStringsOnImage
        Original coordinate-based augmentables before they were converted,
        i.e. the same inputs as provided to :func:`convert_to_kpsois`.

    kpsois : list of imgaug.augmentables.kps.KeypointsOnImages or imgaug.augmentables.kps.KeypointsOnImages
        Keypoints to convert back to the types of `cbaois`, i.e. the outputs
        of :func:`convert_cbaois_to_kpsois`.

    Returns
    -------
    list of imgaug.augmentables.bbs.BoundingBoxesOnImage or list of imgaug.augmentables.bbs.PolygonsOnImage or list of imgaug.augmentables.bbs.LineStringsOnImage or imgaug.augmentables.bbs.BoundingBoxesOnImage or imgaug.augmentables.bbs.PolygonsOnImage or imgaug.augmentables.bbs.LineStringsOnImage
        Parameter `cbaois`, with updated coordinates and shapes derived from
        `kpsois`. `cbaois` is modified in-place.

    """
    if not isinstance(cbaois, list):
        assert not isinstance(kpsois, list), (
            'Expected non-list for `kpsois` when `cbaois` is non-list. Got type %s.'
             % type(kpsois.__name__),)
        return cbaois.invert_to_keypoints_on_image_(kpsois)
    result = []
    for cbaoi, kpsoi in zip(cbaois, kpsois):
        cbaoi_recovered = cbaoi.invert_to_keypoints_on_image_(kpsoi)
        result.append(cbaoi_recovered)
    return result


@classmethod
def from_nlp(cls, nlp, **cfg):
    """Factory to add to Language.factories via entry point."""
    return cls(nlp.vocab, **cfg)


def makeConnection(process):
    """
        Called when the process has been created.

        @type process: L{IProcessTransport} provider
        @param process: An object representing the process which has been
            created and associated with this protocol.
        """


@staticmethod
def _splitNumber(stg):
    """
    Extracts an ending integer from a string if there is one.
    :return str, int: prefix, number
    """
    prefix = stg
    num = None
    for idx in range(len(stg)):
        try:
            _ = int(prefix[-1])
            if num is None:
                num = prefix[-1]
            else:
                num = prefix[-1] + num
            prefix = prefix[:-1]
        except:
            break
    if num is None:
        return prefix, None
    else:
        return prefix, int(num)


def read_job(Id=None):
    """
    The ReadJob operation returns detailed information about a job.
    See also: AWS API Documentation

    :example: response = client.read_job(
        Id='string'
    )

    :type Id: string
    :param Id: [REQUIRED]
            The identifier of the job for which you want to get detailed information.

    :rtype: dict
    :return: {
        'Job': {
            'Id': 'string',
            'Arn': 'string',
            'PipelineId': 'string',
            'Input': {
                'Key': 'string',
                'FrameRate': 'string',
                'Resolution': 'string',
                'AspectRatio': 'string',
                'Interlaced': 'string',
                'Container': 'string',
                'Encryption': {
                    'Mode': 'string',
                    'Key': 'string',
                    'KeyMd5': 'string',
                    'InitializationVector': 'string'
                },
                'TimeSpan': {
                    'StartTime': 'string',
                    'Duration': 'string'
                },
                'InputCaptions': {
                    'MergePolicy': 'string',
                    'CaptionSources': [
                        {
                            'Key': 'string',
                            'Language': 'string',
                            'TimeOffset': 'string',
                            'Label': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ]
                },
                'DetectedProperties': {
                    'Width': 123,
                    'Height': 123,
                    'FrameRate': 'string',
                    'FileSize': 123,
                    'DurationMillis': 123
                }
            },
            'Inputs': [
                {
                    'Key': 'string',
                    'FrameRate': 'string',
                    'Resolution': 'string',
                    'AspectRatio': 'string',
                    'Interlaced': 'string',
                    'Container': 'string',
                    'Encryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'TimeSpan': {
                        'StartTime': 'string',
                        'Duration': 'string'
                    },
                    'InputCaptions': {
                        'MergePolicy': 'string',
                        'CaptionSources': [
                            {
                                'Key': 'string',
                                'Language': 'string',
                                'TimeOffset': 'string',
                                'Label': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'DetectedProperties': {
                        'Width': 123,
                        'Height': 123,
                        'FrameRate': 'string',
                        'FileSize': 123,
                        'DurationMillis': 123
                    }
                },
            ],
            'Output': {
                'Id': 'string',
                'Key': 'string',
                'ThumbnailPattern': 'string',
                'ThumbnailEncryption': {
                    'Mode': 'string',
                    'Key': 'string',
                    'KeyMd5': 'string',
                    'InitializationVector': 'string'
                },
                'Rotate': 'string',
                'PresetId': 'string',
                'SegmentDuration': 'string',
                'Status': 'string',
                'StatusDetail': 'string',
                'Duration': 123,
                'Width': 123,
                'Height': 123,
                'FrameRate': 'string',
                'FileSize': 123,
                'DurationMillis': 123,
                'Watermarks': [
                    {
                        'PresetWatermarkId': 'string',
                        'InputKey': 'string',
                        'Encryption': {
                            'Mode': 'string',
                            'Key': 'string',
                            'KeyMd5': 'string',
                            'InitializationVector': 'string'
                        }
                    },
                ],
                'AlbumArt': {
                    'MergePolicy': 'string',
                    'Artwork': [
                        {
                            'InputKey': 'string',
                            'MaxWidth': 'string',
                            'MaxHeight': 'string',
                            'SizingPolicy': 'string',
                            'PaddingPolicy': 'string',
                            'AlbumArtFormat': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ]
                },
                'Composition': [
                    {
                        'TimeSpan': {
                            'StartTime': 'string',
                            'Duration': 'string'
                        }
                    },
                ],
                'Captions': {
                    'MergePolicy': 'string',
                    'CaptionSources': [
                        {
                            'Key': 'string',
                            'Language': 'string',
                            'TimeOffset': 'string',
                            'Label': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ],
                    'CaptionFormats': [
                        {
                            'Format': 'string',
                            'Pattern': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ]
                },
                'Encryption': {
                    'Mode': 'string',
                    'Key': 'string',
                    'KeyMd5': 'string',
                    'InitializationVector': 'string'
                },
                'AppliedColorSpaceConversion': 'string'
            },
            'Outputs': [
                {
                    'Id': 'string',
                    'Key': 'string',
                    'ThumbnailPattern': 'string',
                    'ThumbnailEncryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'Rotate': 'string',
                    'PresetId': 'string',
                    'SegmentDuration': 'string',
                    'Status': 'string',
                    'StatusDetail': 'string',
                    'Duration': 123,
                    'Width': 123,
                    'Height': 123,
                    'FrameRate': 'string',
                    'FileSize': 123,
                    'DurationMillis': 123,
                    'Watermarks': [
                        {
                            'PresetWatermarkId': 'string',
                            'InputKey': 'string',
                            'Encryption': {
                                'Mode': 'string',
                                'Key': 'string',
                                'KeyMd5': 'string',
                                'InitializationVector': 'string'
                            }
                        },
                    ],
                    'AlbumArt': {
                        'MergePolicy': 'string',
                        'Artwork': [
                            {
                                'InputKey': 'string',
                                'MaxWidth': 'string',
                                'MaxHeight': 'string',
                                'SizingPolicy': 'string',
                                'PaddingPolicy': 'string',
                                'AlbumArtFormat': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'Composition': [
                        {
                            'TimeSpan': {
                                'StartTime': 'string',
                                'Duration': 'string'
                            }
                        },
                    ],
                    'Captions': {
                        'MergePolicy': 'string',
                        'CaptionSources': [
                            {
                                'Key': 'string',
                                'Language': 'string',
                                'TimeOffset': 'string',
                                'Label': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ],
                        'CaptionFormats': [
                            {
                                'Format': 'string',
                                'Pattern': 'string',
                                'Encryption': {
                                    'Mode': 'string',
                                    'Key': 'string',
                                    'KeyMd5': 'string',
                                    'InitializationVector': 'string'
                                }
                            },
                        ]
                    },
                    'Encryption': {
                        'Mode': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string'
                    },
                    'AppliedColorSpaceConversion': 'string'
                },
            ],
            'OutputKeyPrefix': 'string',
            'Playlists': [
                {
                    'Name': 'string',
                    'Format': 'string',
                    'OutputKeys': [
                        'string',
                    ],
                    'HlsContentProtection': {
                        'Method': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'InitializationVector': 'string',
                        'LicenseAcquisitionUrl': 'string',
                        'KeyStoragePolicy': 'string'
                    },
                    'PlayReadyDrm': {
                        'Format': 'string',
                        'Key': 'string',
                        'KeyMd5': 'string',
                        'KeyId': 'string',
                        'InitializationVector': 'string',
                        'LicenseAcquisitionUrl': 'string'
                    },
                    'Status': 'string',
                    'StatusDetail': 'string'
                },
            ],
            'Status': 'string',
            'UserMetadata': {
                'string': 'string'
            },
            'Timing': {
                'SubmitTimeMillis': 123,
                'StartTimeMillis': 123,
                'FinishTimeMillis': 123
            }
        }
    }

    :returns:
    Key
    Key MD5
    Initialization Vector

    """
    pass


@classmethod
def from_cfunits(cls, units):
    """Return a |Period| object representing the time unit of the
        given `units` string aggreeing with the NetCDF-CF conventions.

        The following example string is taken from the `Time Coordinate`_
        chapter of the NetCDF-CF conventions.  Note that the character
        of the first entry (the actual time unit) is of relevance:

        >>> from hydpy import Period
        >>> Period.from_cfunits('seconds since 1992-10-8 15:15:42.5 -6:00')
        Period('1s')
        >>> Period.from_cfunits(' day since 1992-10-8 15:15:00')
        Period('1d')
        >>> Period.from_cfunits('m since 1992-10-8')
        Period('1m')
        """
    return cls(f'1{units.strip()[0]}')


def canonicalizeName(name, mech_type):
    """
    Canonicalizes a GSSAPI Name into a Mechanism Name

    This method turns any GSSAPI name into a "mechanism name",
    i.e. a name that would be returned as initator principal
    from acceptSecContext.

    .. warning::

       Unlike other methods, a mechanism type must be explicitly provided here;
       No default is available for this method.

    :param name: the GSSAPI name to canonicalize
    :param mech_type: the mechanism type
    :type mech_type: :class:`gssapi.base.types.MechType`
    :returns: a canonicalized name
    :rtype: PyCapsule
    :except GSSError:
    """


@staticmethod
def path_to_yaml(representer, node):
    """Convert path to YAML.

        Value is total number of seconds."""
    return representer.represent_scalar('!pathlib.Path', str(node))


def _sym_solve(Dinv, A, r1, r2, solve):
    """
    An implementation of [4] equation 8.31 and 8.32

    References
    ----------
    .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
           optimizer for linear programming: an implementation of the
           homogeneous algorithm." High performance optimization. Springer US,
           2000. 197-232.

    """
    r = r2 + A.dot(Dinv * r1)
    v = solve(r)
    u = Dinv * (A.T.dot(v) - r1)
    return u, v


def lineWidth(requestContext, seriesList, width):
    """
    Takes one metric or a wildcard seriesList, followed by a float F.

    Draw the selected metrics with a line width of F, overriding the default
    value of 1, or the &lineWidth=X.X parameter.

    Useful for highlighting a single metric out of many, or having multiple
    line widths in one graph.

    Example::

        &target=lineWidth(server01.instance01.memory.free,5)

    """
    for series in seriesList:
        series.options['lineWidth'] = width
    return seriesList


@classmethod
def find(cls, db, token):
    """Find a token object by value.

        Returns None if not found.

        `kind='user'` only returns API tokens for users
        `kind='service'` only returns API tokens for services
        """
    prefix_match = cls.find_prefix(db, token)
    for orm_token in prefix_match:
        if orm_token.match(token):
            return orm_token


@classmethod
def is_valid(cls, value):
    """Check whether a value is one of the pre-defined sizes.

        Args:
            value (str): the size.

        Returns:
            True if the value equals one of the constants, False otherwise.

        """
    return value in cls._values


def difference(image1, image2):
    """
    Returns the absolute value of the pixel-by-pixel difference between the two
    images. At least one of the images must have mode "1".

    .. code-block:: python

        out = abs(image1 - image2)

    :rtype: :py:class:`~PIL.Image.Image`
    """
    image1.load()
    image2.load()
    return image1._new(image1.im.chop_difference(image2.im))


@staticmethod
def mime_type_flow():
    """Returns the mime type used for flows."""
    return 'application-x-sympathy-flow'


def channels_ungroup():
    """Remove selected F-Curves from their current groups

    """
    pass


def get_all_headers(message, key):
    """
	Given an HTTPMessage, return all headers matching a given key.
	"""
    return message.get_all(key)


def firstStringInList(literalEntities, prefLanguage='en'):
    """
    from a list of literals, returns the one in prefLanguage
    if no language specification is available, return first element
    """
    match = ''
    if len(literalEntities) == 1:
        match = literalEntities[0]
    elif len(literalEntities) > 1:
        for x in literalEntities:
            if getattr(x, 'language') and getattr(x, 'language'
                ) == prefLanguage:
                match = x
        if not match:
            match = literalEntities[0]
    return match


def file_from_list_of_images(file_list, current_file, request):
    """
    return filename from file_list depends of request
    request: position on the list
    """
    if file_list:
        if request == 'first':
            file = file_list[0]
        elif request == 'previous':
            if current_file in file_list:
                position = file_list.index(current_file)
                if position > 0:
                    file = file_list[position - 1]
                else:
                    file = None
            else:
                file = file_list[0]
        elif request == 'next':
            if current_file in file_list:
                position = file_list.index(current_file)
                if position <= len(file_list) - 2:
                    file = file_list[position + 1]
                else:
                    file = None
            else:
                file = file_list[-1]
        elif request == 'last':
            file = file_list[-1]
        else:
            file = None
    else:
        file = None
    if file == current_file:
        file = None
    return file


def getid(obj):
    """Get obj's id or object itself if no id

    Abstracts the common pattern of allowing both an object or
    an object's ID (UUID) as a parameter when dealing with relationships.
    """
    try:
        return obj.id
    except AttributeError:
        return obj


def flush():
    """Ensure the file object has been updated.

        This is used to make sure that any data buffered in the
        accessor is stored in the file object, allowing other
        accessors to use it.

        """


def GenWrapper(Module, SignalDict, OutputDir):
    """
	Generate a wrapper HDL file for specified IP according to signal Dictionnary.
	"""
    if not isinstance(SignalDict, dict):
        return False
    return True


def unpack_argument(session, service_name, operation_name, cli_argument, value
    ):
    """
    Unpack an argument's value from the commandline. This is part one of a two
    step process in handling commandline arguments. Emits the load-cli-arg
    event with service, operation, and parameter names. Example::

        load-cli-arg.ec2.describe-instances.foo

    """
    param_name = getattr(cli_argument, 'name', 'anonymous')
    value_override = session.emit_first_non_none_response(
        'load-cli-arg.%s.%s.%s' % (service_name, operation_name, param_name
        ), param=cli_argument, value=value, service_name=service_name,
        operation_name=operation_name)
    if value_override is not None:
        value = value_override
    return value


def convert_list_to_string(data, separator=','):
    """
    تبدیل لیست به رشته

    :type data: list
    :type separator: str
    :return: str
    """
    if type(data) == list:
        return separator.join(data)
    if data:
        return data
    return ''


def sqrt(data=None, out=None, name=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 : 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 onlywhite(line):
    """Return true if the line does only consist of whitespace characters."""
    for c in line:
        if c is not ' ' and c is not '  ':
            return c is ' '
    return line


def quaternion_real(quaternion):
    """Return real part of quaternion.

    >>> quaternion_real([3.0, 0.0, 1.0, 2.0])
    3.0

    """
    return quaternion[0]


def emptyDict(dic):
    """
    Tests a dictionary to see if all keys are zero
    and returns True if so.

    Parameters:
    --------------
    dic            a dictionary

    :return:
    """
    for entry in dic.values():
        if entry == 0:
            zero_dic = True
        elif type(entry) == list or type(entry) == str or entry != 0:
            zero_dic = False
            break
    return zero_dic


ttwidgets//ttwidgets - Copy.pyfile:/ttwidgets - Copy.py:function:quote/quote

def quote(s):
    """Ensure that any string S with white space is enclosed in quotes."""
    if isinstance(s, str):
        if ' ' in s or len(s.split()) > 1:
            start, end = s[0], s[-1]
            if start != end or start not in ('"', "'"):
                q1s, q1d, q3s, q3d = "'", '"', 3 * "'", 3 * '"'
                if q1d not in s:
                    s = q1d + s + q1d
                elif q1s not in s:
                    s = q1s + s + q1s
                elif q3d not in s:
                    s = q3d + s + q3d
                elif q3s not in s:
                    s = q3s + s + q3s
    return s


def _export(subs, shared):
    """Configure the `doorstop export` subparser."""
    info = 'export a document as YAML or another format'
    sub = subs.add_parser('export', description=info.capitalize() + '.',
        help=info, **shared)
    sub.add_argument('prefix', help="prefix of document to export or 'all'")
    sub.add_argument('path', nargs='?', help=
        "path to exported file or directory for 'all'")
    group = sub.add_mutually_exclusive_group()
    group.add_argument('-y', '--yaml', action='store_true', help=
        'output YAML (default when no path)')
    group.add_argument('-c', '--csv', action='store_true', help=
        "output CSV (default for 'all')")
    group.add_argument('-t', '--tsv', action='store_true', help='output TSV')
    group.add_argument('-x', '--xlsx', action='store_true', help='output XLSX')
    sub.add_argument('-w', '--width', type=int, help=
        'limit line width on text output')


def FitCBVs(model):
    """
  Fits the CBV design matrix to the de-trended flux of a given target. This
  is called internally whenever the user accesses the :py:attr:`fcor`
  attribute.

  :param model: An instance of the :py:obj:`everest` model for the target

  """
    raise NotImplementedError('This mission is not yet supported.')


def extract_tests(api_response, defined_tests):
    """
    Create and return a dict of test name to test data.

    If api_response is None, return a dict with an empty dict.

    api_response: the JSON response from the Proctor API in Python object form.
    defined_tests: an iterable of test name strings defining the tests that
        should be available to the user. Usually from Django settings.
    """
    if api_response is None:
        return {'tests': {}}
    api_audit = api_response['audit']
    api_tests = api_response['tests']
    test_dict = {}
    for test_name in defined_tests:
        if test_name in api_tests:
            test_dict[test_name] = api_tests[test_name]
        else:
            test_dict[test_name] = {}
    return {'audit': api_audit, 'tests': test_dict}


def default_hook(entries):
    """Default hook called for each entry"""
    return entries


def pytest_benchmark_group_stats(config, benchmarks, group_by):
    """
    You may perform grouping customization here, in case the builtin grouping doesn't suit you.

    Example:

    .. sourcecode:: python

        @pytest.mark.hookwrapper
        def pytest_benchmark_group_stats(config, benchmarks, group_by):
            outcome = yield
            if group_by == "special":  # when you use --benchmark-group-by=special
                result = defaultdict(list)
                for bench in benchmarks:
                    # `bench.special` doesn't exist, replace with whatever you need
                    result[bench.special].append(bench)
                outcome.force_result(result.items())
    """
    pass


def linear(x):
    """ Linear activations.
    """
    return x


def replace_pattern(tokens, new_pattern):
    """ Given a RegexLexer token dictionary 'tokens', replace all patterns that
        match the token specified in 'new_pattern' with 'new_pattern'.
    """
    for state in tokens.values():
        for index, pattern in enumerate(state):
            if isinstance(pattern, tuple) and pattern[1] == new_pattern[1]:
                state[index] = new_pattern


def pg_commit(dbh):
    """Commit a transaction"""
    dbh.commit()


def add_headers(msg, headers):
    """Add headers to a Message object.

       msg is an email.message.Message object.

       headers is a dictionary of headers and values.
       """
    if headers:
        for k in sorted(headers.keys()):
            del msg[k]
            msg[k] = headers[k]


def split_by_n(seq, n_var):
    """
    A generator to divide a sequence into chunks of n units.
    """
    while seq:
        yield seq[:n_var]
        seq = seq[n_var:]


def action_sanitize():
    """Make action suitable for use as a Pose Library

    """
    pass


def _flatten_log(log):
    """
    Convert the nested-dict log format to a list of lovestate dicts.

    The log is typically dictionaries of read/unread information,
    in a doubly-nested dictionary indexed by the plan name and the
    snippet. This converts that structure into a list of those dicts,
    where the former indices (plan name and snippet) are added as
    two extra entries to that dictionary.

    """
    flattened = []
    for un, snips in sorted(log.items()):
        for snip, lovestate in sorted(snips.items()):
            lovestate = dict(lover=un, text=snip, **lovestate)
            flattened.append(lovestate)
    return flattened


def _n_create_handler(event):
    """Default handler for when an N-CREATE request is received.

    See _handlers.doc_handle_create for detailed documentation.
    """
    raise NotImplementedError("No handler has been bound to 'evt.EVT_N_CREATE'"
        )


def create_random_src(min_distance=10, nr_sources=100):
    """Create nr_sources random sources in RA and DEC (in degree)
    :param min_distance : create sources with distance > than min_distance
    among each other (in degree)
    :param nr_sources : number of random sources to create
    """
    import astropy.coordinates as coord
    import astropy.units as u
    from astropy.coordinates import SkyCoord
    import numpy as np
    min_distance = min_distance * u.deg
    print('Minimum distance between sources is: ', min_distance,
        '\nNumber of random sources is: ', nr_sources)
    sources_ra = []
    sources_dec = []
    ra_first = np.random.uniform(-180, 180, 1)
    dec_first = np.random.uniform(0, 90, 1)
    sources_ra.append(ra_first)
    sources_dec.append(dec_first)
    while len(sources_dec) < nr_sources:
        ra = np.random.uniform(-180, 180, 1)
        dec = np.random.uniform(0, 90, 1)
        c1 = SkyCoord(ra=ra, dec=dec, frame='icrs', unit='deg')
        c2 = SkyCoord(ra=sources_ra, dec=sources_dec, frame='icrs', unit='deg')
        sep_vect = c1.separation(c2)
        greater_ = [(True) for i in sep_vect if i > min_distance]
        if len(greater_) < len(sources_ra):
            continue
        else:
            sources_ra.append(ra)
            sources_dec.append(dec)
    final_ra = []
    final_dec = []
    for RA, DEC in zip(sources_ra, sources_dec):
        final_ra.append(RA[0])
        final_dec.append(DEC[0])
    return final_ra, final_dec


def state(sender, process, data):
    """The process state that Supervisor reports

    - ``process:{name}:state``
    """
    sender.riemann.event(service='process:{name}:state'.format(**data),
        state=data['statename'].lower())


def parabola2_func(x, a, b, c):
    """
    Function for defining the second parabola function.
    """
    return a * x ** 2 + b * x + c


@classmethod
def get_config_opts(cls):
    """Override base class config options as do not use datasource """
    return []


def get_key_policy(KeyId=None, PolicyName=None):
    """
    Retrieves a policy attached to the specified key.
    See also: AWS API Documentation

    Examples
    The following example retrieves the key policy for the specified customer master key (CMK).
    Expected Output:

    :example: response = client.get_key_policy(
        KeyId='string',
        PolicyName='string'
    )

    :type KeyId: string
    :param KeyId: [REQUIRED]
            A unique identifier for the customer master key. This value can be a globally unique identifier or the fully specified ARN to a key.
            Key ARN Example - arn:aws:kms:us-east-1:123456789012:key/12345678-1234-1234-1234-123456789012
            Globally Unique Key ID Example - 12345678-1234-1234-1234-123456789012

    :type PolicyName: string
    :param PolicyName: [REQUIRED]
            String that contains the name of the policy. Currently, this must be 'default'. Policy names can be discovered by calling ListKeyPolicies .

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

    """
    pass


@classmethod
def has_issues(cls, subcls_name=None, category=None):
    """ Tell if issues were encountered while checking entities. """
    for _ in cls.issues(subcls_name, category):
        return True
    return False


def reveal():
    """Show hidden particles

    """
    pass


@classmethod
def validate(cls, obj, raise_errors=False):
    """Validate an object to check if it could be of this type.

        Args:
            obj (object): Object to validate.
            raise_errors (bool, optional): If True, errors will be raised when
                the object fails to be validated. Defaults to False.

        Returns:
            bool: True if the object could be of this type, False otherwise.

        """
    if not cls.python_types:
        raise NotImplementedError("Attribute 'python_types' must be set.")
    out = isinstance(obj, cls.python_types)
    if not out and raise_errors:
        raise ValueError(("Object of type '%s' is not one of the accepted " +
            'Python types (%s) for this type (%s).') % (type(obj), cls.
            python_types, cls.name))
    return out


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

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

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


def import_symbol(name):
    """
    Imports a symbol based on its fully qualified name.

    :param name: symbol name
    :type name: basestring
    :returns: symbol
    :raises ImportError: if could not import the module
    :raises AttributeError: if could not find the symbol in the module
    """
    if name and '.' in name:
        module_name, name = name.rsplit('.', 1)
        return getattr(__import__(module_name, fromlist=[name], level=0), name)
    raise ImportError('import not found: {}'.format(name))


def read_mfa_model(filename):
    """
    Import and read csv file.
    Returns the model in lists that separate columns
    """
    file = open(filename)
    labels = file.readline()
    lines = file.readlines()
    rxnID = []
    formulae = []
    atm_trans = []
    rates = []
    rxnType = []
    basis = []
    deviation = []
    LB = []
    UB = []
    excludedMetabolites = []
    inputSubstrates = []
    measuredIsotopes = []
    mids = [[], [], []]
    c = 1
    for line in lines:
        if line[-1] == '\n':
            line = line[0:-1]
        line_split = line.split(',')
        if line_split[1] == '':
            continue
        elif line_split[1] == 'rxnEq':
            c = 1
        elif line_split[1] == 'excludedMetabolites':
            c = 2
        elif line_split[1] == 'inputSubstrates':
            c = 3
        elif line_split[1] == 'measuredIsotopes':
            c = 4
        elif line_split[1] == 'measurements':
            c = 5
        elif c == 1:
            rxnID.append(line_split[0])
            formula = line_split[1].split(' ')
            if '=' in formula:
                ind = formula.index('=')
                formula[ind] = '->'
                formula_string = ' '.join(formula)
                formulae.append(formula_string)
            elif '=>' in formula:
                ind = formula.index('=>')
                formula[ind] = '->'
                formula_string = ' '.join(formula)
                formulae.append(formula_string)
            else:
                formulae.append(line_split[1])
            trans = line_split[2].split(' ')
            if '=' in trans:
                ind = trans.index('=')
                trans[ind] = '->'
                trans_string = ' '.join(trans)
                atm_trans.append(trans_string)
            elif '=>' in trans:
                ind = trans.index('=>')
                trans[ind] = '->'
                trans_string = ' '.join(trans)
                atm_trans.append(trans_string)
            else:
                atm_trans.append(line_split[2])
            rates.append(line_split[3])
            rxnType.append(line_split[4])
            basis.append(line_split[5])
            if line_split[9] == '*':
                prime_basis = float(line_split[5])
            deviation.append(line_split[6])
            LB.append(line_split[7])
            UB.append(line_split[8])
        elif c == 2 and line_split[0] == '#':
            excludedMetabolites.append(line_split[1])
        elif c == 3 and line_split[0] == '#':
            inputSubstrates.append(line_split[1])
        elif c == 4 and line_split[0] == '#':
            measuredIsotopes.append(line_split[1])
        elif c == 5 and line_split[0] == '#':
            mids[1].append(line_split[1])
            mids[2].append(line_split[2])
        mids[0] = measuredIsotopes
    model_metabolite = [[], [], [], [], [], [], [], [], []]
    model_isotope = [[], [], [], [], [], []]
    for i in range(len(rxnID)):
        if rxnType[i] == 'F' or rxnType[i] == 'FR' or rxnType[i
            ] == 'R' or rxnType[i] == 'B' or rxnType[i] == 'BR' or rxnType[i
            ] == 'BRR':
            model_metabolite[0].append(rxnID[i])
            model_metabolite[1].append(formulae[i])
            model_metabolite[2].append(rates[i])
            model_metabolite[3].append(basis[i])
            model_metabolite[4].append(deviation[i])
            model_metabolite[5].append(rxnType[i])
            model_metabolite[7].append(LB[i])
            model_metabolite[8].append(UB[i])
    model_metabolite[6].append(prime_basis)
    for i in range(len(rxnID)):
        if rxnType[i] == 'F' or rxnType[i] == 'FR' or rxnType[i
            ] == 'R' or rxnType[i] == 'S' or rxnType[i] == 'SF':
            model_isotope[0].append(rxnID[i])
            model_isotope[1].append(formulae[i])
            model_isotope[2].append(atm_trans[i])
            model_isotope[3].append(rates[i])
            model_isotope[4].append(basis[i])
            model_isotope[5].append(deviation[i])
    model_isotope.append(measuredIsotopes)
    file.close()
    dc = {'FR': 1, 'F': 2, 'B': 3, 'BR': 1.5, 'R': 6, 'X': 4, 'Basis': 5}
    model_tmp = []
    for j in range(len(model_metabolite[0])):
        if model_metabolite[3][j] == '':
            ln_tmp = [dc[model_metabolite[5][j]]]
        elif model_metabolite[3][j] == 'X':
            ln_tmp = [dc['X']]
            model_metabolite[3][j] = ''
        else:
            ln_tmp = [dc['Basis']]
        ln_tmp.append(model_metabolite[0][j])
        ln_tmp.append(model_metabolite[1][j])
        ln_tmp.append(model_metabolite[2][j])
        ln_tmp.append(model_metabolite[3][j])
        ln_tmp.append(model_metabolite[4][j])
        ln_tmp.append(model_metabolite[5][j])
        ln_tmp.append(model_metabolite[7][j])
        ln_tmp.append(model_metabolite[8][j])
        model_tmp.append(ln_tmp)
    model_tmp = sorted(model_tmp)
    model_metabolite = model_metabolite = [[], [], [], [], [], [], [], [], []]
    model_metabolite[6].append(prime_basis)
    for k in model_tmp:
        model_metabolite[0].append(k[1])
        model_metabolite[1].append(k[2])
        model_metabolite[2].append(k[3])
        model_metabolite[3].append(k[4])
        model_metabolite[4].append(k[5])
        model_metabolite[5].append(k[6])
        model_metabolite[7].append(k[7])
        model_metabolite[8].append(k[8])
    return (model_metabolite, model_isotope, excludedMetabolites,
        inputSubstrates, mids)


def ramp(time, slope, start, finish=0):
    """
    Implements vensim's and xmile's RAMP function

    Parameters
    ----------
    time: function
        The current time of modelling
    slope: float
        The slope of the ramp starting at zero at time start
    start: float
        Time at which the ramp begins
    finish: float
        Optional. Time at which the ramp ends

    Returns
    -------
    response: float
        If prior to ramp start, returns zero
        If after ramp ends, returns top of ramp
    Examples
    --------

    """
    t = time()
    if t < start:
        return 0
    elif finish <= 0:
        return slope * (t - start)
    elif t > finish:
        return slope * (finish - start)
    else:
        return slope * (t - start)


def has_columns(df, columns, exact_cols=False, exact_order=False):
    """Asserts that `df` has ``columns``

    Args:
        df (pd.DataFrame): Any pd.DataFrame.
        columns (list or tuple): Columns that are expected to be in ``df``.
        exact_cols (bool): Whether or not ``columns`` need to be the only columns in ``df``.
        exact_order (bool): Whether or not ``columns`` need to be in
                            the same order as the columns in ``df``.

    Returns:
        Original `df`.

    """
    df_cols = df.columns
    msg = []
    missing_cols = list(set(columns).difference(df_cols))
    if missing_cols:
        msg.append('`df` is missing columns: {}.'.format(missing_cols))
    if exact_cols:
        unexpected_extra_cols = list(set(df_cols).difference(columns))
        if unexpected_extra_cols:
            msg.append('`df` has extra columns: {}.'.format(
                unexpected_extra_cols))
    if exact_order:
        if missing_cols:
            msg.append(
                '`df` column order does not match given `columns` order, because columns are missing.'
                )
        else:
            idx_order = []
            for i in range(len(columns)):
                try:
                    idx_order.append(columns.index(df.columns[i]))
                except ValueError:
                    pass
            if idx_order != sorted(idx_order):
                msg.append(
                    '`df` column order does not match given `columns` order.')
    if msg:
        raise AssertionError(' '.join(msg))
    return df


def listAllowedSubjects(content=None, content_type=None):
    """ List the allowed values of the 'Subject' DCMI element.

        o 'Subject' elements should be keywords categorizing their resource.

        o Return only values appropriate for content's type, or all values if
          both 'content' and 'content_type' are None.
        """


def repeat(input, repeats, dim):
    """Repeats elements of an array.

    Parameters
    ----------
    input : Tensor
        Input data array
    repeats : int
        The number of repetitions for each element
    dim : int
        The dim along which to repeat values.

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


def reshape_bygroups(items, bygroup_columns='formatted', bygroup_as_index=
    True, bygroup_formatted_suffix='_f', bygroup_collision_suffix='_by'):
    """
    Convert current By group representation to the specified representation

    Parameters
    ----------
    items : :class:`SASDataFrame` or list of :class:`SASDataFrames`
        The DataFrames to process.
    bygroup_columns : string, optional
        The way By group columns should be represented in the output table.  The
        options are 'none' (only use metadata), 'formatted', 'raw', or 'both'.
    bygroup_as_index : boolean, optional
        Specifies whether the By group columns should be converted to indices.
    bygroup_formatted_suffix : string, optional
        The suffix to use on formatted columns if the names collide with existing
        columns.
    bygroup_collision_suffix : string, optional
        The suffix to use on By group columns if there is also a data column
        with the same name.

    See Also
    --------
    :meth:`SASDataFrame.reshape_bygroups`

    Returns
    -------
    :class:`SASDataFrame` or list of :class:`SASDataFrame` objects

    """
    if hasattr(items, 'reshape_bygroups'):
        return items.reshape_bygroups(bygroup_columns=bygroup_columns,
            bygroup_as_index=bygroup_as_index, bygroup_formatted_suffix=
            bygroup_formatted_suffix, bygroup_collision_suffix=
            bygroup_collision_suffix)
    out = []
    for item in items:
        if hasattr(item, 'reshape_bygroups'):
            out.append(item.reshape_bygroups(bygroup_columns=
                bygroup_columns, bygroup_as_index=bygroup_as_index,
                bygroup_formatted_suffix=bygroup_formatted_suffix,
                bygroup_collision_suffix=bygroup_collision_suffix))
        else:
            out.append(item)
    return out


def pretty_hex(val):
    """convert a value into a pretty hex"""
    s = hex(int(val))
    s = s[2:]
    if len(s) == 1:
        s = '0' + s
    return s


def batch(proxy):
    """convenience method to get a batch proxy adapter"""
    return proxy._pyroBatch()


def _adjust_n_years(other, n, month, reference_day):
    """Adjust the number of times an annual offset is applied based on
    another date, and the reference day provided"""
    if n > 0:
        if (other.month < month or other.month == month and other.day <
            reference_day):
            n -= 1
    elif other.month > month or other.month == month and other.day > reference_day:
        n += 1
    return n


def delindex(object, index):
    """Deletes the value at the specified index."""
    del object[index]


def shutdown(event):
    """ shutdown the rss feed fetcher. """
    from . import runtime
    rss = runtime.get('rss', None)
    if rss:
        rss.stop()


def case_insensitive_get(d: dict, key: str, default=None, take_first=False):
    """
    Looks up a key in a dictionary ignoring case. We use this sometimes to be
    nicer to users who don't provide perfectly sanitized data
    :param d:
    :param key:
    :param default:
    :param take_first:
    :return:
    """
    found_value = False
    value = None
    for k, v in d.items():
        if k.lower() == key.lower():
            if not take_first and found_value:
                raise ValueError('Duplicate case insensitive keys')
            value = v
            found_value = True
            if take_first:
                break
    if not found_value:
        return default
    return value


def check_callback_arg(callback, name):
    """Raise TypeError if callback is not callable

    :param callback: callback to check
    :param name: Name to include in exception text
    :raises TypeError:

    """
    if not callable(callback):
        raise TypeError('{} must be callable, but got {!r}'.format(name,
            callback))


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

        :param PaperDocRequestAccessDetails val:
        :rtype: EventDetails
        """
    return cls('paper_doc_request_access_details', val)


def get_weight_procent(formula):
    """
    This converts a formula to a dictionary with element : weightprocent
    example converts 'Be24W2' to {'Be': , 'W' : }, also BeW to {'Be' : , 'W' : }
    :params: formula: string
    :returns: a dict, element : weightprocent

    # Todo alternative with structuredata
    """
    pass


@classmethod
def write_str(cls, opc_sync: bool, total_size: int, context: str
    ) ->'IoTransferEventArgs':
    """Creates new IoTransferEventArgs of write string

		:param opc_sync: defines if the command is OPC-synchronised
		:param total_size: size of the data to write
		:param context: SCPI command write. It is truncated to maximum of 100 characters.
		:return: IoTransferEventArgs object of a write string operation."""
    obj = cls(False, opc_sync, total_size, context)
    obj.binary = False
    return obj


def __call__(cls, value, names=None, module=None, type=None):
    """Either returns an existing member, or creates a new enum class.

        This method is used both when an enum class is given a value to match
        to an enumeration member (i.e. Color(3)) and for the functional API
        (i.e. Color = Enum('Color', names='red green blue')).

        When used for the functional API: `module`, if set, will be stored in
        the new class' __module__ attribute; `type`, if set, will be mixed in
        as the first base class.

        Note: if `module` is not set this routine will attempt to discover the
        calling module by walking the frame stack; if this is unsuccessful
        the resulting class will not be pickleable.

        """
    if names is None:
        return cls.__new__(cls, value)
    return cls._create_(value, names, module=module, type=type)


def prefix(tx_addresses, outputs, occurence):
    """
    Pretty print with texttable
    Break line when several values in a cell
    Handle Total line in case of multi-output txs
    """
    if tx_addresses == 'Total':
        return '\n'
    if not outputs:
        return ''
    return '\n' if occurence + len(outputs) > 1 else ''


def bet_sizing_coherence(df_line, matrix_len):
    """
    Evaluates the bet sizing coherence of an altered Kelly DataFrame (doubled columns with shifted values).

    This method was made to be used on a DataFrame with '.apply()'.

    :param df_line: (pandas Series) which is a horizontal line of an altered Kelly DataFrame
    :param matrix_len: (int) original Kelly DataFrame length

    :return: returns a coherent bet sizing line
    :rtype: pandas Series
    """
    for i in range(0, matrix_len):
        if df_line.values[i] > df_line.values[i + matrix_len]:
            df_line.values[i] = df_line.values[i + matrix_len]
        if i > 0:
            if df_line.values[i - 1] > df_line.values[i]:
                df_line.values[i - 1] = df_line.values[i]
    return df_line


@classmethod
def is_applicable(cls) ->bool:
    """
        Checks if this procedure is applicable to the current system.
        NOOP Procedure is always applicable
        :return: True if applicable, else False
        """
    return True


def face_select_linked():
    """Select linked faces

    """
    pass


def ik_add(with_targets: bool=True):
    """Add IK Constraint to the active Bone

    :param with_targets: With Targets, Assign IK Constraint with targets derived from the select bones/objects
    :type with_targets: bool
    """
    pass


def say_hello(to):
    """Say hello to somebody"""
    return f'Hello {to}!'


def constraints_copy():
    """Copy constraints to other selected objects

    """
    pass


@classmethod
def is_key(cls, result):
    """Return ``True`` if result is a key object."""
    raise NotImplementedError


@classmethod
def match_header(cls, header):
    """
        This is an abstract type that implements the shared functionality of
        the ASCII and Binary Table HDU types, which should be used instead of
        this.
        """
    raise NotImplementedError


@classmethod
def get_option_names(cls):
    """Get names of all options."""
    return list(map(lambda x: x.name, cls.get_options()))


def parse_period_arg(arg: str) ->int:
    """
    Makes sure that a period argument is a valid postive integer.
    """
    try:
        period = int(arg)
    except ValueError:
        raise ValueError('Period must be an integer')
    if period < 0:
        raise ValueError('Period cannot be negative')
    return period


@classmethod
def get_connectors(cls, atom):
    """Returns number of possible attachments to a given element"""
    atnum = cls.get_atnum(atom)
    return int(cls.ptable[atom.atnum][-2])


def get_relationship_targets(item_ids, relationships, id2rec):
    """Get item ID set of item IDs in a relationship target set."""
    reltgt_objs_all = set()
    for goid in item_ids:
        obj = id2rec[goid]
        for reltype, reltgt_objs_cur in obj.relationship.items():
            if relationships is True or reltype in relationships:
                reltgt_objs_all.update(reltgt_objs_cur)
    return reltgt_objs_all


def values():
    """
        Return list of user objects providing IPropertiedUser.
        """


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 merge_metadata(cls):
    """
    Merge all the __metadata__ dicts in a class's hierarchy

    keys that do not begin with '_' will be inherited.

    keys that begin with '_' will only apply to the object that defines them.

    """
    cls_meta = cls.__dict__.get('__metadata__', {})
    meta = {}
    for base in cls.__bases__:
        meta.update(getattr(base, '__metadata__', {}))
    for key in list(meta.keys()):
        if key.startswith('_'):
            del meta[key]
    meta.update(cls_meta)
    return meta


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

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

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


def _check_not_tuple_of_2_elements(obj, obj_name='obj'):
    """Check object is not tuple or does not have 2 elements."""
    if not isinstance(obj, tuple) or len(obj) != 2:
        raise TypeError('%s must be a tuple of 2 elements.' % obj_name)


def conc_frame_yield_drift(fye, youngs_steel, av_bay_length, av_beam_depth):
    """
    Yield drift of a concrete frame from DDBD (Priestley et al. (2007)
    :param fye: Effective yeild strength of reinforcing steel
    :param youngs_steel: Young's modulus of reinforcing steel
    :param av_bay_length: Average bay length
    :param av_beam_depth: average beam depth
    :return:
    """
    return 0.5 * fye / youngs_steel * (av_bay_length / av_beam_depth)


@classmethod
def _get_ax_layer(cls, ax, primary=True):
    """get left (primary) or right (secondary) axes"""
    if primary:
        return getattr(ax, 'left_ax', ax)
    else:
        return getattr(ax, 'right_ax', ax)


def enum_value(enum_str):
    """Strip chars around enum value str.
    :param str enum_str: Enum value.
    """
    return enum_str.strip(" '").lower()


def getNewerVersion(oldFile, newFile):
    """Check two files to determine which is newer

       :param str oldFile: one of the two similar files
       :param str newFile: one of the two similar files

       :return: the name of newer file
    """
    if oldFile.split('.')[4] > newFile.split('.')[4]:
        return oldFile
    else:
        return newFile


def is_mutating(status):
    """Determines if the statement is mutating based on the status."""
    if not status:
        return False
    mutating = set(['insert', 'update', 'delete'])
    return status.split(None, 1)[0].lower() in mutating


def int_to_32bit_array(val):
    """Converts an integer to 32 bit bytearray

    :param val: the value to convert to bytes
    :type val: int
    :rtype: bytearray
    """
    value = val
    bytes = bytearray()
    for i in range(4):
        bytes.insert(0, value & 255)
        value >>= 8
    return str(bytes)


def remove_node(node_var, breakline=True):
    """Query for removal of a node (with side-effects)."""
    return 'DETACH DELETE {}\n'.format(node_var)


def shape(input):
    """Return the shape of the tensor.

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

    Returns
    -------
    tuple of int
        The tensor shape.
    """
    pass


def __call__():
    """
        Weak references are callable objects. Calling them returns
        the object they reference if it is still available, otherwise
        it returns ``None``.
        """


def get_further_config_instructions(project_name):
    """Gets the 'Further configuration' instructions that apply to all types of
    project. These will be displayed before project-specific other further
    configuration instructions."""
    return [
        'Add configuration settings outside of version control in ~/.virtualenvs/{site}/postactivate'
        .format(site=project_name),
        "Run 'workon {site}' each time you edit ~/.virtualenvs/{site}/postactivate"
        .format(site=project_name)]


def _update_children(nodes):
    """ Fills the children property of joints.

    :param nodes: Dictionary with skeleton hierarchy.
    :type nodes: dict
    """
    for node, properties in nodes.items():
        parent = properties['parent']
        try:
            p_props = nodes[parent]
        except KeyError:
            if not parent:
                continue
            raise ValueError(
                'ERROR: Parent of {} cannot be found in the hierarchy definition!'
                .format(node))
        p_children = p_props['children']
        p_children.append(node)
        p_props.update({'children': p_children})


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


def redis_stream_id_subtract_one(message_id):
    """Subtract one from the message ID

    This is useful when we need to xread() events inclusive of the given ID,
    rather than exclusive of the given ID (which is the sensible default).
    Only use when one can tolerate an exceptionally slim risk of grabbing extra events.
    """
    milliseconds, n = map(int, message_id.split('-'))
    if n > 0:
        n = n - 1
    elif milliseconds > 0:
        milliseconds = milliseconds - 1
        n = 9999
    else:
        return message_id
    return '{:13d}-{}'.format(milliseconds, n)


def subgraph(G, nbunch):
    """Return the subgraph induced on nodes in nbunch.

        Parameters
        ----------
        G : graph
           A DyNetx graph

        nbunch : list, iterable
           A container of nodes that will be iterated through once (thus
           it should be an iterator or be iterable).  Each element of the
           container should be a valid node type: any hashable type except
           None.  If nbunch is None, return all edges data in the graph.
           Nodes in nbunch that are not in the graph will be (quietly)
           ignored.

    """
    return G.subgraph(nbunch)


def file_sorting_key(filename):
    """
    Extract a key for a filename sort, putting JPEGs before everything else.
    """
    extension = filename.lower()[filename.rfind('.') + 1:]
    key = 0 if extension in ('jpg', 'jpeg') else 1
    return key, filename


def _read_header_byte_data(header_structure):
    """ Reads the byte data from the data file for a PDS4 Header.

    Determines, from the structure's meta data, the relevant start and stop bytes in the data file prior to
    reading.

    Parameters
    ----------
    header_structure : HeaderStructure
        The PDS4 Header data structure for which the byte data needs to be read. Should have been
        initialized via `HeaderStructure.from_file` method, or contain the required meta data.

    Returns
    -------
    str or bytes
        The exact byte data for the header.
    """
    from .core import read_byte_data
    meta_data = header_structure.meta_data
    start_byte = meta_data['offset']
    stop_byte = start_byte + meta_data['object_length']
    return read_byte_data(header_structure.parent_filename, start_byte,
        stop_byte)


def package(qualified_name):
    """Return the enclosing package name where qualified_name is located.

    `qualified_name` can be a module inside the package or even an object
    inside the module. If a package name itself is provided it is returned.

    """
    try:
        module = __import__(qualified_name, fromlist=[''])
    except ImportError:
        if '.' in qualified_name:
            qualified_name, attr_name = qualified_name.rsplit('.', 1)
            module = __import__(qualified_name, fromlist=[attr_name])
        else:
            raise
    if module.__package__:
        return module.__package__
    else:
        assert module.__name__ == qualified_name
        return qualified_name