def plot(self, pts_per_edge, color=None, ax=None):
    if (ax is None):
        ax = _plot_helpers.new_axis()
    _plot_helpers.add_patch(ax, color, pts_per_edge, *self._edges)
    return ax

Plot the current curved polygon.

Args:
pts_per_edge (int): Number of points to plot per curved edge.
color (Optional[Tuple[float, float, float]]): Color as RGB profile.
ax (Optional[matplotlib.artist.Artist]): matplotlib axis object
to add plot to.

Returns:
matplotlib.artist.Artist: The axis containing the plot. This
may be a newly created axis.


def _as_document(self, partition):

        doc = super(self.__class__, self)._as_document(partition)

        doc['time_coverage'] = partition.time_coverage
        return doc

Converts partition to document indexed by to FTS index.

Args:
partition (orm.Partition): partition to convert.

Returns:
dict with structure matches to BasePartitionIndex._schema.


def annotate(self, framedata):

        for artist in self.annotation_artists:
            artist.remove()
        self.annotation_artists = []
        for annotation in self.annotations:
            if annotation[2] > framedata:
                return
            if annotation[2] == framedata:
                pos = annotation[0:2]
                shape = self.annotations_default['shape']
                color = self.annotations_default['color']
                size = self.annotations_default['size']
                line = self.annotations_default['line']
                if len(annotation) > 3:
                    shape = annotation[3].get('shape', shape)
                    color = annotation[3].get('color', color)
                    size = annotation[3].get('size', size)
                    line = annotation[3].get('line', line)
                if shape == 'CIRC' and hasattr(size, '__len__'):
                    size = 30

                if not hasattr(color, '__len__'):
                    color = (color,) * 3

                if shape == 'RECT':
                    patch = patches.Rectangle((pos[0] - size[0]
                                               pos[1] - size[1]
                                              size[0], size[1], fill=False,
                                              lw=line, fc='none', ec=color)
                elif shape == 'CIRC':
                    patch = patches.CirclePolygon(pos, radius=size, fc='none',
                                                  ec=color, lw=line)
                self.annotation_artists.append(patch)
                self.axes_processed.add_artist(self.annotation_artists[-1])

Annotates the processed axis with given annotations for
the provided framedata.

Args:
framedata: The current frame number.


def update_user_flags(self, user, claims):

        if settings.GROUPS_CLAIM is not None:
            if settings.GROUPS_CLAIM in claims:
                access_token_groups = claims[settings.GROUPS_CLAIM]
                if not isinstance(access_token_groups, list):
                    access_token_groups = [access_token_groups, ]
            else:
                logger.debug("The configured group claim was not found in the access token")
                access_token_groups = []

            for flag, group in settings.GROUP_TO_FLAG_MAPPING.items():
                if hasattr(user, flag):
                    if group in access_token_groups:
                        value = True
                    else:
                        value = False
                    setattr(user, flag, value)
                    logger.debug("Attribute '{}' for user '{}' was set to '{}'.".format(user, flag, value))
                else:
                    msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                    raise ImproperlyConfigured(msg.format(flag))

        for field, claim in settings.BOOLEAN_CLAIM_MAPPING.items():
            if hasattr(user, field):
                bool_val = False
                if claim in claims and str(claims[claim]).lower() in ['y', 'yes', 't', 'true', 'on', '1']:
                    bool_val = True
                setattr(user, field, bool_val)
                logger.debug('Attribute "{}" for user "{}" was set to "{}".'.format(user, field, bool_val))
            else:
                msg = "User model has no field named '{}'. Check ADFS boolean claims mapping."
                raise ImproperlyConfigured(msg.format(field))

Updates user boolean attributes based on the BOOLEAN_CLAIM_MAPPING setting.

Args:
user (django.contrib.auth.models.User): User model instance
claims (dict): Claims from the access token


def _fill_parameters(self):

        self._parameters = self._config.get('parameters', {})
        self._fill_defaults()

        for k in self._parameters.keys():
            try:
                if self._parameters[k].startswith(self.SSM) and self._parameters[k].endswith(']'):
                    parts = self._parameters[k].split(':')
                    tmp = parts[1].replace(']', '')
                    val = self._get_ssm_parameter(tmp)
                    if val:
                        self._parameters[k] = val
                    else:
                        logging.error('SSM parameter {} not found'.format(tmp))
                        return False
                elif self._parameters[k] == self.ASK:
                    val = None
                    a1 = '__x___'
                    a2 = '__y___'
                    prompt1 = "Enter value for '{}': ".format(k)
                    prompt2 = "Confirm value for '{}': ".format(k)
                    while a1 != a2:
                        a1 = getpass.getpass(prompt=prompt1)
                        a2 = getpass.getpass(prompt=prompt2)
                        if a1 == a2:
                            val = a1
                        else:
                            print('values do not match, try again')
                    self._parameters[k] = val
            except:
                pass

        return True

Fill in the _parameters dict from the properties file.

Args:
None

Returns:
True

Todo:
Figure out what could go wrong and at least acknowledge the the
fact that Murphy was an optimist.


def __init__(self, file_path):

        if file_path is not None:
            if not os.path.isfile(file_path):
                raise ValueError(
                    'Cannot find an stat file at {}'.format(file_path))
            if not file_path.lower().endswith('stat'):
                raise TypeError('{} is not an .stat file.'.format(file_path))
            self._file_path = os.path.normpath(file_path)

        self._winter_des_day_dict = {}
        self._summer_des_day_dict = {}
        self._monthly_wind_dirs = []

        if file_path is not None:
            self._import_data()

Initalize the class.

Args:
file_path: Address to a local .stat file.


def get_args(get_item):
    if (not isinstance(get_item, dict)):
        raise ContextError('envGet must contain a list of dicts.')
    env = get_item.get('env', None)
    if (not env):
        raise KeyNotInContextError('context envGet[env] must exist in context for envGet.')
    key = get_item.get('key', None)
    if (not key):
        raise KeyNotInContextError('context envGet[key] must exist in context for envGet.')
    if ('default' in get_item):
        has_default = True
        default = get_item['default']
    else:
        has_default = False
        default = None
    return (env, key, has_default, default)

Parse env, key, default out of input dict.

Args:
get_item: dict. contains keys env/key/default

Returns:
(env, key, has_default, default) tuple, where
env: str. env var name.
key: str. save env value to this context key.
has_default: bool. True if default specified.
default: the value of default, if specified.

Raises:
ContextError: envGet is not a list of dicts.
KeyNotInContextError: If env or key not found in get_config.


def profile_update(self, profile):

        if profile.get('install_json') is None:
            print(
                '{}{}Missing install_json parameter for profile {}.'.format(
                    c.Style.BRIGHT, c.Fore.YELLOW, profile.get('profile_name')
                )
            )

        self.profile_update_args_v2(profile)

        self.profile_update_args_v3(profile)

        self.profile_update_schema(profile)

Update an existing profile with new parameters or remove deprecated parameters.

Args:
profile (dict): The dictionary containting the profile settings.


def __init__(self, filename=None, global_env=None, error_formatter=None):
    self._filename = filename
    self._global_env = global_env
    self._local_env = {'_curr_module': None}
    error_formatter = error_formatter or stl.error_formatter.PrettyErrorFormatter()
    self.lexer_error_handler = stl.error_handler.LexerErrorHandler(error_formatter)
    self.parser_error_handler = stl.error_handler.ParserErrorHandler(error_formatter)
    self.lexer = stl.lexer.StlLexer(self._filename, self.lexer_error_handler)
    self.parser = ply.yacc.yacc(module=self)

Creates an StlParser with an StlLexer.

Args:
filename: The string to use in debug output. The parser does not attempt
to read from |filename|. To pass data to parse, use StlParser.parse
global_env: The global environment dict to be updated during parsing.


def get_osdp(self, id_or_uri):

        uri = self._client.build_subresource_uri(resource_id_or_uri=id_or_uri, subresource_path="osdp")
        return self._client.get(uri)

Retrieves facts about Server Profiles and Server Profile Templates that are using Deployment Plan based on the ID or URI provided.

Args:
id_or_uri: ID or URI of the Deployment Plan.

Returns:
dict: Server Profiles and Server Profile Templates


def info(self, **kwargs):

        path = self._get_id_path('info')

        response = self._GET(path, kwargs)
        self._set_attrs_to_values(response)
        return response

Get the basic movie information for a specific movie id.

Args:
language: (optional) ISO 639-1 code.
append_to_response: (optional) Comma separated, any movie method.

Returns:
A dict representation of the JSON returned from the API.


def _DocPackageFromTop(self, packages, showprivate=False, showinh=False):
    appIndex = ''
    if (not isinstance(packages, list)):
        packages = [packages]
    if os.path.exists('content'):
        shutil.rmtree('content')
    os.makedirs('content')
    appIndex += ('\n\n.. toctree::\n   :maxdepth: 5\n   :hidden:\n   :caption: %s:\n\n' % 'API Index')
    for i in range(len(packages)):
        package = packages[i]
        try:
            name = package.__displayname__
        except AttributeError:
            name = package.__name__
        path = ('content/%s' % package.__name__)
        if os.path.exists(path):
            shutil.rmtree(path)
        os.makedirs(path)
        meta = ('About %s\n%s\n' % (name, ('=' * len(('About ' + name)))))
        author = getattr(package, '__author__', None)
        license = getattr(package, '__license__', None)
        copyright = getattr(package, '__copyright__', None)
        version = getattr(package, '__version__', None)
        if author:
            meta += ('\n* Author: %s' % author)
        if license:
            meta += ('\n* License: %s' % license)
        if copyright:
            meta += ('\n* Copyright: %s' % copyright)
        if version:
            meta += ('\n* Version: %s' % version)
        about = ('%s/%s' % (path, 'index.rst'))
        this_toc = ('\n\n.. toctree::\n   :maxdepth: 5\n   :caption: %s:\n' % name)
        this_toc += self._MakePackagePages(package, showprivate=showprivate, showinh=showinh)
        this_toc = this_toc.replace(('%s/' % path), '')
        with open(about, 'w') as f:
            f.write(('%s\n\n' % meta))
            if package.__doc__:
                f.write(package.__doc__)
            f.write(this_toc)
        appIndex += ('\n   %s' % about)
    return appIndex

Generates all of the documentation for given packages and
appends new tocrees to the index. All documentation pages will be under the
set relative path.

Args:
packages (list(module)): A package or list of packages that contain submodules to document
showprivate (bool): A flag for whether or not to display private members

Returns:
str: The new content to append to the index


def nac_v(msg):

    tc = typecode(msg)

    if tc != 19:
        raise RuntimeError("%s: Not an airborne velocity message, expecting TC = 19" % msg)

    msgbin = common.hex2bin(msg)
    NACv = common.bin2int(msgbin[42:45])

    try:
        HFOMr = uncertainty.NACv[NACv]['HFOMr']
        VFOMr = uncertainty.NACv[NACv]['VFOMr']
    except KeyError:
        HFOMr, VFOMr = uncertainty.NA, uncertainty.NA

    return HFOMr, VFOMr

Calculate NACv, Navigation Accuracy Category - Velocity

Args:
msg (string): 28 bytes hexadecimal message string, TC = 19

Returns:
int or string: 95% horizontal accuracy bounds for velocity, Horizontal Figure of Merit
int or string: 95% vertical accuracy bounds for velocity, Vertical Figure of Merit


def step(self, thumb=False):
    method = self._dll.JLINKARM_Step
    if thumb:
        method = self._dll.JLINKARM_StepComposite
    res = method()
    if (res != 0):
        raise errors.JLinkException('Failed to step over instruction.')
    return None

Executes a single step.

Steps even if there is a breakpoint.

Args:
self (JLink): the ``JLink`` instance
thumb (bool): boolean indicating if to step in thumb mode

Returns:
``None``

Raises:
JLinkException: on error


def Process(self, parser_mediator, registry_key, **kwargs):

    if registry_key is None:
      raise ValueError('Windows Registry key is not set.')

    super(WindowsRegistryPlugin, self).Process(parser_mediator, **kwargs)

    self.ExtractEvents(parser_mediator, registry_key, **kwargs)

Processes a Windows Registry key or value.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.

Raises:
ValueError: If the Windows Registry key is not set.


def introduce_errors(s, corruption_rate=0.003, infill_marker='|?|', max_infill_len=8):
    num_errors = 0
    ret = []
    operations = ['delete', 'insert', 'replace', 'transpose']
    if max_infill_len:
        operations.append('infill')
    pos = 0
    while (pos < len(s)):
        if (random.random() >= corruption_rate):
            ret.append(s[pos])
            pos += 1
            continue
        num_errors += 1
        operation = operations[random.randint(0, (len(operations) - 1))]
        if (operation == 'delete'):
            pos += 1
        elif (operation == 'insert'):
            ret.append(s[random.randint(0, (len(s) - 1))])
        elif (operation == 'replace'):
            ret.append(s[random.randint(0, (len(s) - 1))])
            pos += 1
        elif (operation == 'transpose'):
            ret.append((s[(pos + 1)] if ((pos + 1) < len(s)) else ''))
            ret.append(s[pos])
            pos += 2
        else:
            assert (operation == 'infill')
            ret.append(infill_marker)
            pos += random.randint(0, max_infill_len)
    return (''.join(ret), num_errors)

Artificially add spelling errors and infill markers.

This function should be applied to the inputs of a correction model.

The artificial errors are particularly useful to train a network to
correct spelling when the training data does not contain many
natural errors.

Also replaces some substrings with an "infill" marker.  e.g.
"the fat cat sat on the mat" -> "the fat ca??? the mat"

This causes the trained model to learn infilling (predicting what text
to insert at the current cursor position).

Args:
s: a string (the uncorrupted text)
corruption_rate: a floating point value.  Probability of introducing an
error/infill at each character.
infill_marker: a string
max_infill_len: an optional integer - maximum number of characters to remove
and replace by an infill marker.  None means no infilling.

Returns:
a string


def get_default_model_and_revision(targeted_task: Dict, framework: Optional[str], task_options: Optional[Any]) -> Tuple[str, str]:
    if is_torch_available() and (not is_tf_available()):
        framework = 'pt'
    elif is_tf_available() and (not is_torch_available()):
        framework = 'tf'
    defaults = targeted_task['default']
    if task_options:
        if task_options not in defaults:
            raise ValueError(f'The task does not provide any default models for options {task_options}')
        default_models = defaults[task_options]['model']
    elif 'model' in defaults:
        default_models = targeted_task['default']['model']
    else:
        raise ValueError('The task defaults can\'t be correctly selected. You probably meant "translation_XX_to_YY"')
    if framework is None:
        framework = 'pt'
    return default_models[framework]

Select a default model to use for a given task. Defaults to pytorch if ambiguous.

Args:
targeted_task (`Dict`):
Dictionary representing the given task, that should contain default models

framework (`str`, None)
"pt", "tf" or None, representing a specific framework if it was specified, or None if we don't know yet.

task_options (`Any`, None)
Any further value required by the task to get fully specified, for instance (SRC, TGT) languages for
translation task.

Returns

Tuple:
- `str` The model string representing the default model for this pipeline.
- `str` The revision of the model.


def configure(self, commands):
    try:
        self.node.config(commands)
        return True
    except (CommandError, ConnectionError):
        return False

Sends the commands list to the node in config mode

This method performs configuration the node using the array of
commands specified.   This method wraps the configuration commands
in a try/except block and stores any exceptions in the error
property.

Note:
If the return from this method is False, use the error property
to investigate the exception

Args:
commands (list): A list of commands to be sent to the node in
config mode

Returns:
True if the commands are executed without exception otherwise
False is returned


def _get_mpr_table(self, connection, partition):
    logger.debug('Looking for materialized view of the partition.\n    partition: {}'.format(partition.name))
    foreign_table = partition.vid
    view_table = '{}_v'.format(foreign_table)
    view_exists = self._relation_exists(connection, view_table)
    if view_exists:
        logger.debug('Materialized view of the partition found.\n    partition: {}, view: {}'.format(partition.name, view_table))
        return view_table
    logger.debug('Looking for foreign table of the partition.\n    partition: {}'.format(partition.name))
    foreign_exists = self._relation_exists(connection, foreign_table)
    if foreign_exists:
        logger.debug('Foreign table of the partition found.\n    partition: {}, foreign table: {}'.format(partition.name, foreign_table))
        return foreign_table
    raise MissingTableError('postgres database does not have table for {} partition.'.format(partition.vid))

Returns name of the postgres table who stores mpr data.

Args:
connection: connection to postgres db who stores mpr data.
partition (orm.Partition):

Returns:
str:

Raises:
MissingTableError: if partition table not found in the db.


def _create_route(self, env, item):
    if (item.name in env):
        if isinstance(env[item.name], ApiRoutesByVersion):
            if (item.version in env[item.name].at_version):
                existing_dt = env[item.name].at_version[item.version]
                raise InvalidSpec(('Route %s at version %d already defined (%s:%d).' % (quote(item.name), item.version, existing_dt._ast_node.path, existing_dt._ast_node.lineno)), item.lineno, item.path)
        else:
            existing_dt = env[item.name]
            raise InvalidSpec(('Symbol %s already defined (%s:%d).' % (quote(item.name), existing_dt._ast_node.path, existing_dt._ast_node.lineno)), item.lineno, item.path)
    else:
        env[item.name] = ApiRoutesByVersion()
    route = ApiRoute(name=item.name, version=item.version, ast_node=item)
    env[route.name].at_version[route.version] = route
    return route

Constructs a route and adds it to the environment.

Args:
env (dict): The environment of defined symbols. A new key is added
corresponding to the name of this new route.
item (AstRouteDef): Raw route definition from the parser.

Returns:
stone.api.ApiRoutesByVersion: A group of fully-defined routes indexed by versions.


def from_text_vision_configs(cls, text_config: AltCLIPTextConfig, vision_config: AltCLIPVisionConfig, **kwargs):
    return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)

Instantiate a [`AltCLIPConfig`] (or a derived class) from altclip text model configuration and altclip vision
model configuration.

Returns:
[`AltCLIPConfig`]: An instance of a configuration object


def get_theme():
    theme = None
    log.debug('COLORFGBG: %s', env.COLORFGBG)
    if env.COLORFGBG:
        (FG, _, BG) = env.COLORFGBG.partition(';')
        theme = ('dark' if (BG < '8') else 'light')
    elif (os_name == 'nt'):
        from .windows import get_color as _get_color
        color_id = _get_color('background')
        theme = ('dark' if (color_id < 8) else 'light')
    elif (os_name == 'posix'):
        if (env.TERM in ('linux', 'fbterm')):
            theme = 'dark'
        elif sys.platform.startswith('freebsd'):
            theme = 'dark'
        else:
            colors = get_color('background')
            if colors:
                colors = tuple((int(cm[:2], 16) for cm in colors))
                avg = (sum(colors) / len(colors))
                theme = ('dark' if (avg < 128) else 'light')
    log.debug('%r', theme)
    return theme

Checks system for theme information.

First checks for the environment variable COLORFGBG.
Next, queries terminal, supported on Windows and xterm, perhaps others.
See notes on get_color().

Returns:
str, None: 'dark', 'light', None if no information.


def transform_array_to_list(array):

    if (array.dtype.kind in ('u', 'i', 'f') and (~np.isfinite(array)).any()):
        transformed = array.astype('object')
        transformed[np.isnan(array)] = 'NaN'
        transformed[np.isposinf(array)] = 'Infinity'
        transformed[np.isneginf(array)] = '-Infinity'
        return transformed.tolist()
    elif (array.dtype.kind == 'O' and pd and pd.isnull(array).any()):
        transformed = array.astype('object')
        transformed[pd.isnull(array)] = 'NaN'
        return transformed.tolist()
    return array.tolist()

Transforms a NumPy array into a list of values

Args:
array (np.nadarray) : the NumPy array series to transform

Returns:
list or dict


def stage_tc_create_security_label(self, label, resource):
    sl_resource = resource.security_labels(label)
    sl_resource.http_method = 'POST'
    sl_response = sl_resource.request()
    if (sl_response.get('status') != 'Success'):
        self.log.warning('[tcex] Failed adding security label "{}" ({}).'.format(label, sl_response.get('response').text))

Add a security label to a resource.

Args:
label (str): The security label (must exit in ThreatConnect).
resource (obj): An instance of tcex resource class.


def RawBytesToScriptHash(raw):

        rawh = binascii.unhexlify(raw)
        rawhashstr = binascii.unhexlify(bytes(Crypto.Hash160(rawh), encoding='utf-8'))
        return UInt160(data=rawhashstr)

Get a hash of the provided raw bytes using the ripemd160 algorithm.

Args:
raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC'

Returns:
UInt160:


async def auth(self, username, password):
    (await self.ehlo_or_helo_if_needed())
    errors = []
    code = message = None
    for (auth, meth) in self.__class__._supported_auth_mechanisms.items():
        if (auth in self.auth_mechanisms):
            auth_func = getattr(self, meth)
            try:
                (code, message) = (await auth_func(username, password))
            except SMTPAuthenticationError as e:
                errors.append(e)
            else:
                break
    else:
        if (not errors):
            err = 'Could not find any suitable authentication mechanism.'
            errors.append(SMTPAuthenticationError((- 1), err))
        raise SMTPLoginError(errors)
    return (code, message)

Tries to authenticate user against the SMTP server.

Args:
username (str): Username to authenticate with.
password (str): Password to use along with the given ``username``.

Raises:
ConnectionResetError: If the connection with the server is
unexpectedely lost.
SMTPCommandFailedError: If the server refuses our EHLO/HELO
greeting.
SMTPLoginError: If the authentication failed (either because all
attempts failed or because there was no suitable authentication
mechanism).

Returns:
(int, str): A (code, message) 2-tuple containing the last server
response.


def _input_array(num_dims):
    formatter = '{:0%db}' % num_dims
    strings = [formatter.format(i) for i in range(2 ** num_dims)]
    return np.array(strings, dtype='S%d' % num_dims).reshape([2] * num_dims)

Creates an ndarray where each element is the binary of its linear index.

Args:
num_dims: The number of dimensions to create.

Returns:
An ndarray of shape [2] * num_dims.


def update_social_asset(self, asset_id, name, asset_type):

        self.update_asset('SOCIAL', asset_id, name, asset_type)

Updates a Social Asset
Args:
name: The name provided to the social asset
asset_type: The type provided to the social asset
asset_id:

Returns:


def _parse_address(self, val):

        ret = {
            'type': None,
            'value': None
        }

        try:

            ret['type'] = val[1]['type']

        except (KeyError, ValueError, TypeError):

                pass

        try:

            ret['value'] = val[1]['label']

        except (KeyError, ValueError, TypeError):

            ret['value'] = '\n'.join(val[3]).strip()

        try:

            self.vars['address'].append(ret)

        except AttributeError:

            self.vars['address'] = []
            self.vars['address'].append(ret)

The function for parsing the vcard address.

Args:
val (:obj:`list`): The value to parse.


def setFilter(self, search):

        if not isinstance(search, DataSearch):
            raise TypeError('The given parameter must an `qtpandas.DataSearch` object')

        self._search = search

        self.layoutAboutToBeChanged.emit()

        if self._dataFrameOriginal is not None:
            self._dataFrame = self._dataFrameOriginal
        self._dataFrameOriginal = self._dataFrame.copy()

        self._search.setDataFrame(self._dataFrame)
        searchIndex, valid = self._search.search()

        if valid:
            self._dataFrame = self._dataFrame[searchIndex]
            self.layoutChanged.emit()
        else:
            self.clearFilter()
            self.layoutChanged.emit()

        self.dataFrameChanged.emit()

Apply a filter and hide rows.

The filter must be a `DataSearch` object, which evaluates a python
expression.
If there was an error while parsing the expression, the data will remain
unfiltered.

Args:
search(qtpandas.DataSearch): data search object to use.

Raises:
TypeError: An error is raised, if the given parameter is not a
`DataSearch` object.


def genrepo(**kwargs):
    saltenv = kwargs.pop('saltenv', 'base')
    verbose = salt.utils.data.is_true(kwargs.pop('verbose', False))
    failhard = salt.utils.data.is_true(kwargs.pop('failhard', True))
    ret = {}
    successful_verbose = {}
    total_files_processed = 0
    ret['repo'] = {}
    ret['errors'] = {}
    repo_details = _get_repo_details(saltenv)
    for (root, _, files) in salt.utils.path.os_walk(repo_details.local_dest, followlinks=False):
        if re.search('[\\\\/]\\..*', root):
            log.debug('Skipping files in directory: %s', root)
            continue
        short_path = os.path.relpath(root, repo_details.local_dest)
        if (short_path == '.'):
            short_path = ''
        for name in files:
            if name.endswith('.sls'):
                total_files_processed += 1
                _repo_process_pkg_sls(os.path.join(root, name), os.path.join(short_path, name), ret, successful_verbose)
    serial = salt.payload.Serial(__opts__)
    with salt.utils.files.fopen(repo_details.winrepo_file, 'wb') as repo_cache:
        repo_cache.write(serial.dumps(ret))
    successful_count = len(successful_verbose)
    error_count = len(ret['errors'])
    if verbose:
        results = {'total': total_files_processed, 'success': successful_count, 'failed': error_count, 'success_list': successful_verbose, 'failed_list': ret['errors']}
    elif (error_count > 0):
        results = {'total': total_files_processed, 'success': successful_count, 'failed': error_count, 'failed_list': ret['errors']}
    else:
        results = {'total': total_files_processed, 'success': successful_count, 'failed': error_count}
    if ((error_count > 0) and failhard):
        raise CommandExecutionError('Error occurred while generating repo db', info=results)
    else:
        return results

Generate package metadata db based on files within the winrepo_source_dir

Kwargs:

saltenv (str): Salt environment. Default: ``base``

verbose (bool):
Return verbose data structure which includes 'success_list', a list
of all sls files and the package names contained within.
Default ``False``.

failhard (bool):
If ``True``, an error will be raised if any repo SLS files failed
to process. If ``False``, no error will be raised, and a dictionary
containing the full results will be returned.

.. note::
- Hidden directories (directories beginning with '`.`', such as
'`.git`') will be ignored.

Returns:
dict: A dictionary of the results of the command

CLI Example:

.. code-block:: bash

salt-run pkg.genrepo
salt -G 'os:windows' pkg.genrepo verbose=true failhard=false
salt -G 'os:windows' pkg.genrepo saltenv=base


def get_container_instance_group(access_token, subscription_id, resource_group, container_group_name):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', resource_group, '/providers/Microsoft.ContainerInstance/ContainerGroups/', container_group_name, '?api-version=', CONTAINER_API])
    return do_get(endpoint, access_token)

Get the JSON definition of a container group.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
container_group_name (str): Name of container instance group.

Returns:
HTTP response. JSON body of container group.


def _write_base(buf, value, bits_per_octet, end_bit=0, sign_bit=0, is_signed=False):
    if (value == 0):
        buf.append((sign_bit | end_bit))
        return 1
    num_bits = bit_length(value)
    num_octets = (num_bits
    remainder = (num_bits % bits_per_octet)
    if ((remainder != 0) or is_signed):
        num_octets += 1
    else:
        remainder = bits_per_octet
    for i in range(num_octets):
        octet = 0
        if (i == 0):
            octet |= sign_bit
        if (i == (num_octets - 1)):
            octet |= end_bit
        octet |= ((value >> (num_bits - (remainder + (bits_per_octet * i)))) & _OCTET_MASKS[bits_per_octet])
        buf.append(octet)
    return num_octets

Write a field to the provided buffer.

Args:
buf (Sequence): The buffer into which the UInt will be written
in the form of integer octets.
value (int): The value to write as a UInt.
bits_per_octet (int): The number of value bits (i.e. exclusive of the end bit, but
inclusive of the sign bit, if applicable) per octet.
end_bit (Optional[int]): The end bit mask.
sign_bit (Optional[int]): The sign bit mask.

Returns:
int: The number of octets written.


def _make_inc_temp(self, suffix='', prefix='', directory_name='/tmp/ray'):
    directory_name = os.path.expanduser(directory_name)
    index = self._incremental_dict[(suffix, prefix, directory_name)]
    while (index < tempfile.TMP_MAX):
        if (index == 0):
            filename = os.path.join(directory_name, (prefix + suffix))
        else:
            filename = os.path.join(directory_name, (((prefix + '.') + str(index)) + suffix))
        index += 1
        if (not os.path.exists(filename)):
            self._incremental_dict[(suffix, prefix, directory_name)] = index
            return filename
    raise FileExistsError(errno.EEXIST, 'No usable temporary filename found')

Return a incremental temporary file name. The file is not created.

Args:
suffix (str): The suffix of the temp file.
prefix (str): The prefix of the temp file.
directory_name (str) : The base directory of the temp file.

Returns:
A string of file name. If there existing a file having
the same name, the returned name will look like
"{directory_name}/{prefix}.{unique_index}{suffix}"


def __write_error(self, status_code, error_message=None):

    if error_message is None:
      error_message = httplib.responses[status_code]
    status = '%d %s' % (status_code, httplib.responses[status_code])
    message = EndpointsErrorMessage(
        state=EndpointsErrorMessage.State.APPLICATION_ERROR,
        error_message=error_message)
    return status, self.__PROTOJSON.encode_message(message)

Return the HTTP status line and body for a given error code and message.

Args:
status_code: HTTP status code to be returned.
error_message: Error message to be returned.

Returns:
Tuple (http_status, body):
http_status: HTTP status line, e.g. 200 OK.
body: Body of the HTTP request.


def double_sha256(ba):
    d1 = hashlib.sha256(ba)
    d2 = hashlib.sha256()
    d1.hexdigest()
    d2.update(d1.digest())
    return d2.hexdigest()

Perform two SHA256 operations on the input.

Args:
ba (bytes): data to hash.

Returns:
str: hash as a double digit hex string.


def exhaust(fn, transform=None, *args, **kwargs):
    while True:
        iterRes = fn(*args, **kwargs)
        if iterRes:
            for item in (transform(iterRes) if transform else iterRes):
                (yield item)
        else:
            break

Repeatedly call a function, starting with init, until false-y, yielding each item in turn.

The ``transform`` parameter can be used to map a collection to another format, for example iterating over a
:class:`dict` by value rather than key.

Use with state-synced functions to retrieve all results.

Args:
fn (method): function to call
transform (method): secondary function to convert result into an iterable
args (list): positional arguments to pass to ``fn``
kwargs (dict): keyword arguments to pass to ``fn``

Returns:
generator: generator of objects produced from the method


def run(self, verbose=True):
    self.results.clear()
    for analysis_group in self.config.analysis_groups:
        if analysis_group.providers:
            for provider in analysis_group.providers:
                logger.info('Run provider %s', provider.identifier)
                provider.run()
                for checker in analysis_group.checkers:
                    result = self._get_checker_result(analysis_group, checker, provider)
                    self.results.append(result)
                    analysis_group.results.append(result)
                    if verbose:
                        result.print()
        else:
            for checker in analysis_group.checkers:
                result = self._get_checker_result(analysis_group, checker, nd='no-data-')
                self.results.append(result)
                analysis_group.results.append(result)
                if verbose:
                    result.print()

Run the analysis.

Generate data from each provider, then check these data with every
checker, and store the analysis results.

Args:
verbose (bool): whether to immediately print the results or not.


def log_sinkhorn_iterations(log_cost_matrix: torch.Tensor, log_source_distribution: torch.Tensor, log_target_distribution: torch.Tensor, num_iterations: int) -> torch.Tensor:
    log_u_scaling = torch.zeros_like(log_source_distribution)
    log_v_scaling = torch.zeros_like(log_target_distribution)
    for _ in range(num_iterations):
        log_u_scaling = log_source_distribution - torch.logsumexp(log_cost_matrix + log_v_scaling.unsqueeze(1), dim=2)
        log_v_scaling = log_target_distribution - torch.logsumexp(log_cost_matrix + log_u_scaling.unsqueeze(2), dim=1)
    return log_cost_matrix + log_u_scaling.unsqueeze(2) + log_v_scaling.unsqueeze(1)

Perform Sinkhorn Normalization in Log-space for stability

Args:
log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`):
Logarithm of the cost matrix.
log_source_distribution (`torch.Tensor` of shape `(batch_size, num_rows)`):
Logarithm of the source distribution.
log_target_distribution (`torch.Tensor` of shape `(batch_size, num_columns)`):
Logarithm of the target distribution.

Returns:
log_cost_matrix (`torch.Tensor` of shape `(batch_size, num_rows, num_columns)`): Logarithm of the optimal
transport matrix.


def VerifyStructure(self, parser_mediator, line):
    self._line_structures = self.LINE_STRUCTURES
    self._day_of_month = None
    self._month = None
    self._year = None
    if (self._SIGNATURE in line):
        return True
    return False

Verify that this file is an IIS log file.

Args:
parser_mediator (ParserMediator): mediates interactions between
parsers and other components, such as storage and dfvfs.
line (str): line from a text file.

Returns:
bool: True if the line was successfully parsed.


def delete_resource_view(self, resource_view):
    if isinstance(resource_view, str):
        if (is_valid_uuid(resource_view) is False):
            raise HDXError(('%s is not a valid resource view id!' % resource_view))
        resource_view = ResourceView({'id': resource_view}, configuration=self.configuration)
    else:
        resource_view = self._get_resource_view(resource_view)
        if ('id' not in resource_view):
            found = False
            title = resource_view.get('title')
            for rv in self.get_resource_views():
                if (resource_view['title'] == rv['title']):
                    resource_view = rv
                    found = True
                    break
            if (not found):
                raise HDXError(('No resource views have title %s in this resource!' % title))
    resource_view.delete_from_hdx()

Delete a resource view from the resource and HDX

Args:
resource_view (Union[ResourceView,Dict,str]): Either a resource view id or resource view metadata either from a ResourceView object or a dictionary

Returns:
None


def get_device_ids(mesh: layout_lib.Mesh, client_id: Optional[int]=None) -> List[int]:
    if mesh.device_type() != _TPU_DEVICE_TYPE:
        raise ValueError('The mesh must be a TPU mesh')
    if client_id is None or client_id == config.client_id():
        return mesh.local_device_ids()
    raise NotImplementedError("Looking up other clients' device IDs is not supported")

Returns the device IDs of all TPU cores local to the given client.

A device ID is a non-negative integer that uniquely identifies a device in the
mesh. For example, for a 2x2 mesh ('x', 'y'), this function returns a
permutation of [0, 1, 2, 3].

Note that device IDs and device locations are equivalent. The former is a
linearization of the latter along mesh dimensions.

Args:
mesh: A TPU mesh.
client_id: Optional; A DTensor client ID. If empty, query this client.


def _ParseFilterOptions(self, options):

    self._event_filter_expression = self.ParseStringOption(options, 'filter')
    if self._event_filter_expression:
      self._event_filter = event_filter.EventObjectFilter()

      try:
        self._event_filter.CompileFilter(self._event_filter_expression)
      except errors.ParseError as exception:
        raise errors.BadConfigOption((
            'Unable to compile filter expression with error: '
            '{0!s}').format(exception))

    time_slice_event_time_string = getattr(options, 'slice', None)
    time_slice_duration = getattr(options, 'slice_size', 5)
    self._use_time_slicer = getattr(options, 'slicer', False)

    if time_slice_event_time_string and self._use_time_slicer:
      raise errors.BadConfigOption(
          'Time slice and slicer cannot be used at the same time.')

    time_slice_event_timestamp = None
    if time_slice_event_time_string:

      preferred_time_zone = self._preferred_time_zone or 'UTC'
      timezone = pytz.timezone(preferred_time_zone)
      time_slice_event_timestamp = timelib.Timestamp.FromTimeString(
          time_slice_event_time_string, timezone=timezone)
      if time_slice_event_timestamp is None:
        raise errors.BadConfigOption(
            'Unsupported time slice event date and time: {0:s}'.format(
                time_slice_event_time_string))

    if time_slice_event_timestamp is not None or self._use_time_slicer:

      self._time_slice = time_slices.TimeSlice(
          time_slice_event_timestamp, duration=time_slice_duration)

Parses the filter options.

Args:
options (argparse.Namespace): command line arguments.

Raises:
BadConfigOption: if the options are invalid.


def get_concatenated_pdf_in_memory(pdf_plans: Iterable[PdfPlan], start_recto: bool=True) -> bytes:
    writer = PdfFileWriter()
    for pdfplan in pdf_plans:
        pdfplan.add_to_writer(writer, start_recto=start_recto)
    return pdf_from_writer(writer)

Concatenates PDFs and returns them as an in-memory binary PDF.

Args:
pdf_plans: iterable of :class:`PdfPlan` objects
start_recto: start a new right-hand page for each new PDF?

Returns:
concatenated PDF, as ``bytes``


def get_text_features(self, input_ids: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, position_ids: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None) -> torch.FloatTensor:
    output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
    output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    text_outputs: BaseModelOutputWithPooling = self.text_model(input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, output_attentions=output_attentions, output_hidden_states=output_hidden_states)
    pooled_output = text_outputs.pooler_output
    return pooled_output

Returns:
text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
applying the projection layer to the pooled output of [`SiglipTextModel`].

Examples:

```python
>>> from transformers import AutoTokenizer, AutoModel
>>> import torch

>>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
>>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")

>>> # important: make sure to set padding="max_length" as that's how the model was trained
>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
>>> with torch.no_grad():
...     text_features = model.get_text_features(**inputs)
```


def _on_qosok(self, qosok_frame):
    for (name, args) in self._exchanges.items():
        self._channel.exchange_declare(exchange=name, exchange_type=args['type'], durable=args['durable'], auto_delete=args['auto_delete'], arguments=args['arguments'], passive=config.conf['passive_declares'], callback=self._on_exchange_declareok)
    for (name, args) in self._queues.items():
        self._channel.queue_declare(queue=name, durable=args['durable'], auto_delete=args['auto_delete'], exclusive=args['exclusive'], arguments=args['arguments'], passive=config.conf['passive_declares'], callback=self._on_queue_declareok)

Callback invoked when the server acknowledges the QoS settings.

Asserts or creates the exchanges and queues exist.

Args:
qosok_frame (pika.spec.Basic.Qos): The frame send from the server.


def normalize_to(self, comp, factor=1):
    scale_factor = abs(((1 / self._coeffs[self._all_comp.index(comp)]) * factor))
    self._coeffs = [(c * scale_factor) for c in self._coeffs]

Normalizes the reaction to one of the compositions.
By default, normalizes such that the composition given has a
coefficient of 1. Another factor can be specified.

Args:
comp (Composition): Composition to normalize to
factor (float): Factor to normalize to. Defaults to 1.


def get_service_health(service_id: str) -> str:
    if (DC.get_replicas(service_id) != DC.get_actual_replica(service_id)):
        health_status = 'Unhealthy'
    else:
        health_status = 'Healthy'
    return health_status

Get the health of a service using service_id.

Args:
service_id

Returns:
str, health status


async def attach_url(self, url: str, description: str=None) -> Attachment:
    return (await self._attach(url=url, description=description))

add an url as an attachment

|methcoro|

Args:
url: url you want to add
description: *optional* description for your attachment

Returns:
Attachment:

Raises:
ValueError: url must not be None
APIException


def get_signature_list(self):
    full_signature_defs = self._interpreter.GetSignatureDefs()
    for _, signature_def in full_signature_defs.items():
        signature_def['inputs'] = list(signature_def['inputs'].keys())
        signature_def['outputs'] = list(signature_def['outputs'].keys())
    return full_signature_defs

Gets the list of SignatureDefs in the model.

Example,
```
signatures = interpreter.get_signature_list()
print(signatures)

# {
#   'add': {'inputs': ['x', 'y'], 'outputs': ['output_0']}
# }

Then using the names in the signature list you can get a callable from
get_signature_runner().
```

Returns:
A list of SignatureDef details in a dictionary structure.
It is keyed on the SignatureDef method name, and the value holds
a dictionary of inputs and outputs.


async def remove(self, index=''):
    if (not (self.state == 'ready')):
        logger.debug("Trying to remove from wrong state '{}'".format(self.state))
        return
    if (index == ''):
        self.statuslog.error('Must provide index to remove')
        return
    elif (index == 'all'):
        self.queue = []
        self.update_queue()
        self.statuslog.info('Removed all songs')
        return
    indexes = index.split('-')
    self.logger.debug('Removing {}'.format(indexes))
    try:
        if (len(indexes) == 0):
            self.statuslog.error('Remove must specify an index or range')
            return
        elif (len(indexes) == 1):
            num_lower = (int(indexes[0]) - 1)
            num_upper = (num_lower + 1)
        elif (len(indexes) == 2):
            num_lower = (int(indexes[0]) - 1)
            num_upper = int(indexes[1])
        else:
            self.statuslog.error('Cannot have more than 2 indexes for remove range')
            return
    except TypeError:
        self.statuslog.error('Remove index must be a number')
        return
    except ValueError:
        self.statuslog.error('Remove index must be a number')
        return
    if ((num_lower < 0) or (num_lower >= len(self.queue)) or (num_upper > len(self.queue))):
        if (len(self.queue) == 0):
            self.statuslog.warning('No songs in queue')
        elif (len(self.queue) == 1):
            self.statuslog.error('Remove index must be 1 (only 1 song in queue)')
        else:
            self.statuslog.error('Remove index must be between 1 and {}'.format(len(self.queue)))
        return
    if (num_upper <= num_lower):
        self.statuslog.error('Second index in range must be greater than first')
        return
    lower_songname = self.queue[num_lower][1]
    for num in range(0, (num_upper - num_lower)):
        self.logger.debug('Removed {}'.format(self.queue[num_lower][1]))
        self.queue.pop(num_lower)
    if (len(indexes) == 1):
        self.statuslog.info('Removed {}'.format(lower_songname))
    else:
        self.statuslog.info('Removed songs {}-{}'.format((num_lower + 1), num_upper))
    self.update_queue()

The remove command

Args:
index (str): The index to remove, can be either a number, or a range in the for '##-##'


def upload_to_s3(context, file_obj):

    bucket = context.solid_config['bucket']
    key = context.solid_config['key']

    context.resources.s3.put_object(
        Bucket=bucket, Body=file_obj.read(), Key=key, **(context.solid_config.get('kwargs') or {})
    )
    yield Result(bucket, 'bucket')
    yield Result(key, 'key')

Upload a file to s3.

Args:
info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource.

Returns:
(str, str):
The bucket and key to which the file was uploaded.


def import_optional(mod_name):

    try:
        return import_module(mod_name)
    except ImportError:
        pass
    except Exception:
        msg = "Failed to import optional module `{}`".format(mod_name)
        log.exception(msg)

Attempt to import an optional dependency.

Silently returns None if the requested module is not available.

Args:
mod_name (str) : name of the optional module to try to import

Returns:
imported module or None, if import fails


def histogram(name, data, step=None, buckets=None, description=None):
    summary_metadata = metadata.create_summary_metadata(display_name=None, description=description)
    summary_scope = (getattr(tf.summary.experimental, 'summary_scope', None) or tf.summary.summary_scope)
    with summary_scope(name, 'histogram_summary', values=[data, buckets, step]) as (tag, _):
        tensor = _buckets(data, bucket_count=buckets)
        return tf.summary.write(tag=tag, tensor=tensor, step=step, metadata=summary_metadata)

Write a histogram summary.

Arguments:
name: A name for this summary. The summary tag used for TensorBoard will
be this name prefixed by any active name scopes.
data: A `Tensor` of any shape. Must be castable to `float64`.
step: Explicit `int64`-castable monotonic step value for this summary. If
omitted, this defaults to `tf.summary.experimental.get_step()`, which must
not be None.
buckets: Optional positive `int`. The output will have this
many buckets, except in two edge cases. If there is no data, then
there are no buckets. If there is data but all points have the
same value, then there is one bucket whose left and right
endpoints are the same.
description: Optional long-form description for this summary, as a
constant `str`. Markdown is supported. Defaults to empty.

Returns:
True on success, or false if no summary was emitted because no default
summary writer was available.

Raises:
ValueError: if a default writer exists, but no step was provided and
`tf.summary.experimental.get_step()` is None.


def __init__(self, message=None, errors=None, status=None):

        self.status = status or 200
        self.message = message
        self.errors = errors

        if self.errors and self.status == 200:
            self.status = 400

Create a response object.

Args:
message: the message object (it could be any type of object.)
errors: the errors to attach (it could be any type of object.)
status (int): the status of the response. Errors should use the
status that is the most appropriate. System failures should
set a 500.


def scatter_sub(self, sparse_delta, use_locking=False, name=None):
    if not isinstance(sparse_delta, indexed_slices.IndexedSlices):
        raise TypeError('sparse_delta is not IndexedSlices: %s' % sparse_delta)
    return gen_state_ops.scatter_sub(self._variable, sparse_delta.indices, sparse_delta.values, use_locking=use_locking, name=name)

Subtracts `tf.IndexedSlices` from this variable.

Args:
sparse_delta: `tf.IndexedSlices` to be subtracted from this variable.
use_locking: If `True`, use locking during the operation.
name: the name of the operation.

Returns:
A `Tensor` that will hold the new value of this variable after
the scattered subtraction has completed.

Raises:
TypeError: if `sparse_delta` is not an `IndexedSlices`.


def _update_linear_bucket_count(a_float, dist):
    buckets = dist.linearBuckets
    if (buckets is None):
        raise ValueError((_BAD_UNSET_BUCKETS % u'linear buckets'))
    bucket_counts = dist.bucketCounts
    num_finite_buckets = buckets.numFiniteBuckets
    if (len(bucket_counts) < (num_finite_buckets + 2)):
        raise ValueError(_BAD_LOW_BUCKET_COUNT)
    width = buckets.width
    lower = buckets.offset
    upper = (lower + (num_finite_buckets * width))
    if (a_float < lower):
        index = 0
    elif (a_float >= upper):
        index = (num_finite_buckets + 1)
    else:
        index = (1 + int(((a_float - lower) / width)))
    bucket_counts[index] += 1
    _logger.debug(u'upper:%f, lower:%f, width:%f, sample:%f, index:%d', upper, lower, width, a_float, index)

Adds `a_float` to `dist`, updating the its linear buckets.

Args:
a_float (float): a new value
dist (:class:`endpoints_management.gen.servicecontrol_v1_messages.Distribution`):
the Distribution being updated

Raises:
ValueError: if `dist` does not already have linear buckets defined
ValueError: if there are not enough bucket count fields in `dist`


def __init__(self,
               api,
               path,
               content_type=None,
               gcs_headers=None):

    assert self._maxrequestsize > self._blocksize
    assert self._maxrequestsize % self._blocksize == 0
    assert self._maxrequestsize >= self._flushsize

    self._api = api
    self._path = path

    self.name = api_utils._unquote_filename(path)
    self.closed = False

    self._buffer = collections.deque()
    self._buffered = 0
    self._written = 0
    self._offset = 0

    headers = {'x-goog-resumable': 'start'}
    if content_type:
      headers['content-type'] = content_type
    if gcs_headers:
      headers.update(gcs_headers)
    status, resp_headers, content = self._api.post_object(path, headers=headers)
    errors.check_status(status, [201], path, headers, resp_headers,
                        body=content)
    loc = resp_headers.get('location')
    if not loc:
      raise IOError('No location header found in 201 response')
    parsed = urlparse.urlparse(loc)
    self._path_with_token = '%s?%s' % (self._path, parsed.query)

Constructor.

Args:
api: A StorageApi instance.
path: Quoted/escaped path to the object, e.g. /mybucket/myfile
content_type: Optional content-type; Default value is
delegate to Google Cloud Storage.
gcs_headers: additional gs headers as a str->str dict, e.g
{'x-goog-acl': 'private', 'x-goog-meta-foo': 'foo'}.
Raises:
IOError: When this location can not be found.


def fit(self, X):

        U, V = self.split_matrix(X)
        self.tau = stats.kendalltau(U, V)[0]
        self.theta = self.compute_theta()
        self.check_theta()

Fit a model to the data updating the parameters.

Args:
X: `np.ndarray` of shape (,2).

Return:
None


def AddEventTag(self, event_tag):

    self._RaiseIfNotWritable()

    self._storage_file.AddEventTag(event_tag)

    self._session.event_labels_counter['total'] += 1
    for label in event_tag.labels:
      self._session.event_labels_counter[label] += 1
    self.number_of_event_tags += 1

Adds an event tag.

Args:
event_tag (EventTag): an event tag.

Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.


def is_noncopyable(class_, already_visited_cls_vars=None):
    logger = utils.loggers.cxx_parser
    class_decl = class_traits.get_declaration(class_)
    true_header = ('is_noncopyable(TRUE) - %s - ' % class_.decl_string)
    if is_union(class_):
        return False
    if class_decl.is_abstract:
        logger.debug((true_header + 'abstract client'))
        return True
    copy_ = find_copy_constructor(class_decl)
    if (copy_ and (copy_.access_type == 'public') and (not copy_.is_artificial)):
        return False
    if (already_visited_cls_vars is None):
        already_visited_cls_vars = []
    for base_desc in class_decl.recursive_bases:
        assert isinstance(base_desc, class_declaration.hierarchy_info_t)
        if (base_desc.related_class.decl_string in ('::boost::noncopyable', '::boost::noncopyable_::noncopyable')):
            logger.debug((true_header + 'derives from boost::noncopyable'))
            return True
        if (not has_copy_constructor(base_desc.related_class)):
            base_copy_ = find_copy_constructor(base_desc.related_class)
            if (base_copy_ and (base_copy_.access_type == 'private')):
                logger.debug((true_header + 'there is private copy constructor'))
                return True
            elif __is_noncopyable_single(base_desc.related_class, already_visited_cls_vars):
                logger.debug((true_header + '__is_noncopyable_single returned True'))
                return True
        if __is_noncopyable_single(base_desc.related_class, already_visited_cls_vars):
            logger.debug((true_header + '__is_noncopyable_single returned True'))
            return True
    if (not has_copy_constructor(class_decl)):
        logger.debug((true_header + 'does not have trivial copy constructor'))
        return True
    elif (not has_public_constructor(class_decl)):
        logger.debug((true_header + 'does not have a public constructor'))
        return True
    elif (has_destructor(class_decl) and (not has_public_destructor(class_decl))):
        logger.debug((true_header + 'has private destructor'))
        return True
    return __is_noncopyable_single(class_decl, already_visited_cls_vars)

Checks if class is non copyable

Args:
class_ (declarations.class_t): the class to be checked
already_visited_cls_vars (list): optional list of vars that should not
be checked a second time, to prevent infinite recursions.
In general you can ignore this argument, it is mainly used during
recursive calls of is_noncopyable() done by pygccxml.

Returns:
bool: if the class is non copyable


def __init__(self, timeout, proxy_config):

    suds.transport.http.HttpTransport.__init__(self, timeout=timeout)
    self.handlers = proxy_config.GetHandlers()

Initializes SudsHTTPSTransport.

Args:
timeout: An integer for the connection timeout time.
proxy_config: A ProxyConfig instance representing proxy settings.


def reverse_transform(self, col):

        if isinstance(col, pd.Series):
            col = col.to_frame()

        output = pd.DataFrame(index=col.index)
        output[self.col_name] = col.apply(self.safe_date, axis=1)

        return output

Converts data back into original format.

Args:
col(pandas.DataFrame): Data to transform.

Returns:
pandas.DataFrame


def from_ordinals(ordinals, validate=True):
    ordinals = tf.convert_to_tensor(ordinals, dtype=tf.int32)
    control_deps = []
    if validate:
        control_deps.append(tf.debugging.assert_positive(ordinals, message='Ordinals must be positive.'))
        with tf.compat.v1.control_dependencies(control_deps):
            ordinals = tf.identity(ordinals)
    with tf.compat.v1.control_dependencies(control_deps):
        years, months, days = date_utils.ordinal_to_year_month_day(ordinals)
        return DateTensor(ordinals, years, months, days)

Creates DateTensor from tensors of ordinals.

Args:
ordinals: Tensor of type int32. Each value is number of days since 1 Jan
0001. 1 Jan 0001 has `ordinal=1`.
validate: Whether to validate the dates.

Returns:
DateTensor object.

#### Example

```python
ordinals = tf.constant([
735703,  # 2015-4-12
736693   # 2017-12-30
], dtype=tf.int32)

date_tensor = tff.datetime.dates_from_ordinals(ordinals)
```


def _query(self, path: str, method: str, data: Dict[str, Any]=None, expected_status: int = 200) \
            -> Union[List[Dict[str, Any]], Dict[str, Any], None]:

        url = Pycord.url_base + path
        self.logger.debug(f'Making {method} request to "{url}"')
        if method == 'GET':
            r = requests.get(url, headers=self._build_headers())
        elif method == 'POST':
            r = requests.post(url, headers=self._build_headers(), json=data)
            r = requests.get(url, headers=self._build_headers())
        elif method == 'PATCH':
            r = requests.patch(url, headers=self._build_headers(), json=data)
        else:
            raise ValueError(f'Unknown HTTP method {method}')
        self.logger.debug(f'{method} response from "{url}" was "{r.status_code}"')
        if r.status_code != expected_status:
            raise ValueError(f'Non-{expected_status} {method} response from Discord API ({r.status_code}): {r.text}')
        if expected_status == 200:
            return r.json()
        return None

Make an HTTP request

Args:
path: the URI path (not including the base url, start with
the first uri segment, like 'users/...')
method: the HTTP method to use (GET, POST, PATCH, ...)
data: the data to send as JSON data
expected_status: expected HTTP status; other statuses
received will raise an Exception

Returns:
Data from the endpoint's response


def run(self, fetches, *args, **kwargs):
    feed_dict = kwargs.pop('feed_dict', {})
    if feed_dict:
        raise RuntimeError('feed_dict is not supported when eager execution is enabled (in this case, sess.run(t) is shorthand for t.numpy()')
    if args or kwargs:
        raise RuntimeError('Optional args are not supported when eager execution is enabled (in this case, sess.run(t) is shorthand for t.numpy()')
    return self._test_case.evaluate(fetches)

Evaluate `fetches`.

Fail if additional args are specified.

Args:
fetches: A Tensor or a nested list/tuple of Tensors.
*args: Positional arguments
**kwargs: Keyword arguments

Raises:
RuntimeError: If args or kwargs are specified.

Returns:
Tensors as numpy values.


def convert_concat(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting concat ...')
    concat_nodes = [layers[i] for i in inputs]
    if (len(concat_nodes) == 1):
        layers[scope_name] = concat_nodes[0]
        return
    if (names == 'short'):
        tf_name = ('CAT' + random_string(5))
    elif (names == 'keep'):
        tf_name = w_name
    else:
        tf_name = (w_name + str(random.random()))
    cat = keras.layers.Concatenate(name=tf_name, axis=params['axis'])
    layers[scope_name] = cat(concat_nodes)

Convert concatenation.

Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras tensors
weights: pytorch state_dict
names: use short names for keras layers


def setXpanId(self, xPanId):

        xpanid = ''
        print '%s call setXpanId' % self.port
        print xPanId
        try:
            if not isinstance(xPanId, str):
                xpanid = self.__convertLongToString(xPanId)

                if len(xpanid) < 16:
                    xpanid = xpanid.zfill(16)
                    print xpanid
                    cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid
                    datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid
            else:
                xpanid = xPanId
                cmd = WPANCTL_CMD + 'setprop Network:XPANID %s' % xpanid
                datasetCmd = WPANCTL_CMD + 'setprop Dataset:ExtendedPanId %s' % xpanid

            self.xpanId = xpanid
            self.hasActiveDatasetToCommit = True
            return self.__sendCommand(cmd)[0] != 'Fail' and self.__sendCommand(datasetCmd)[0] != 'Fail'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger('setXpanId() Error: ' + str(e))

set extended PAN ID of Thread Network

Args:
xPanId: extended PAN ID in hex format

Returns:
True: successful to set the extended PAN ID
False: fail to set the extended PAN ID


def from_file(xmu_dat_file="xmu.dat", feff_inp_file="feff.inp"):

        data = np.loadtxt(xmu_dat_file)
        header = Header.from_file(feff_inp_file)
        parameters = Tags.from_file(feff_inp_file)
        pots = Potential.pot_string_from_file(feff_inp_file)

        if "RECIPROCAL" in parameters:
            absorbing_atom = parameters["TARGET"]

        else:
            absorbing_atom = pots.splitlines()[3].split()[2]
        return Xmu(header, parameters, absorbing_atom, data)

Get Xmu from file.

Args:
xmu_dat_file (str): filename and path for xmu.dat
feff_inp_file (str): filename and path of feff.inp input file

Returns:
Xmu object


def comment(self, text, comment_prefix='
    comment = Comment(self._container)
    if (not text.startswith(comment_prefix)):
        text = '{} {}'.format(comment_prefix, text)
    if (not text.endswith('\n')):
        text = '{}{}'.format(text, '\n')
    comment.add_line(text)
    self._container.structure.insert(self._idx, comment)
    self._idx += 1
    return self

Creates a comment block

Args:
text (str): content of comment without #
comment_prefix (str): character indicating start of comment

Returns:
self for chaining


def from_file( cls, filename ):

        with open( filename, 'r' ) as stream:
            data = yaml.load( stream, Loader=yaml.SafeLoader )
            notes = data.get( 'notes' )
            v_type = data.get( 'type' )
            track = data.get( 'track' )
            xargs = {}
            if track:
                if type( track ) is str:
                    track = [ track ]
                xargs['track'] = track
            vaspmeta = VASPMeta( data['title'],
                                 data['description'],
                                 data['status'],
                                 notes=notes,
                                 type=v_type,
                                 **xargs )
        return vaspmeta

Create a VASPMeta object by reading a `vaspmeta.yaml` file

Args:
filename (Str): filename to read in.

Returns:
(vasppy.VASPMeta): the VASPMeta object


def simple_spool_transaction(self, from_address, to, op_return, min_confirmations=6):
    ntokens = len(to)
    nfees = old_div(self._t.estimate_fee(ntokens, 2), self.fee)
    inputs = self.select_inputs(from_address, nfees, ntokens, min_confirmations=min_confirmations)
    outputs = [{'address': to_address, 'value': self.token} for to_address in to]
    outputs += [{'script': self._t._op_return_hex(op_return), 'value': 0}]
    unsigned_tx = self._t.build_transaction(inputs, outputs)
    return unsigned_tx

Utililty function to create the spool transactions. Selects the inputs,
encodes the op_return and constructs the transaction.

Args:
from_address (str): Address originating the transaction
to (str): list of addresses to receive tokens (file_hash, file_hash_metadata, ...)
op_return (str): String representation of the spoolverb, as returned by the properties of Spoolverb
min_confirmations (int): Number of confirmations when chosing the inputs of the transaction. Defaults to 6

Returns:
str: unsigned transaction


def with_metadata_spec(self, column_name: str='metadata', python_type: Type=str, convert_fn: Optional[Callable[[Dict[str, Any]], Any]]=None, sql_typecast: Optional[str]='::jsonb') -> 'ColumnSpecsBuilder':

    def value_fn(chunk: Chunk) -> Any:
        if convert_fn:
            return convert_fn(chunk.metadata)
        return json.dumps(chunk.metadata) if python_type == str else chunk.metadata
    self._specs.append(ColumnSpec(column_name=column_name, python_type=python_type, value_fn=value_fn, sql_typecast=sql_typecast))
    return self

Add metadata :class:`.ColumnSpec` with optional type and conversion.

Args:
column_name: Name for the metadata column (defaults to "metadata")
python_type: Python type for the column (defaults to str)
convert_fn: Optional function to convert the metadata dictionary
If None and python_type is str, converts to JSON string
sql_typecast: Optional SQL type cast (defaults to "::jsonb")

Returns:
Self for method chaining

Example:
>>> builder.with_metadata_spec(
...     column_name="meta_tags",
...     python_type=list,
...     convert_fn=lambda meta: list(meta.keys()),
...     sql_typecast="::text[]"
... )


def get_commit(profile, sha):

    resource = "/commits/" + sha
    data = api.get_request(profile, resource)
    return prepare(data)

Fetch a commit.

Args:

profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.

sha
The SHA of the commit to fetch.

Returns:
A dict with data about the commit.


def ComponentsToPath(components):

  precondition.AssertIterableType(components, Text)
  for component in components:
    if not component:
      raise ValueError("Empty path component in: {}".format(components))

    if "/" in component:
      raise ValueError("Path component with '/' in: {}".format(components))

  if components:
    return "/" + "/".join(components)
  else:
    return ""

Converts a list of path components to a canonical path representation.

Args:
components: A sequence of path components.

Returns:
A canonical MySQL path representation.


def __init__(self, speech, display_text=None, is_ssml=False):

        super(ask, self).__init__(speech, display_text, is_ssml)
        self._response["payload"]["google"]["expect_user_response"] = True

Returns a response to the user and keeps the current session alive.
Expects a response from the user.

Arguments:
speech {str} --  Text to be pronounced to the user / shown on the screen


def is_in_range(self, values, unit=None, raise_exception=True):

        self._is_numeric(values)
        if unit is None or unit == self.units[0]:
            minimum = self.min
            maximum = self.max
        else:
            namespace = {'self': self}
            self.is_unit_acceptable(unit, True)
            min_statement = "self._{}_to_{}(self.min)".format(
                self._clean(self.units[0]), self._clean(unit))
            max_statement = "self._{}_to_{}(self.max)".format(
                self._clean(self.units[0]), self._clean(unit))
            minimum = eval(min_statement, namespace)
            maximum = eval(max_statement, namespace)

        for value in values:
            if value < minimum or value > maximum:
                if not raise_exception:
                    return False
                else:
                    raise ValueError(
                        '{0} should be between {1} and {2}. Got {3}'.format(
                            self.__class__.__name__, self.min, self.max, value
                        )
                    )
        return True

Check if a list of values is within physically/mathematically possible range.

Args:
values: A list of values.
unit: The unit of the values.  If not specified, the default metric
unit will be assumed.
raise_exception: Set to True to raise an exception if not in range.


def __init__(self, element_values: typing.Union[ValueSpecOrAnnotation, typing.Sequence[ValueSpecOrAnnotation]], default: typing.Optional[typing.Tuple[typing.Any, ...]]=MISSING_VALUE, min_size: typing.Optional[int]=None, max_size: typing.Optional[int]=None, size: typing.Optional[int]=None, transform: typing.Optional[typing.Callable[[typing.Any], typing.Tuple[typing.Any, ...]]]=None, is_noneable: bool=False, frozen: bool=False):
    if isinstance(element_values, (tuple, list)):
        if not element_values:
            raise ValueError("Argument 'element_values' must be a non-empty list.")
        if size is not None or min_size is not None or max_size is not None:
            raise ValueError(f'"size", "min_size" and "max_size" are not applicable for fixed-length Tuple with elements: {element_values!r}')
        element_values = [ValueSpec.from_annotation(v, auto_typing=True) for v in element_values]
        min_size = len(element_values)
        max_size = min_size
    else:
        element_values = ValueSpec.from_annotation(element_values, auto_typing=True)
        if size is not None and (min_size is not None or max_size is not None):
            raise ValueError(f'Either "size" or "min_size"/"max_size" pair can be specified. Encountered: size={size}, min_size={min_size}, max_size={max_size}.')
        if size is not None:
            min_size = size
            max_size = size
        if min_size is None:
            min_size = 0
        if min_size < 0:
            raise ValueError(f'"min_size" of List must be no less than 0. Encountered: {min_size}.')
        if max_size is not None:
            if max_size < min_size:
                raise ValueError(f'"max_size" of List must be no less than "min_size". Encountered: min_size={min_size}, max_size=max_size.')
        if min_size == max_size:
            element_values = [element_values] * min_size
    if isinstance(element_values, ValueSpec):
        elements = [Field(key_specs.TupleKey(None), element_values, 'Field of variable-length tuple element')]
    else:
        elements = []
        for i, element_value in enumerate(element_values):
            if not isinstance(element_value, ValueSpec):
                raise ValueError(f"Items in 'element_values' must be ValueSpec objects.Encountered: {element_value!r} at {i}.")
            elements.append(Field(key_specs.TupleKey(i), element_value, f'Field of tuple element at {i}'))
    self._min_size = min_size
    self._max_size = max_size
    self._elements = elements
    super().__init__(tuple, default, transform, is_noneable=is_noneable, frozen=frozen)

Constructor.

Args:
element_values: A ValueSpec object or its equivalence as the element spec
for a variable-length tuple, or a sequence of ValueSpec objects or their
equivalences as the elements specs for a fixed-length tuple.
default: (Optional) default value for this spec.
min_size: (Optional) min size of tuple. If None, 0 will be used.
Applicable only for variable-length tuple.
max_size: (Optional) max size of list. Applicable only for variable-length
tuple.
size: (Optional) size of List. A shortcut to specify min_size and max_size
at the same time. `size` and `min_size`/`max_size` are mutual exclusive.
transform: (Optional) user-defined function to be called on the input
of `apply`. It could be used as a type converter or a custom
validator which may raise errors.
is_noneable: If True, None is acceptable.
frozen: If True, values other than the default value is not accceptable.


def list_skus(access_token, subscription_id, location, publisher, offer):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/providers/Microsoft.Compute/',
                        'locations/', location,
                        '/publishers/', publisher,
                        '/artifacttypes/vmimage/offers/', offer,
                        '/skus?api-version=', COMP_API])
    return do_get(endpoint, access_token)

List available VM image skus for a publisher offer.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
location (str): Azure data center location. E.g. westus.
publisher (str): VM image publisher. E.g. MicrosoftWindowsServer.
offer (str): VM image offer. E.g. WindowsServer.

Returns:
HTTP response with JSON list of skus.


def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:

    columns = get_fieldnames_from_cursor(cursor)
    return [
        OrderedDict(zip(columns, row))
        for row in cursor.fetchall()
    ]

Return all rows from a cursor as a list of :class:`OrderedDict` objects.

Args:
cursor: the cursor

Returns:
a list (one item per row) of :class:`OrderedDict` objects whose key are
column names and whose values are the row values


def report(self, verbose=1):

        lines = []
        if verbose >= 2:

            lines.append(self._status_line(tense='past'))
            if verbose >= 3:
                unit, mag = _choose_unit(self.total_time, self.unit,
                                         self._asciimode)
                lines.append('    body took: {total:.{pr}{t}} {unit}'.format(
                    total=self.total_time / mag,
                    t=self._precision_type,
                    pr=self._precision, unit=unit))
            lines.append('    time per loop: {}'.format(self._seconds_str()))
        else:

            line = 'Timed ' + self._seconds_str()
            if self.label:
                line += ' for ' + self.label
            lines.append(line)
        text = '\n'.join(lines)
        return text

Creates a human readable report

Args:
verbose (int): verbosity level. Either 1, 2, or 3.

Returns:
str: the report

SeeAlso:
timerit.Timerit.print

Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
>>> print(ti.report(verbose=1))
Timed best=...s, mean=...s


def eval_input_receiver_fn(tf_transform_output, schema):
    raw_feature_spec = taxi.get_raw_feature_spec(schema)
    serialized_tf_example = tf.placeholder(dtype=tf.string, shape=[None], name='input_example_tensor')
    features = tf.parse_example(serialized_tf_example, raw_feature_spec)
    transformed_features = tf_transform_output.transform_raw_features(features)
    receiver_tensors = {'examples': serialized_tf_example}
    features.update(transformed_features)
    return tfma.export.EvalInputReceiver(features=features, receiver_tensors=receiver_tensors, labels=transformed_features[taxi.transformed_name(taxi.LABEL_KEY)])

Build everything needed for the tf-model-analysis to run the model.

Args:
tf_transform_output: A TFTransformOutput.
schema: the schema of the input data.

Returns:
EvalInputReceiver function, which contains:
- Tensorflow graph which parses raw untransformed features, applies the
tf-transform preprocessing operators.
- Set of raw, untransformed features.
- Label against which predictions will be compared.


def cftime_to_timestamp(date, time_unit='us'):
    import cftime
    utime = cftime.utime('microseconds since 1970-01-01 00:00:00')
    if (time_unit == 'us'):
        tscale = 1
    else:
        tscale = (np.timedelta64(1, 'us') / np.timedelta64(1, time_unit))
    return (utime.date2num(date) * tscale)

Converts cftime to timestamp since epoch in milliseconds

Non-standard calendars (e.g. Julian or no leap calendars)
are converted to standard Gregorian calendar. This can cause
extra space to be added for dates that don't exist in the original
calendar. In order to handle these dates correctly a custom bokeh
model with support for other calendars would have to be defined.

Args:
date: cftime datetime object (or array)

Returns:
time_unit since 1970-01-01 00:00:00


def create_position_ids_from_input_ids(self, input_ids, past_key_values_length=0):
    mask = tf.cast(tf.math.not_equal(input_ids, self.padding_idx), dtype=input_ids.dtype)
    incremental_indices = (tf.math.cumsum(mask, axis=1) + past_key_values_length) * mask
    return incremental_indices + self.padding_idx

Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding
symbols are ignored. This is modified from fairseq's `utils.make_positions`.

Args:
input_ids: tf.Tensor
Returns: tf.Tensor


def _ParseMRUListExValue(self, registry_key):
    mrulistex_value = registry_key.GetValueByName('MRUListEx')
    if (not mrulistex_value):
        return None
    mrulistex_entries_map = self._GetDataTypeMap('mrulistex_entries')
    context = dtfabric_data_maps.DataTypeMapContext(values={'data_size': len(mrulistex_value.data)})
    return self._ReadStructureFromByteStream(mrulistex_value.data, 0, mrulistex_entries_map, context=context)

Parses the MRUListEx value in a given Registry key.

Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains
the MRUListEx value.

Returns:
mrulistex_entries: MRUListEx entries or None if not available.


class ShieldGemma2ImageClassifierOutputWithNoAttention(ImageClassifierOutputWithNoAttention):
    probabilities: Optional[torch.Tensor] = None

ShieldGemma2 classifies imags as violative or not relative to a specific policy
Args:


def _create(cls, user_agent=None, user_agent_config_yaml=None,
                user_agent_lookup=None, **kwargs):

        kwargs = UserAgent._environment_variables(**kwargs)
        if 'user_agent' in kwargs:
            user_agent = kwargs['user_agent']
            del kwargs['user_agent']
        prefix = kwargs.get('prefix')
        if prefix:
            del kwargs['prefix']
        else:
            prefix = 'HDXPythonUtilities/%s' % get_utils_version()
        if not user_agent:
            ua = cls._load(prefix, user_agent_config_yaml, user_agent_lookup)
        else:
            ua = cls._construct(kwargs, prefix, user_agent)
        return ua

Get full user agent string

Args:
user_agent (Optional[str]): User agent string. HDXPythonLibrary/X.X.X- is prefixed.
user_agent_config_yaml (Optional[str]): Path to YAML user agent configuration. Ignored if user_agent supplied. Defaults to ~/.useragent.yml.
user_agent_lookup (Optional[str]): Lookup key for YAML. Ignored if user_agent supplied.

Returns:
str: Full user agent string


def TempFilePath(suffix='', prefix='tmp', dir=None):
    precondition.AssertType(suffix, Text)
    precondition.AssertType(prefix, Text)
    precondition.AssertOptionalType(dir, Text)
    root = _TempRootPath()
    if (not dir):
        dir = root
    elif (root and (not os.path.commonprefix([dir, root]))):
        raise ValueError(("path '%s' must start with '%s'" % (dir, root)))
    (desc, path) = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
    os.close(desc)
    return path

Creates a temporary file based on the environment configuration.

If no directory is specified the file will be placed in folder as specified by
the `TEST_TMPDIR` environment variable if available or fallback to
`Test.tmpdir` of the current configuration if not.

If directory is specified it must be part of the default test temporary
directory.

Args:
suffix: A suffix to end the file name with.
prefix: A prefix to begin the file name with.
dir: A directory to place the file in.

Returns:
An absolute path to the created file.

Raises:
ValueError: If the specified directory is not part of the default test
temporary directory.


def predict(self, structure, ref_structure):

        if self.check_isostructural:
            m = StructureMatcher()
            mapping = m.get_best_electronegativity_anonymous_mapping(
                structure, ref_structure)
            if mapping is None:
                raise ValueError("Input structures do not match!")

        if "ionic" in self.radii_type:
            try:

                if (not is_ox(structure)) and self.use_bv:
                    a = BVAnalyzer()
                    structure = a.get_oxi_state_decorated_structure(structure)
                if (not is_ox(ref_structure)) and self.use_bv:
                    a = BVAnalyzer()
                    ref_structure = a.get_oxi_state_decorated_structure(
                        ref_structure)

                comp = structure.composition
                ref_comp = ref_structure.composition

                if any([k.ionic_radius is None for k in list(comp.keys())]) or \
                        any([k.ionic_radius is None for k in
                             list(ref_comp.keys())]):
                    raise ValueError("Not all the ionic radii are available!")

                numerator = 0
                denominator = 0

                for k, v in comp.items():
                    numerator += k.ionic_radius * v ** (1 / 3)
                for k, v in ref_comp.items():
                    denominator += k.ionic_radius * v ** (1 / 3)

                return ref_structure.volume * (numerator / denominator) ** 3
            except Exception as ex:
                warnings.warn("Exception occured. Will attempt atomic radii.")

                pass

        if "atomic" in self.radii_type:
            comp = structure.composition
            ref_comp = ref_structure.composition

            numerator = 0
            denominator = 0
            for k, v in comp.items():
                numerator += k.atomic_radius * v ** (1 / 3)
            for k, v in ref_comp.items():
                denominator += k.atomic_radius * v ** (1 / 3)
            return ref_structure.volume * (numerator / denominator) ** 3

        raise ValueError("Cannot find volume scaling based on radii choices "
                         "specified!")

Given a structure, returns the predicted volume.
Args:
structure (Structure): structure w/unknown volume
ref_structure (Structure): A reference structure with a similar
structure but different species.
Returns:
a float value of the predicted volume


def ext_xsect(scatterer, h_pol=True):
    if (scatterer.psd_integrator is not None):
        try:
            return scatterer.psd_integrator.get_angular_integrated(scatterer.psd, scatterer.get_geometry(), 'ext_xsect')
        except AttributeError:
            pass
    old_geom = scatterer.get_geometry()
    (thet0, thet, phi0, phi, alpha, beta) = old_geom
    try:
        scatterer.set_geometry((thet0, thet0, phi0, phi0, alpha, beta))
        S = scatterer.get_S()
    finally:
        scatterer.set_geometry(old_geom)
    if h_pol:
        return ((2 * scatterer.wavelength) * S[(1, 1)].imag)
    else:
        return ((2 * scatterer.wavelength) * S[(0, 0)].imag)

Extinction cross section for the current setup, with polarization.

Args:
scatterer: a Scatterer instance.
h_pol: If True (default), use horizontal polarization.
If False, use vertical polarization.

Returns:
The extinction cross section.


def read_probes(self, key = None):

        print(('xxxxx probes', key, self._PROBES()))

        if key is None:

            d = {}
            for k in list(self._PROBES.keys()):
                d[k] = self.read_probes(k)
            return d
        else:

            assert key in list(self._PROBES.keys())

            value = None

            return value

function is overloaded:
- read_probes()
- read_probes(key)

Args:
key: name of requested value

Returns:
- if called without argument: returns the values of all probes in dictionary form
- if called with argument: returns the value the requested key


def create_event(self, institute, case, user, link, category, verb, subject, level='specific', variant=None, content=None, panel=None):
    variant = (variant or {})
    event = dict(institute=institute['_id'], case=case['_id'], user_id=user['_id'], user_name=user['name'], link=link, category=category, verb=verb, subject=subject, level=level, variant_id=variant.get('variant_id'), content=content, panel=panel, created_at=datetime.now(), updated_at=datetime.now())
    LOG.debug('Saving Event')
    self.event_collection.insert_one(event)
    LOG.debug('Event Saved')
    return event

Create a Event with the parameters given.

Arguments:
institute (dict): A institute
case (dict): A case
user (dict): A User
link (str): The url to be used in the event
category (str): case or variant
verb (str): What type of event
subject (str): What is operated on
level (str): 'specific' or 'global'. Default is 'specific'
variant (dict): A variant
content (str): The content of the comment

Returns:
event(dict): The inserted event


def index(self, column):

        for i, key in enumerate(self._keys):
            if key == column:
                return i
        raise ValueError('Column "%s" not found.' % column)

Fetches the column number (0 indexed).

Args:
column: A string, column to fetch the index of.

Returns:
An int, the row index number.

Raises:
ValueError: The specified column was not found.


def Count3(pcoll, factor=1):
    return pcoll | 'PairWithOne' >> beam.Map(lambda v: (v, factor)) | beam.CombinePerKey(sum)

Count as a decorated function with a side input.

Args:
pcoll: the PCollection passed in from the previous transform
factor: the amount by which to count

Returns:
A PCollection counting the number of times each unique element occurs.


def dump_package_data(data, buf, format_=FileFormat.py, skip_attributes=None):
    if (format_ == FileFormat.txt):
        raise ValueError("'txt' format not supported for packages.")
    data_ = dict(((k, v) for (k, v) in data.iteritems() if (v is not None)))
    data_ = package_serialise_schema.validate(data_)
    skip = set((skip_attributes or []))
    items = []
    for key in package_key_order:
        if (key not in skip):
            value = data_.pop(key, None)
            if (value is not None):
                items.append((key, value))
    for (key, value) in data_.iteritems():
        if (key not in skip):
            items.append((key, value))
    dump_func = dump_functions[format_]
    dump_func(items, buf)

Write package data to `buf`.

Args:
data (dict): Data source - must conform to `package_serialise_schema`.
buf (file-like object): Destination stream.
format_ (`FileFormat`): Format to dump data in.
skip_attributes (list of str): List of attributes to not print.


def update_target_state(self, value: str, force: bool = True) -> datetime:

        value = value.lower()
        if not force:
            current_state = self.current_state
            if current_state == 'unknown':
                raise RuntimeError("Unable to set target state when current "
                                   "state is 'unknown'")

            allowed_target_states = self._allowed_target_states[current_state]

            LOG.debug('Updating target state of %s to %s', self._id, value)

            if value not in allowed_target_states:
                raise ValueError("Invalid target state: '{}'. {} can be "
                                 "commanded to states: {}".
                                 format(value, current_state,
                                        allowed_target_states))

        return self._update_state('target', value)

Set the target state.

Args:
value (str): New value for target state
force (bool): If true, ignore allowed transitions

Returns:
datetime, update timestamp

Raises:
RuntimeError, if it is not possible to currently set the target
state.
ValueError, if the specified target stat is not allowed.


def get_callable_name(func):

    try:
        return meta_util_six.get_funcname(func)
    except AttributeError:
        if isinstance(func, type):
            return repr(func).replace('<type \'', '').replace('\'>', '')
        elif hasattr(func, '__name__'):
            return func.__name__
        else:
            raise NotImplementedError(('cannot get func_name of func=%r'
                                        'type(func)=%r') % (func, type(func)))

Works on must functionlike objects including str, which has no func_name

Args:
func (function):

Returns:
str:

CommandLine:
python -m utool.util_str --exec-get_callable_name

Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import *  # NOQA
>>> func = len
>>> result = get_callable_name(func)
>>> print(result)
len


def __init__(self, sess, coord, stop_grace_period_secs=120):
    _WrappedSession.__init__(self, sess)
    self._coord = coord
    self._stop_grace_period_secs = stop_grace_period_secs

Create a new `_CoordinatedSession`.

Args:
sess: A `tf.compat.v1.Session` object.  The wrapped session.
coord: A `tf.train.Coordinator` object.
stop_grace_period_secs: Number of seconds given to threads to stop after
`close()` has been called.


async def fetch_messages(self, selected: SelectedMailbox,
                             sequence_set: SequenceSet,
                             attributes: FrozenSet[FetchAttribute]) \
            -> Tuple[Iterable[Tuple[int, MessageInterface]], SelectedMailbox]:

        ...

Get a list of loaded message objects corresponding to given sequence
set.

Args:
selected: The selected mailbox session.
sequence_set: Sequence set of message sequences or UIDs.
attributes: Fetch attributes for the messages.

Raises:
:class:`~pymap.exceptions.MailboxNotFound`


def values(self):
    return self._values

The concatenated rows for this ragged tensor.

`rt.values` is a potentially ragged tensor formed by flattening the two
outermost dimensions of `rt` into a single dimension.

`rt.values.shape = [nvals] + rt.shape[2:]` (where `nvals` is the
number of items in the outer two dimensions of `rt`).

`rt.ragged_rank = self.ragged_rank - 1`

Returns:
A potentially ragged tensor.

#### Example:

>>> rt = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
>>> print(rt.values)
tf.Tensor([3 1 4 1 5 9 2 6], shape=(8,), dtype=int32)


def __init__(self,
                 kernel_fn,
                 verbose=False,
                 random_state=None):

        self.kernel_fn = kernel_fn
        self.verbose = verbose
        self.random_state = check_random_state(random_state)

Init function

Args:
kernel_fn: function that transforms an array of distances into an
array of proximity values (floats).
verbose: if true, print local prediction values from linear model.
random_state: an integer or numpy.RandomState that will be used to
generate random numbers. If None, the random state will be
initialized using the internal numpy seed.


def _send_request(url_id, data=None, json=None, req_type=None):

    url = settings.SEEDER_INFO_URL % url_id

    if not req_type:
        req_type = requests.get

    resp = req_type(
        url,
        data=data,
        json=json,
        timeout=settings.SEEDER_TIMEOUT,
        headers={
            "User-Agent": settings.USER_AGENT,
            "Authorization": settings.SEEDER_TOKEN,
        }
    )
    resp.raise_for_status()
    data = resp.json()

    return data

Send request to Seeder's API.

Args:
url_id (str): ID used as identification in Seeder.
data (obj, default None): Optional parameter for data.
json (obj, default None): Optional parameter for JSON body.
req_type (fn, default None): Request method used to send/download the
data. If none, `requests.get` is used.

Returns:
dict: Data from Seeder.


def path_data(self, variable_data, path):
    try:
        import jmespath
    except ImportError:
        print('Could not import jmespath module (try "pip install jmespath").')
        sys.exit(1)
    if isinstance(variable_data, string_types):
        try:
            variable_data = json.loads(variable_data)
        except Exception:
            self.log.debug('String value ({}) could not JSON serialized.'.format(variable_data))
    if ((path is not None) and isinstance(variable_data, (dict, list))):
        expression = jmespath.compile(path)
        variable_data = expression.search(variable_data, jmespath.Options(dict_cls=collections.OrderedDict))
    return variable_data

Return JMESPath data.

Args:
variable_data (str): The JSON data to run path expression.
path (str): The JMESPath expression.

Returns:
dict: The resulting data from JMESPath.


def silence(self, seq_set: SequenceSet, flag_set: AbstractSet[Flag], flag_op: FlagOp) -> None:
    session_flags = self.session_flags
    permanent_flag_set = (self.permanent_flags & flag_set)
    session_flag_set = (session_flags & flag_set)
    for (seq, msg) in self._messages.get_all(seq_set):
        msg_flags = msg.permanent_flags
        msg_sflags = session_flags.get(msg.uid)
        updated_flags = flag_op.apply(msg_flags, permanent_flag_set)
        updated_sflags = flag_op.apply(msg_sflags, session_flag_set)
        if (msg_flags != updated_flags):
            self._silenced_flags.add((msg.uid, updated_flags))
        if (msg_sflags != updated_sflags):
            self._silenced_sflags.add((msg.uid, updated_sflags))

Runs the flags update against the cached flags, to prevent untagged
FETCH responses unless other updates have occurred.

For example, if a session adds ``\\Deleted`` and calls this method,
the FETCH response will be silenced. But if another added ``\\Seen``
at the same time, the FETCH response will be sent.

Args:
seq_set: The sequence set of messages.
flag_set: The set of flags for the update operation.
flag_op: The mode to change the flags.


def AddFile(self, filepath):

    if filepath not in self._files:
      self._files.add(filepath)
      return True
    return False

Adds a file path as a source.

Args:
filepath: a string representing a path to the file.

Returns:
True if the file is not an already existing source.


def ParseFileObject(self, parser_mediator, file_object):
    file_header_map = self._GetDataTypeMap('asl_file_header')
    try:
        (file_header, _) = self._ReadStructureFromFileObject(file_object, 0, file_header_map)
    except (ValueError, errors.ParseError) as exception:
        raise errors.UnableToParseFile('Unable to parse file header with error: {0!s}'.format(exception))
    if (file_header.signature != self._FILE_SIGNATURE):
        raise errors.UnableToParseFile('Invalid file signature.')
    file_size = file_object.get_size()
    if (file_header.first_log_entry_offset > 0):
        last_log_entry_offset = 0
        file_offset = file_header.first_log_entry_offset
        while (file_offset < file_size):
            last_log_entry_offset = file_offset
            try:
                file_offset = self._ParseRecord(parser_mediator, file_object, file_offset)
            except errors.ParseError as exception:
                parser_mediator.ProduceExtractionWarning('unable to parse record with error: {0!s}'.format(exception))
                return
            if (file_offset == 0):
                break
        if (last_log_entry_offset != file_header.last_log_entry_offset):
            parser_mediator.ProduceExtractionWarning('last log entry offset does not match value in file header.')

Parses an ASL file-like object.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.

Raises:
UnableToParseFile: when the file cannot be parsed.