def mark_experimental(fn):

    @wraps(fn)
    def wrapper(*args, **kw):
        from peltak.core import shell

        if shell.is_tty:
            warnings.warn("This command is has experimental status. The "
                          "interface is not yet stable and might change "
                          "without notice within with a patch version update. "
                          "Use at your own risk")
        return fn(*args, **kw)

    return wrapper

Mark function as experimental.

Args:
fn (FunctionType):
The command function to decorate.


def are_genes_in_api(my_clue_api_client, gene_symbols):
    if (len(gene_symbols) > 0):
        query_gene_symbols = (gene_symbols if (type(gene_symbols) is list) else list(gene_symbols))
        query_result = my_clue_api_client.run_filter_query(resource_name, {'where': {'gene_symbol': {'inq': query_gene_symbols}}, 'fields': {'gene_symbol': True}})
        logger.debug('query_result:  {}'.format(query_result))
        r = set([x['gene_symbol'] for x in query_result])
        return r
    else:
        logger.warning('provided gene_symbols was empty, cannot run query')
        return set()

determine if genes are present in the API

Args:
my_clue_api_client:
gene_symbols: collection of gene symbols to query the API with

Returns: set of the found gene symbols


def get_local_variable_from_name(self, variable_name):

        return next((v for v in self.variables if v.name == variable_name), None)

Return a local variable from a name
Args:
varible_name (str): name of the variable
Returns:
LocalVariable


def StartFlowAndWorker(client_id, flow_name, **kwargs):

  queue = rdfvalue.RDFURN("DEBUG-%s-" % getpass.getuser())
  if "token" in kwargs:
    token = kwargs.pop("token")
  else:
    token = access_control.ACLToken(username="GRRConsole")

  session_id = flow.StartAFF4Flow(
      client_id=client_id,
      flow_name=flow_name,
      queue=queue,
      token=token,
      **kwargs)
  worker_thrd = worker_lib.GRRWorker(
      queues=[queue], token=token, threadpool_size=1)
  while True:
    try:
      worker_thrd.RunOnce()
    except KeyboardInterrupt:
      print("exiting")
      worker_thrd.thread_pool.Join()
      break

    time.sleep(2)
    with aff4.FACTORY.Open(session_id, token=token) as flow_obj:
      if not flow_obj.GetRunner().IsRunning():
        break

  worker_thrd.thread_pool.Join()

  return session_id

Launches the flow and worker and waits for it to finish.

Args:
client_id: The client common name we issue the request.
flow_name: The name of the flow to launch.
**kwargs: passthrough to flow.

Returns:
A flow session id.

Note: you need raw access to run this flow as it requires running a worker.


def unique_parameter_values(self) -> 'list[Collection[cfg.Binding]]':

    def _get_values(parameter):
        return {b.data.get_type_key(): b for b in parameter.bindings}.values()
    return [_get_values(parameter) for parameter in self._unique_parameters()]

Get unique parameter subtypes as bindings.

Like _unique_parameters, but returns bindings instead of variables.

Returns:
A list of list of bindings.


def install(self, connection, partition, table_name = None, index_columns=None, materialize=False,
                logger = None):

        virtual_table = partition.vid

        table = partition.vid if not table_name else table_name

        if self._relation_exists(connection, table):
            if logger:
                logger.debug("Skipping '{}'; already installed".format(table))
            return
        else:
            if logger:
                logger.info("Installing '{}'".format(table))

        partition.localize()

        virtual_table = partition.vid + '_vt'

        self._add_partition(connection, partition)

        if materialize:

            if self._relation_exists(connection, table):
                debug_logger.debug(
                    'Materialized table of the partition already exists.\n partition: {}, table: {}'
                    .format(partition.name, table))
            else:
                cursor = connection.cursor()

                create_query = self.__class__._get_create_query(partition, table)
                debug_logger.debug(
                    'Creating new materialized view for partition mpr.'
                    '\n    partition: {}, view: {}, query: {}'
                    .format(partition.name, table, create_query))

                cursor.execute(create_query)

                copy_query = .format(table, virtual_table)
                debug_logger.debug(
                    'Populating sqlite table with rows from partition mpr.'
                    '\n    partition: {}, view: {}, query: {}'
                    .format(partition.name, table, copy_query))
                cursor.execute(copy_query)

                cursor.close()

        else:
            cursor = connection.cursor()
            view_q = "CREATE VIEW IF NOT EXISTS {} AS SELECT * FROM {} ".format(partition.vid, virtual_table)
            cursor.execute(view_q)
            cursor.close()

        if index_columns is not None:
            self.index(connection,table, index_columns)

        return table

Creates virtual table or read-only table for gion.

Args:
ref (str): id, vid, name or versioned name of the partition.
materialize (boolean): if True, create read-only table. If False create virtual table.

Returns:
str: name of the created table.


def as_dict(self, verbosity=0):
    species_list = []
    for (spec, occu) in self._species.items():
        d = spec.as_dict()
        del d['@module']
        del d['@class']
        d['occu'] = occu
        species_list.append(d)
    d = {'species': species_list, 'abc': [float(c) for c in self._frac_coords], 'lattice': self._lattice.as_dict(verbosity=verbosity), '@module': self.__class__.__module__, '@class': self.__class__.__name__}
    if (verbosity > 0):
        d['xyz'] = [float(c) for c in self.coords]
        d['label'] = self.species_string
    d['properties'] = self.properties
    return d

Json-serializable dict representation of PeriodicSite.

Args:
verbosity (int): Verbosity level. Default of 0 only includes the
matrix representation. Set to 1 for more details such as
cartesian coordinates, etc.


def require_params(self, req):
    params = {}
    for (name, param) in self.params.items():
        if ((name not in req.params) and param.required):
            missing = (set((p for p in self.params if self.params[p].required)) - set(req.params.keys()))
            raise errors.HTTPMissingParam(', '.join(missing))
        elif ((name in req.params) or param.default):
            try:
                if param.many:
                    values = (req.get_param_as_list(name, param.validated_value) or [(param.default and param.validated_value(param.default))])
                    params[name] = param.container(values)
                else:
                    params[name] = param.validated_value(req.get_param(name, default=param.default))
            except ValidationError as err:
                raise err.as_invalid_param(name)
            except ValueError as err:
                raise errors.HTTPInvalidParam(str(err), name)
    return params

Require all defined parameters from request query string.

Raises ``falcon.errors.HTTPMissingParam`` exception if any of required
parameters is missing and ``falcon.errors.HTTPInvalidParam`` if any
of parameters could not be understood (wrong format).

Args:
req (falcon.Request): request object


def tokens(cls, tokens):
    return cls(Lnk.TOKENS, tuple(map(int, tokens)))

Create a Lnk object for a token range.

Args:
tokens: a list of token identifiers


def __init__(self, p_range, ns_range, query_spec):

    self._property_range = p_range
    self._ns_range = ns_range
    self._query_spec = query_spec
    self._cursor = None
    self._query = None

Init.

Args:
p_range: a property_range.PropertyRange object that defines the
conditions entities should safisfy.
ns_range: a namesrange.NamespaceRange object that defines the namespaces
to examine.
query_spec: a model.QuerySpec object that defines how to retrieve
entities from datastore.


def rank(input: ragged_tensor.Ragged, name=None):
    with ops.name_scope(name, 'RaggedRank', [input]) as name:
        if not ragged_tensor.is_ragged(input):
            return array_ops.rank(input, name)
        return input.ragged_rank + array_ops.rank(input.flat_values)

Returns the rank of a RaggedTensor.

Returns a 0-D `int32` `Tensor` representing the rank of `input`.

#### Example:

>>> # shape of tensor 't' is [2, None, None]
>>> t = tf.ragged.constant([[[1], [2, 2]], [[3, 3, 3], [4, 4, 4, 4]]])
>>> tf.rank(t).numpy().item()
3

Args:
input: A `RaggedTensor`
name: A name for the operation (optional).

Returns:
A `Tensor` of type `int32`.


def get_dialect(mixed: Union[(SQLCompiler, Engine, Dialect)]) -> Dialect:
    if isinstance(mixed, Dialect):
        return mixed
    elif isinstance(mixed, Engine):
        return mixed.dialect
    elif isinstance(mixed, SQLCompiler):
        return mixed.dialect
    else:
        raise ValueError("get_dialect: 'mixed' parameter of wrong type")

Finds the SQLAlchemy dialect in use.

Args:
mixed: an SQLAlchemy :class:`SQLCompiler`, :class:`Engine`, or
:class:`Dialect` object

Returns: the SQLAlchemy :class:`Dialect` being used


def get_campaign_name_list(self):
    campaigns = self.find('campaigns', {})
    campaign_names = []
    for campaign in campaigns:
        if ('name' in campaign):
            campaign_names.append(campaign['name'])
    return campaign_names

Returns a list of all valid campaign names

Returns:
List of strings containing all valid campaign names


def cos(times: np.ndarray, amp: complex, freq: float, phase: float = 0) -> np.ndarray:

    return amp*np.cos(2*np.pi*freq*times+phase).astype(np.complex_)

Continuous cosine wave.

Args:
times: Times to output wave for.
amp: Pulse amplitude.
freq: Pulse frequency, units of 1/dt.
phase: Pulse phase.


def extract_wavs(utterances: List[Utterance], tgt_dir: Path,
                 lazy: bool) -> None:

    tgt_dir.mkdir(parents=True, exist_ok=True)
    for utter in utterances:
        wav_fn = "{}.{}".format(utter.prefix, "wav")
        out_wav_path = tgt_dir / wav_fn
        if lazy and out_wav_path.is_file():
            logger.info("File {} already exists and lazy == {}; not " \
                         "writing.".format(out_wav_path, lazy))
            continue
        logger.info("File {} does not exist and lazy == {}; creating " \
                     "it.".format(out_wav_path, lazy))
        trim_wav_ms(utter.org_media_path, out_wav_path,
                    utter.start_time, utter.end_time)

Extracts WAVs from the media files associated with a list of Utterance
objects and stores it in a target directory.

Args:
utterances: A list of Utterance objects, which include information
about the source media file, and the offset of the utterance in the
media_file.
tgt_dir: The directory in which to write the output WAVs.
lazy: If True, then existing WAVs will not be overwritten if they have
the same name


def _flatten_multiplicand_list(kernels):
    flattened = []
    for k in kernels:
        if isinstance(k, _ProductKernel):
            flattened += k.kernels
        else:
            flattened.append(k)
    return flattened

Flatten a list of kernels which may contain _ProductKernel instances.

Args:
kernels: Python list of `PositiveSemidefiniteKernel` instances

Returns:
Python list containing the elements of kernels, with any _ProductKernel
instances replaced by their `kernels` property contents.


def to_raw_op(f: types.FunctionType) -> Callable[..., Any]:
    f = types.FunctionType(f.__code__, f.__globals__, f.__name__, f.__defaults__, f.__closure__)
    return kwarg_only(f)

Make a given op wrapper function `f` raw.

Raw op wrappers can only be called with keyword arguments.

Args:
f: An op wrapper function to make raw.

Returns:
Raw `f`.


def _map_args(call_node, function):
    args = call_node.args
    kwds = {kwd.arg: kwd.value for kwd in call_node.keywords}
    call_args = tf_inspect.getcallargs(function, *args, **kwds)
    unexpected_defaults = []
    for k in call_args:
        if k not in kwds and call_args[k] not in args and (call_args[k] is not directives.UNSPECIFIED):
            unexpected_defaults.append(k)
    if unexpected_defaults:
        raise ValueError('Unexpected keyword argument values, %s, for function %s' % (zip(unexpected_defaults, [call_args[k] for k in unexpected_defaults]), function))
    return {k: v for k, v in call_args.items() if v is not directives.UNSPECIFIED}

Maps AST call nodes to the actual function's arguments.

Args:
call_node: ast.Call
function: Callable[..., Any], the actual function matching call_node
Returns:
Dict[Text, ast.AST], mapping each of the function's argument names to
the respective AST node.
Raises:
ValueError: if the default arguments are not correctly set


def touch(self, key, expire=0, noreply=None):
    if (noreply is None):
        noreply = self.default_noreply
    key = self.check_key(key)
    cmd = (((b'touch ' + key) + b' ') + six.text_type(expire).encode('ascii'))
    if noreply:
        cmd += b' noreply'
    cmd += b'\r\n'
    results = self._misc_cmd([cmd], b'touch', noreply)
    if noreply:
        return True
    return (results[0] == b'TOUCHED')

The memcached "touch" command.

Args:
key: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional bool, True to not wait for the reply (defaults to
self.default_noreply).

Returns:
True if the expiration time was updated, False if the key wasn't
found.


def transform(self, program: moderngl.Program, buffer: moderngl.Buffer,
                  mode=None, vertices=-1, first=0, instances=1):

        vao = self.instance(program)

        if mode is None:
            mode = self.mode

        vao.transform(buffer, mode=mode, vertices=vertices, first=first, instances=instances)

Transform vertices. Stores the output in a single buffer.

Args:
program: The ``moderngl.Program``
buffer: The ``moderngl.buffer`` to store the output

Keyword Args:
mode: Draw mode (for example ``moderngl.POINTS``)
vertices (int): The number of vertices to transform
first (int): The index of the first vertex to start with
instances (int): The number of instances


def _init_index(root_dir, schema, index_name):

    index_dir = os.path.join(root_dir, index_name)
    try:
        if not os.path.exists(index_dir):
            os.makedirs(index_dir)
            return create_in(index_dir, schema), index_dir
        else:
            return open_dir(index_dir), index_dir
    except Exception as e:
        logger.error("Init error: failed to open search index at: '{}': {} ".format(index_dir, e))
        raise

Creates new index or opens existing.

Args:
root_dir (str): root dir where to find or create index.
schema (whoosh.fields.Schema): schema of the index to create or open.
index_name (str): name of the index.

Returns:
tuple ((whoosh.index.FileIndex, str)): first element is index, second is index directory.


def build_request_body(type, id, attributes=None, relationships=None):
    result = {'data': {'type': type}}
    data = result['data']
    if (attributes is not None):
        data['attributes'] = attributes
    if (relationships is not None):
        data['relationships'] = relationships
    if (id is not None):
        data['id'] = id
    return result

Build a request body  object.

A body JSON object is used for any of the ``update`` or ``create``
methods on :class:`Resource` subclasses. In normal library use you
should not have to use this function directly.

Args:

type(string): The resource type for the attribute
id(uuid): The id of the object to update. This may be ``None``

Keyword Args:

attributes(dict): A JSON dictionary of the attributes to set
relationships(dict) A JSON dictionary of relationships to set

Returns:

A valid attribute dictionary. Often used in the ``update`` or
``create`` :class:`Resource`` methods.


def add(self, pattern, function, method=None, type_cast=None):
    if (not type_cast):
        type_cast = {}
    with self._lock:
        self._data_store.append({'pattern': pattern, 'function': function, 'method': method, 'type_cast': type_cast})

Function for registering a path pattern.

Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever fits your situation though.
Defaults to None.
type_cast (dict, optional): Mapping between the param name and
one of `int`, `float` or `bool`. The value reflected by the
provided param name will than be casted to the given type.
Defaults to None.


def tf_initialize(self, x_init, b):

        if x_init is None:

            x_init = [tf.zeros(shape=util.shape(t)) for t in b]

        initial_args = super(ConjugateGradient, self).tf_initialize(x_init)

        conjugate = residual = [t - fx for t, fx in zip(b, self.fn_x(x_init))]

        squared_residual = tf.add_n(inputs=[tf.reduce_sum(input_tensor=(res * res)) for res in residual])

        return initial_args + (conjugate, residual, squared_residual)

Initialization step preparing the arguments for the first iteration of the loop body:
$x_0, 0, p_0, r_0, r_0^2$.

Args:
x_init: Initial solution guess $x_0$, zero vector if None.
b: The right-hand side $b$ of the system of linear equations.

Returns:
Initial arguments for tf_step.


def error_messages(self, driver_id=None):

        if driver_id is not None:
            assert isinstance(driver_id, ray.DriverID)
            return self._error_messages(driver_id)

        error_table_keys = self.redis_client.keys(
            ray.gcs_utils.TablePrefix_ERROR_INFO_string + "*")
        driver_ids = [
            key[len(ray.gcs_utils.TablePrefix_ERROR_INFO_string):]
            for key in error_table_keys
        ]

        return {
            binary_to_hex(driver_id): self._error_messages(
                ray.DriverID(driver_id))
            for driver_id in driver_ids
        }

Get the error messages for all drivers or a specific driver.

Args:
driver_id: The specific driver to get the errors for. If this is
None, then this method retrieves the errors for all drivers.

Returns:
A dictionary mapping driver ID to a list of the error messages for
that driver.


def compute_metrics_cv(self, X, y, **kwargs):
    results = self.cv_score_mean(X, y)
    return results

Compute cross-validated metrics.

Trains this model on data X with labels y.
Returns a list of dict with keys name, scoring_name, value.

Args:
X (Union[np.array, pd.DataFrame]): data
y (Union[np.array, pd.DataFrame, pd.Series]): labels


def get_pipeline_id(app='', name=''):

    return_id = None

    pipelines = get_all_pipelines(app=app)

    for pipeline in pipelines:
        LOG.debug('ID of %(name)s: %(id)s', pipeline)

        if pipeline['name'] == name:
            return_id = pipeline['id']
            LOG.info('Pipeline %s found, ID: %s', name, return_id)
            break

    return return_id

Get the ID for Pipeline _name_.

Args:
app (str): Name of Spinnaker Application to search.
name (str): Name of Pipeline to get ID for.

Returns:
str: ID of specified Pipeline.
None: Pipeline or Spinnaker Appliation not found.


def __init__(self, executable_path: _PATH = 'default', port: Union[int, str] = 5037, env: Dict = None, service_args: Union[list, tuple] = None) -> None:

        self._service_args = service_args or []

        super(Service, self).__init__(executable_path, port=port, env=env)

Creates a new instance of the Service.

Args:
executable_path: Path to the AndroidDriver.
port: Port the service is running on.
env: Environment variables.
service_args: List of args to pass to the androiddriver service.


def get_original(self):
    pk_value = self._get_pk_value()
    if (isinstance(pk_value, int) and (not self._original)):
        self._original = self.select().where((self.__class__.id == pk_value)).get()
    return self._original

Get the original instance of this instance before it's updated.

Returns:
fleaker.peewee.EventMixin:
The original instance of the model.


def __init__(self, table_id=None, active_count=None, lookup_count=None,
                 matched_count=None):

        super().__init__()
        self.table_id = table_id
        self.active_count = active_count
        self.lookup_count = lookup_count
        self.matched_count = matched_count

Create a TableStats with the optional parameters below.

Args:
table_id (int): Identifier of table.  Lower numbered tables are
consulted first.
active_count (int): Number of active entries.
lookup_count (int): Number of packets looked up in table.
matched_count (int): Number of packets that hit table.


def press(keys, presses=1, interval=0.0, pause=None, _pause=True):
    if (type(keys) == str):
        keys = [keys]
    else:
        lowerKeys = []
        for s in keys:
            if (len(s) > 1):
                lowerKeys.append(s.lower())
            else:
                lowerKeys.append(s)
    interval = float(interval)
    for i in range(presses):
        for k in keys:
            _failSafeCheck()
            platformModule._keyDown(k)
            platformModule._keyUp(k)
        time.sleep(interval)
    _autoPause(pause, _pause)

Performs a keyboard key press down, followed by a release.

Args:
key (str, list): The key to be pressed. The valid names are listed in
KEYBOARD_KEYS. Can also be a list of such strings.
presses (integer, optiional): the number of press repetition
1 by default, for just one press
interval (float, optional): How many seconds between each press.
0.0 by default, for no pause between presses.
pause (float, optional): How many seconds in the end of function process.
None by default, for no pause in the end of function process.
Returns:
None


def _force_disconnect_action(self, action):

        conn_key = action.data['id']
        if self._get_connection_state(conn_key) == self.Disconnected:
            return

        data = self._get_connection(conn_key)

        if data['state'] == self.Connecting:
            callback = data['action'].data['callback']
            callback(data['connection_id'], self.id, False, 'Unexpected disconnection')
        elif data['state'] == self.Disconnecting:
            callback = data['action'].data['callback']
            callback(data['connection_id'], self.id, True, None)
        elif data['state'] == self.InProgress:
            callback = data['action'].data['callback']
            if data['microstate'] == 'rpc':
                callback(False, 'Unexpected disconnection', 0xFF, None)
            elif data['microstate'] == 'open_interface':
                callback(False, 'Unexpected disconnection')
            elif data['microstate'] == 'close_interface':
                callback(False, 'Unexpected disconnection')

        connection_id = data['connection_id']
        internal_id = data['internal_id']
        del self._connections[connection_id]
        del self._int_connections[internal_id]

Forcibly disconnect a device.

Args:
action (ConnectionAction): the action object describing what we are
forcibly disconnecting


def update(self, *args, **kwargs):

        for next_dict in chain(args, (kwargs, )):
            for k, v in next_dict.items():
                self[k] = v

Equivalent to the python dict update method.

Update the dictionary with the key/value pairs from other, overwriting
existing keys.

Args:
other (dict): The source of key value pairs to add to headers
Keyword Args:
All keyword arguments are stored in header directly

Returns:
None


def Exponential(cls, mean: 'TensorFluent', batch_size: Optional[int]=None) -> Tuple[(Distribution, 'TensorFluent')]:
    rate = (1 / mean.tensor)
    dist = tf.distributions.Exponential(rate)
    batch = mean.batch
    if ((not batch) and (batch_size is not None)):
        t = dist.sample(batch_size)
        batch = True
    else:
        t = dist.sample()
    scope = mean.scope.as_list()
    return (dist, TensorFluent(t, scope, batch=batch))

Returns a TensorFluent for the Exponential sampling op with given mean parameter.

Args:
mean: The mean parameter of the Exponential distribution.
batch_size: The size of the batch (optional).

Returns:
The Exponential distribution and a TensorFluent sample drawn from the distribution.


def _read_range(self, start, end=0):

        try:
            with _handle_client_exception():
                return self._client.get_object(*self._client_args, headers=dict(
                    Range=self._http_range(start, end)))[1]

        except _ClientException as exception:
            if exception.http_status == 416:

                return b''
            raise

Read a range of bytes in stream.

Args:
start (int): Start stream position.
end (int): End stream position.
0 To not specify end.

Returns:
bytes: number of bytes read


def copy(self, source, dest):

        if not self.copyable:
            raise IOError('Driver does not support raster copying')
        if not isinstance(source, Raster):
            source = Raster(source)
            should_close = True
        else:
            should_close = False
        if source.name == dest:
            raise ValueError(
                'Input and output are the same location: %s' % source.name)
        settings = driverdict_tolist(self.settings)
        ds = self.CreateCopy(dest, source.ds, self.strictmode,
                             options=settings)
        if should_close:
            source.close()
        return Raster(ds)

Returns a copied Raster instance.

Arguments:
source -- the source Raster instance or filepath as str
dest -- destination filepath as str


def __init__(self, item_type=None, min_length=None, max_length=None, empty=True):

        super(ListTypeChecker, self).__init__(
            iter_type=list, item_type=item_type, min_length=min_length, max_length=max_length, empty=empty
        )

Initialization method.

Args:
item_type (type): the type of the items inside the list.
min_length (int): minimum length of the list (included).
max_length (int): maximum length of the list (included).
empty (bool): whether empty list is allowed.


def get_unconditional_inputs(self, num_samples=1):
    input_ids = torch.ones((num_samples, 1), device=self.device, dtype=torch.int64) * self.config.vocab_size
    user_audio_codes = torch.ones((num_samples, self.num_codebooks, 1), device=self.device, dtype=torch.int64) * self.config.audio_vocab_size
    moshi_audio_codes = torch.ones((num_samples, self.num_codebooks, 1), device=self.device, dtype=torch.int64) * self.config.audio_vocab_size
    attention_mask = torch.ones((num_samples, 1), device=self.device, dtype=torch.long)
    return MoshiUnconditionalInput(input_ids=input_ids, user_audio_codes=user_audio_codes, moshi_audio_codes=moshi_audio_codes, attention_mask=attention_mask)

Helper function to get null inputs for unconditional generation, enabling the model to be used without the
feature extractor or tokenizer.

Args:
num_samples (int, *optional*):
Number of audio samples to unconditionally generate.
max_new_tokens (int, *optional*):
Number of tokens to generate for each sample. More tokens means longer audio samples, at the expense of
longer inference (since more audio tokens need to be generated per sample).

Example:
```python
>>> from transformers import MoshiForConditionalGeneration

>>> model = MoshiForConditionalGeneration.from_pretrained("kmhf/hf-moshiko-pytorch-bf16")

>>> # get the unconditional (or 'null') inputs for the model
>>> unconditional_inputs = model.get_unconditional_inputs(num_samples=1)
>>> audio_samples = model.generate(**unconditional_inputs, max_new_tokens=256)
```


def call_api(self, method, url, headers=None, params=None, data=None, files=None, timeout=None):
    method = method.upper()
    headers = (deepcopy(headers) or {})
    headers['Accept'] = self.accept_type
    params = (deepcopy(params) or {})
    data = (data or {})
    files = (files or {})
    if (self.username and self.api_key):
        params.update(self.get_credentials())
    url = urljoin(self.base_url, url)
    r = requests.request(method, url, headers=headers, params=params, files=files, data=data, timeout=timeout)
    return (r, r.status_code)

Call API.

This returns object containing data, with error details if applicable.

Args:
method (str): The HTTP method to use.
url (str): Resource location relative to the base URL.
headers (dict or None): Extra request headers to set.
params (dict or None): Query-string parameters.
data (dict or None): Request body contents for POST or PUT requests.
files (dict or None: Files to be passed to the request.
timeout (int): Maximum time before timing out.

Returns:
ResultParser or ErrorParser.


def zero_fraction(value, name=None):
    with ops.name_scope(name, 'zero_fraction', [value]):
        value = ops.convert_to_tensor(value, name='value')
        size = array_ops.size(value, out_type=dtypes.int64)
        num_nonzero = tf_cond.cond(size <= dtypes.int32.max, true_fn=lambda: math_ops.cast(_count_nonzero(value, dtype=dtypes.int32), dtype=dtypes.int64), false_fn=lambda: _count_nonzero(value, dtype=dtypes.int64))
        with ops.name_scope('counts_to_fraction'):
            num_zero = size - num_nonzero
            num_zero_float32 = math_ops.cast(num_zero, dtype=dtypes.float32)
            size_float32 = math_ops.cast(size, dtype=dtypes.float32)
            zero_fraction_float32 = num_zero_float32 / size_float32
        return array_ops.identity(zero_fraction_float32, 'fraction')

Returns the fraction of zeros in `value`.

If `value` is empty, the result is `nan`.

This is useful in summaries to measure and report sparsity.  For example,

```python
z = tf.nn.relu(...)
summ = tf.compat.v1.summary.scalar('sparsity', tf.nn.zero_fraction(z))
```

Args:
value: A tensor of numeric type.
name: A name for the operation (optional).

Returns:
The fraction of zeros in `value`, with type `float32`.


def extract_resources_from_bundle(bundle: message.Message, *, resource_type: Type[_T]) -> List[_T]:
    if not fhir_types.is_type_or_profile_of('http:
        raise TypeError(f'{bundle.DESCRIPTOR.name} is not a type or profile of Bundle.')
    contained_resource_field = path_utils.camel_case_to_snake_case(resource_type.DESCRIPTOR.name)
    return [getattr(entry.resource, contained_resource_field) for entry in cast(Any, bundle).entry if entry.resource.HasField(contained_resource_field)]

Returns a list of resources of type `resource_type` from `bundle`.

Args:
bundle: The FHIR Bundle to examine.
resource_type: The message type of the resource to return.

Returns:
A list of resources of type `resource_type` belonging to the bundle.

Raises:
TypeError: In the event that `bundle` is not of type "Bundle".
ValueError: In the event that a field corresponding to the "snake_case" name
of `resource_type` does not exist on `Bundle.Entry`.


def __init__(self, statistics: calib_stats_pb2.CalibrationStatistics, calib_opts: stablehlo_quant_config_pb2.CalibrationOptions):
    super().__init__(statistics, calib_opts)
    hist_stats = statistics.histogram_statistics
    self._bin_width = hist_stats.bin_width
    self._lower_bound = hist_stats.lower_bound
    self._hist_freq = np.array(hist_stats.hist_freq)
    self._num_bins = len(self._hist_freq)
    self._num_bits = 8
    first_mid = self._lower_bound + self._bin_width / 2
    last_mid = first_mid + (self._num_bins - 1) * self._bin_width
    self._hist_mids = np.linspace(first_mid, last_mid, self._num_bins)

Builds histogram using statistics.histogram_statistics.

lower_bound                                    hist_mid
v                                            v
|=========|=========|=========|=========|=========|
bin width

Args:
statistics: Collected calibration statistics.
calib_opts: Calibration options used for calculating min and max.


def fixup_for_packaged():
    if exists(join(ROOT, 'PKG-INFO')):
        if (('--build-js' in sys.argv) or ('--install-js' in sys.argv)):
            print(SDIST_BUILD_WARNING)
            if ('--build-js' in sys.argv):
                sys.argv.remove('--build-js')
            if ('--install-js' in sys.argv):
                sys.argv.remove('--install-js')
        if ('--existing-js' not in sys.argv):
            sys.argv.append('--existing-js')

If we are installing FROM an sdist, then a pre-built BokehJS is
already installed in the python source tree.

The command line options ``--build-js`` or ``--install-js`` are
removed from ``sys.argv``, with a warning.

Also adds ``--existing-js`` to ``sys.argv`` to signal that BokehJS is
already packaged.

Returns:
None


def get_parent_of_type(typ, obj):

    if type(typ) is not text:
        typ = typ.__name__

    while hasattr(obj, 'parent'):
        obj = obj.parent
        if obj.__class__.__name__ == typ:
            return obj

Finds first object up the parent chain of the given type.
If no parent of the given type exists None is returned.

Args:
typ(str or python class): The type of the model object we are
looking for.
obj (model object): Python model object which is the start of the
search process.


def _common_args(self):
    return {'metadata': self._metadata.SerializeToString(), 'output_shapes': self._flat_shapes, 'output_types': self._flat_types}

Helper for generating arguments that are common across most dataset ops.

Most dataset op constructors expect `output_shapes` and `output_types`
arguments that represent the flattened structure of an element, as well as a
`metadata` argument for additional metadata such as user-defined dataset
name. This helper function generates common attributes as a keyword argument
dictionary, allowing `Dataset._variant_tensor` implementations to pass
`**self._common_args` to the op constructor.

Returns:
A dictionary of keyword arguments that can be passed to a dataset op
constructor.


def config_from_url(u, **kwargs):

    path = u.path.lstrip("/").split("/")
    if len(path) > 2 or not path:
        raise AssertionError("zmq url format: zmq:

    typ = path[0].upper()

    try:
        topic = path[1]
    except IndexError as _:
        topic = ''

    param = dict(urllib.parse.parse_qsl(u.query))

    transport = param.get("transport", "tcp")

    _id = "%s-%s-%s-%s" % (typ, topic, transport, u.netloc)
    if kwargs.get("prefix") is not None:
        _id = "%s-%s" % (kwargs.get("prefix"), _id)

    return {
        "id" : _id,
        "typ_str" : typ,
        "typ" : getattr(zmq, typ),
        "topic" : topic,
        "transport" : transport,
        "url" : "%s:
    }

Returns dict containing zmq configuration arguments
parsed from xbahn url

Arguments:

- u (urlparse.urlparse result)

Returns:

dict:
- id (str): connection index key
- typ_str (str): string representation of zmq socket type
- typ (int): zmq socket type (PUB, SUB, REQ, REP, PUSH, PULL)
- topic (str): subscription topic
- url (str): url to use with zmq's bind function


def broadcast_to(input: ragged_tensor.RaggedOrDense, shape: dynamic_ragged_shape.DynamicRaggedShape) -> Union[ragged_tensor.RaggedTensor, tensor_lib.Tensor]:
    return dynamic_ragged_shape.broadcast_to(input, shape)

Broadcasts a potentially ragged tensor to a ragged shape.

Tiles `input` as necessary to match the given shape.

Behavior is undefined if `input` is not broadcast-compatible with `shape`.

Args:
input: The potentially ragged tensor to broadcast.
shape: A `DynamicRaggedShape`

Returns:
A potentially ragged tensor whose values are taken from
`input`, and whose shape matches `shape`.


def convert_inference_tf_type_to_tflite_type(tf_type: dtypes.DType, usage: str='') -> _types_pb2.IODataType:
    mapping = {dtypes.float32: _types_pb2.FLOAT, dtypes.uint8: _types_pb2.QUANTIZED_UINT8, dtypes.int8: _types_pb2.QUANTIZED_INT8, dtypes.int16: _types_pb2.QUANTIZED_INT16}
    tflite_type = mapping.get(tf_type)
    if tflite_type is None:
        raise ValueError('Unsupported TensorFlow type `{0}` provided for the {1}'.format(tf_type, usage))
    return tflite_type

Convert inference type from tf type to tflite type.

Args:
tf_type: TensorFlow type.
usage: Text describing the reason for invoking this function.

Raises:
ValueError: If `tf_type` is unsupported.

Returns:
tflite_type: TFLite type. Refer to compiler/mlir/lite/types.proto.


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

Set global 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:
None


def list_knowledge_bases(project_id):
    import dialogflow_v2beta1 as dialogflow
    client = dialogflow.KnowledgeBasesClient()
    project_path = client.project_path(project_id)
    print('Knowledge Bases for: {}'.format(project_id))
    for knowledge_base in client.list_knowledge_bases(project_path):
        print(' - Display Name: {}'.format(knowledge_base.display_name))
        print(' - Knowledge ID: {}\n'.format(knowledge_base.name))

Lists the Knowledge bases belonging to a project.

Args:
project_id: The GCP project linked with the agent.


def db_en020(self, value=None):

        if value is not None:
            try:
                value = float(value)
            except ValueError:
                raise ValueError('value {} need to be of type float '
                                 'for field `db_en020`'.format(value))

        self._db_en020 = value

Corresponds to IDD Field `db_en020`
mean coincident dry-bulb temperature to
Enthalpy corresponding to 2.0% annual cumulative frequency of occurrence

Args:
value (float): value for IDD Field `db_en020`
Unit: C
if `value` is None it will not be checked against the
specification and is assumed to be a missing value

Raises:
ValueError: if `value` is not a valid value


def apply_regression(input_, regression_fn, target, regression_args=(), regression_kwargs=None, name=PROVIDED, loss_weight=None, per_example_weights=None):
    if (regression_kwargs is None):
        regression_kwargs = {}
    if ((name is not None) and ('name' not in regression_kwargs)):
        regression_kwargs['name'] = name
    elif (name is None):
        name = input_.tensor.op.name
    tensor = input_.tensor
    loss = regression_fn(tensor, target, *regression_args, **regression_kwargs)
    if (loss_weight is not None):
        loss *= loss_weight
    if (per_example_weights is not None):
        per_example_weights = _convert_and_assert_per_example_weights_compatible(input_, per_example_weights, dtype=loss.dtype)
        loss *= per_example_weights
    if (name is None):
        name = loss.op.name
    if (tensor.get_shape()[0].value is not None):
        avg_loss = (tf.reduce_sum(loss) / tensor.get_shape()[0].value)
    else:
        avg_loss = tf.reduce_mean(loss)
    return input_.add_loss(avg_loss, name=name)

Applies the given regression and adds the loss to the bookkeeper.

This does not change tensor.
Args:
input_: A Tensor or a Pretty Tensor holding the input.
regression_fn: A function that takes (in order) tensor, labels.
target: The targe of the regression.
regression_args: Other arguments for the regression.
regression_kwargs: Keyword args for the regression.
name: The name, also added to regression_kwargs.
loss_weight: A scalar multiplier for the loss.
per_example_weights: A Tensor with a weight per example.
Returns:
The loss tensor's name.
Raises:
ValueError: If the target is not a compatible shape with input_.


def _GetParsersFromPresetCategory(cls, category):
    preset_definition = cls._presets.GetPresetByName(category)
    if (preset_definition is None):
        return []
    preset_names = cls._presets.GetNames()
    parser_names = set()
    for element_name in preset_definition.parsers:
        if (element_name in preset_names):
            category_parser_names = cls._GetParsersFromPresetCategory(element_name)
            parser_names.update(category_parser_names)
        else:
            parser_names.add(element_name)
    return sorted(parser_names)

Retrieves the parser names of specific preset category.

Args:
category (str): parser preset categories.

Returns:
list[str]: parser names in alphabetical order.


def flat_values(self):
    rt_values = self.values
    while isinstance(rt_values, RaggedTensor):
        rt_values = rt_values.values
    return rt_values

The innermost `values` tensor for this ragged tensor.

Concretely, if `rt.values` is a `Tensor`, then `rt.flat_values` is
`rt.values`; otherwise, `rt.flat_values` is `rt.values.flat_values`.

Conceptually, `flat_values` is the tensor formed by flattening the
outermost dimension and all of the ragged dimensions into a single
dimension.

`rt.flat_values.shape = [nvals] + rt.shape[rt.ragged_rank + 1:]`
(where `nvals` is the number of items in the flattened dimensions).

Returns:
A `Tensor`.

#### Example:

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


def __register_notifiers(self):
    notifiers = {}
    for entry_point in CINQ_PLUGINS['cloud_inquisitor.plugins.notifiers']['plugins']:
        cls = entry_point.load()
        notifiers[cls.notifier_type] = cls.validation
    return notifiers

Lists all notifiers to be able to provide metadata for the frontend

Returns:
`list` of `dict`


def __init__(self, connections, picker_class=RoundRobinPicker):

        self.connections = connections
        self.picker = picker_class()

Initializes a :class:`~bigchaindb_driver.pool.Pool` instance.

Args:
connections (list): List of
:class:`~bigchaindb_driver.connection.Connection` instances.


def connection_delay(self, node_id):

        conn = self._conns.get(node_id)
        if conn is None:
            return 0
        return conn.connection_delay()

Return the number of milliseconds to wait, based on the connection
state, before attempting to send data. When disconnected, this respects
the reconnect backoff time. When connecting, returns 0 to allow
non-blocking connect to finish. When connected, returns a very large
number to handle slow/stalled connections.

Arguments:
node_id (int): The id of the node to check

Returns:
int: The number of milliseconds to wait.


def get(self, profile_id):

        if profile_id not in self._profiles:
            try:
                self._profiles[profile_id] = self._get_profile(profile_id)
            except (ValueError,
                    IOError) as e:
                six.raise_from(RegistryError(e), e)
        return self._profiles[profile_id]

Returns the profile with the received ID as a dict

If a local copy of the profile exists, it'll be returned. If not, it'll
be downloaded from the web. The results are cached, so any subsequent
calls won't hit the filesystem or the web.

Args:
profile_id (str): The ID of the profile you want.

Raises:
RegistryError: If there was some problem opening the profile file
or its format was incorrect.


def run(self, group_x=1, group_y=1, group_z=1) -> None:

        return self.mglo.run(group_x, group_y, group_z)

Run the compute shader.

Args:
group_x (int): The number of work groups to be launched in the X dimension.
group_y (int): The number of work groups to be launched in the Y dimension.
group_z (int): The number of work groups to be launched in the Z dimension.


def _colourise(text: str, colour: str) -> str:

    if COLOUR:
        text = style(text, fg=colour, bold=True)
    return text

Colour text, if possible.

Args:
text: Text to colourise
colour: Colour to display text in
Returns:
Colourised text, if possible


def connect(self, component):

        if not isinstance(component, ThreadPool):
            raise TypeError('"component" must be a ThreadPool object')
        component.in_queue = self.out_queue
        return component

Connect two ThreadPools.

The ``in_queue`` of the second pool will be set as the ``out_queue`` of
the current pool, thus all the output will be input to the second pool.

Args:
component (ThreadPool): the ThreadPool to be connected.
Returns:
ThreadPool: the modified second ThreadPool.


def add_logger(self, name, address, conn_type, log_dir_path=None, **kwargs):
    capture_handler_conf = kwargs
    if (not log_dir_path):
        log_dir_path = self._mngr_conf['root_log_directory']
    log_dir_path = os.path.normpath(os.path.expanduser(log_dir_path))
    capture_handler_conf['log_dir'] = log_dir_path
    capture_handler_conf['name'] = name
    if ('rotate_log' not in capture_handler_conf):
        capture_handler_conf['rotate_log'] = True
    transforms = []
    if ('pre_write_transforms' in capture_handler_conf):
        for transform in capture_handler_conf['pre_write_transforms']:
            if isinstance(transform, str):
                if globals().has_key(transform):
                    transforms.append(globals().get(transform))
                else:
                    msg = 'Unable to load data transformation "{}" for handler "{}"'.format(transform, capture_handler_conf['name'])
                    log.warn(msg)
            elif hasattr(transform, '__call__'):
                transforms.append(transform)
            else:
                msg = 'Unable to determine how to load data transform "{}"'.format(transform)
                log.warn(msg)
    capture_handler_conf['pre_write_transforms'] = transforms
    address_key = str(address)
    if (address_key in self._stream_capturers):
        capturer = self._stream_capturers[address_key][0]
        capturer.add_handler(capture_handler_conf)
        return
    socket_logger = SocketStreamCapturer(capture_handler_conf, address, conn_type)
    greenlet = gevent.spawn(socket_logger.socket_monitor_loop)
    self._stream_capturers[address_key] = (socket_logger, greenlet)
    self._pool.add(greenlet)

Add a new stream capturer to the manager.

Add a new stream capturer to the manager with the provided configuration
details. If an existing capturer is monitoring the same address the
new handler will be added to it.

Args:
name:
A string defining the new capturer's name.

address:
A tuple containing address data for the capturer. Check the
:class:`SocketStreamCapturer` documentation for what is
required.

conn_type:
A string defining the connection type. Check the
:class:`SocketStreamCapturer` documentation for a list of valid
options.

log_dir_path:
An optional path defining the directory where the
capturer should write its files. If this isn't provided the root
log directory from the manager configuration is used.


def with_rank_at_least(self, rank):
    if ((self.ndims is not None) and (self.ndims < rank)):
        raise ValueError(('Shape %s must have rank at least %d' % (self, rank)))
    else:
        return self

Returns a shape based on `self` with at least the given rank.

Args:
rank: An integer.

Returns:
A shape that is at least as specific as `self` with at least the given
rank.

Raises:
ValueError: If `self` does not represent a shape with at least the given
`rank`.


def _make_estimator_serving_session(estimator, serving_input_fn, checkpoint_path):
    with tf.Graph().as_default() as g:
        mode = tf_v1.estimator.ModeKeys.PREDICT
        tf_v1.train.create_global_step(g)
        tf_v1.set_random_seed(estimator.config.tf_random_seed)
        serving_input_receiver = serving_input_fn()
        estimator_spec = estimator.model_fn(features=serving_input_receiver.features, labels=None, mode=mode, config=estimator.config)
        session = tf_v1.Session(config=estimator._session_config)
        with session.as_default():
            saver_for_restore = (estimator_spec.scaffold.saver or tf_v1.train.Saver(sharded=True))
            saver_for_restore.restore(session, checkpoint_path)
        return session

Returns a session constructed using `estimator` and `serving_input_fn`.

The Estimator API does not provide an API to construct a graph and session,
making it necessary for this function to replicate how an estimator builds
a graph.

This code is based on `Estimator.export_savedmodel` (another function that
has to replicate how an estimator builds a graph).

Args:
estimator: tf.Estimator to use when constructing the session.
serving_input_fn: A function that takes no arguments and returns a
`ServingInputReceiver`. It is used to construct the session.
checkpoint_path: The checkpoint path to restore in the session. Must not
be None.


def median(data):
    ordered = sorted(data)
    length = len(ordered)
    if ((length % 2) == 0):
        return ((ordered[(math.floor((length / 2)) - 1)] + ordered[math.floor((length / 2))]) / 2.0)
    elif ((length % 2) != 0):
        return ordered[math.floor((length / 2))]

Calculates  the median of a list of integers or floating point numbers.

Args:
data: A list of integers or floating point numbers

Returns:
Sorts the list numerically and returns the middle number if the list has an odd number
of items. If the list contains an even number of items the mean of the two middle numbers
is returned.


def reset_port_protection(self, id_or_uri, timeout=-1):

        uri = self._client.build_uri(id_or_uri) + "/resetportprotection"
        return self._client.update_with_zero_body(uri, timeout)

Triggers a reset of port protection.

Cause port protection to be reset on all the interconnects of the logical interconnect that matches ID.

Args:
id_or_uri: Can be either the interconnect id or the interconnect uri.
timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation
in OneView; it just stops waiting for its completion.

Returns:
dict: The interconnect.


def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    if token_ids_1 is None:
        return [self.cls_token_id] + token_ids_0 + [self.sep_token_id]
    cls = [self.cls_token_id]
    sep = [self.sep_token_id]
    return cls + token_ids_0 + sep + token_ids_1 + sep

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
adding special tokens. A Big Bird sequence has the following format:

- single sequence: `[CLS] X [SEP]`
- pair of sequences: `[CLS] A [SEP] B [SEP]`

Args:
token_ids_0 (`List[int]`):
List of IDs to which the special tokens will be added.
token_ids_1 (`List[int]`, *optional*):
Optional second list of IDs for sequence pairs.

Returns:
`List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.


def ungzip(file_path, extract_path: Path = None):

    CHUNK = 16 * 1024
    file_path = Path(file_path)
    extract_path = extract_path or file_path.with_suffix('')

    with gzip.open(file_path, 'rb') as fin, extract_path.open('wb') as fout:
        while True:
            block = fin.read(CHUNK)
            if not block:
                break
            fout.write(block)

Simple .gz archive extractor

Args:
file_path: path to the gzip file to be extracted
extract_path: path where the file will be extracted


def _illegal_character(c, ctx, message=''):
    container_type = (((ctx.container.ion_type is None) and 'top-level') or ctx.container.ion_type.name)
    value_type = (((ctx.ion_type is None) and 'unknown') or ctx.ion_type.name)
    if (c is None):
        header = 'Illegal token'
    else:
        c = ('EOF' if BufferQueue.is_eof(c) else _chr(c))
        header = ('Illegal character %s' % (c,))
    raise IonException(('%s at position %d in %s value contained in %s. %s Pending value: %s' % (header, ctx.queue.position, value_type, container_type, message, ctx.value)))

Raises an IonException upon encountering the given illegal character in the given context.

Args:
c (int|None): Ordinal of the illegal character.
ctx (_HandlerContext):  Context in which the illegal character was encountered.
message (Optional[str]): Additional information, as necessary.


def ctype_to_dtype(cl_type, mot_float_type='float'):
    if is_vector_ctype(cl_type):
        (raw_type, vector_length) = split_vector_ctype(cl_type)
        if (raw_type == 'mot_float_type'):
            if is_vector_ctype(mot_float_type):
                (raw_type, _) = split_vector_ctype(mot_float_type)
            else:
                raw_type = mot_float_type
        vector_type = (raw_type + str(vector_length))
        return getattr(cl_array.vec, vector_type)
    else:
        if (cl_type == 'mot_float_type'):
            cl_type = mot_float_type
        data_types = [('char', np.int8), ('uchar', np.uint8), ('short', np.int16), ('ushort', np.uint16), ('int', np.int32), ('uint', np.uint32), ('long', np.int64), ('ulong', np.uint64), ('float', np.float32), ('double', np.float64)]
        for (ctype, dtype) in data_types:
            if (ctype == cl_type):
                return dtype

Get the numpy dtype of the given cl_type string.

Args:
cl_type (str): the CL data type to match, for example 'float' or 'float4'.
mot_float_type (str): the C name of the ``mot_float_type``. The dtype will be looked up recursively.

Returns:
dtype: the numpy datatype


def decode_body(headers: MutableMapping, body: bytes) -> dict:

    type_, encoding = parse_content_type(headers)
    decoded_body = body.decode(encoding)

    if type_ == "application/json":
        payload = json.loads(decoded_body)
    else:
        if decoded_body == "ok":
            payload = {"ok": True}
        else:
            payload = {"ok": False, "data": decoded_body}

    return payload

Decode the response body

For 'application/json' content-type load the body as a dictionary

Args:
headers: Response headers
body: Response body

Returns:
decoded body


def top_prior(name, z_shape, learn_prior='normal', temperature=1.0):
    with tf.variable_scope(name, reuse=tf.AUTO_REUSE):
        h = tf.zeros(z_shape, dtype=tf.float32)
        if (learn_prior == 'normal'):
            prior_dist = tfp.distributions.Normal(h, tf.exp(h))
        elif (learn_prior == 'single_conv'):
            prior_dist = single_conv_dist('top_learn_prior', h)
        else:
            raise ValueError(('Expected learn_prior to be normal or single_conv got %s' % learn_prior))
        return TemperedNormal(prior_dist.loc, prior_dist.scale, temperature)

Unconditional prior distribution.

Args:
name: variable scope
z_shape: Shape of the mean / scale of the prior distribution.
learn_prior: Possible options are "normal" and "single_conv".
If set to "single_conv", the gaussian is parametrized by a
single convolutional layer whose input are an array of zeros
and initialized such that the mean and std are zero and one.
If set to "normal", the prior is just a Gaussian with zero
mean and unit variance.
temperature: Temperature with which to sample from the Gaussian.
Returns:
objective: 1-D Tensor shape=(batch_size,) summed across spatial components.
Raises:
ValueError: If learn_prior not in "normal" or "single_conv"


def main(argv):
    parser = _BuildParser()
    args = parser.parse_args(argv[1:])
    style_config = args.style
    if args.style_help:
        _PrintHelp(args)
        return 0
    if args.lines and len(args.files) > 1:
        parser.error('cannot use -l/--lines with more than one file')
    lines = _GetLines(args.lines) if args.lines is not None else None
    if not args.files:
        if args.in_place or args.diff:
            parser.error('cannot use --in-place or --diff flags when reading from stdin')
        original_source = []
        while True:
            if hasattr(sys.stdin, 'closed') and sys.stdin.closed:
                break
            try:
                original_source.append(_raw_input())
            except EOFError:
                break
            except KeyboardInterrupt:
                return 1
        if style_config is None and (not args.no_local_style):
            style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
        source = [line.rstrip() for line in original_source]
        source[0] = _removeBOM(source[0])
        try:
            reformatted_source, _ = yapf_api.FormatCode(str('\n'.join(source).replace('\r\n', '\n') + '\n'), filename='<stdin>', style_config=style_config, lines=lines)
        except errors.YapfError:
            raise
        except Exception as e:
            raise errors.YapfError(errors.FormatErrorMsg(e))
        file_resources.WriteReformattedCode('<stdout>', reformatted_source)
        return 0
    exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(os.getcwd())
    files = file_resources.GetCommandLineFiles(args.files, args.recursive, (args.exclude or []) + exclude_patterns_from_ignore_file)
    if not files:
        raise errors.YapfError('input filenames did not match any python files')
    changed = FormatFiles(files, lines, style_config=args.style, no_local_style=args.no_local_style, in_place=args.in_place, print_diff=args.diff, parallel=args.parallel, quiet=args.quiet, verbose=args.verbose, print_modified=args.print_modified)
    return 1 if changed and (args.diff or args.quiet) else 0

Main program.

Arguments:
argv: command-line arguments, such as sys.argv (including the program name
in argv[0]).

Returns:
Zero on successful program termination, non-zero otherwise.
With --diff: zero if there were no changes, non-zero otherwise.

Raises:
YapfError: if none of the supplied files were Python files.


def update_pos(self, pos_id, name, pos_type, location=None):

        arguments = {'name': name,
                     'type': pos_type,
                     'location': location}
        return self.do_req('PUT',
                           self.merchant_api_base_url + '/pos/' +
                           pos_id + '/', arguments)

Update POS resource. Returns the raw response object.

Arguments:
pos_id:
POS id as chosen on registration
name:
Human-readable name of the POS, used for displaying payment
request origin to end user
pos_type:
POS type
location:
Merchant location


def defaultannotator(self, annotationtype, set=None):
    if (inspect.isclass(annotationtype) or isinstance(annotationtype, AbstractElement)):
        annotationtype = annotationtype.ANNOTATIONTYPE
    if (not set):
        set = self.defaultset(annotationtype)
    try:
        return self.annotationdefaults[annotationtype][set]['annotator']
    except KeyError:
        raise NoDefaultError

Obtain the default annotator for the specified annotation type and set.

Arguments:
annotationtype: The type of annotation, this is conveyed by passing the corresponding annototion class (such as :class:`PosAnnotation` for example), or a member of :class:`AnnotationType`, such as ``AnnotationType.POS``.
set (str): the set, should formally be a URL pointing to the set definition

Returns:
the set (str)

Raises:
:class:`NoDefaultError` if the annotation type does not exist or if there is ambiguity (multiple sets for the same type)


def from_args_and_dict(cls, args, processor_dict: dict[str, Any], **kwargs):
    processor_dict = processor_dict.copy()
    return_unused_kwargs = kwargs.pop('return_unused_kwargs', False)
    if 'processor_class' in processor_dict:
        del processor_dict['processor_class']
    if 'auto_map' in processor_dict:
        del processor_dict['auto_map']
    processor_dict.update(kwargs)
    accepted_args_and_kwargs = cls.__init__.__code__.co_varnames[:cls.__init__.__code__.co_argcount][1:]
    unused_kwargs, valid_kwargs = cls.validate_init_kwargs(processor_config=processor_dict, valid_kwargs=accepted_args_and_kwargs)
    args_to_remove = [i for i, arg in enumerate(accepted_args_and_kwargs) if arg in processor_dict]
    args = [arg for i, arg in enumerate(args) if i not in args_to_remove]
    processor = cls(*args, **valid_kwargs)
    logger.info(f'Processor {processor}')
    if return_unused_kwargs:
        return (processor, unused_kwargs)
    else:
        return processor

Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters.

Args:
processor_dict (`Dict[str, Any]`):
Dictionary that will be used to instantiate the processor object. Such a dictionary can be
retrieved from a pretrained checkpoint by leveraging the
[`~processing_utils.ProcessingMixin.to_dict`] method.
kwargs (`Dict[str, Any]`):
Additional parameters from which to initialize the processor object.

Returns:
[`~processing_utils.ProcessingMixin`]: The processor object instantiated from those
parameters.


def lines(start=None, end=None, reverse=False, selection=False):
    if selection:
        (start, end) = get_selection()
    else:
        (start, end) = fix_addresses(start, end)
    if (not reverse):
        item = idaapi.get_item_head(start)
        while (item < end):
            (yield Line(item))
            item += idaapi.get_item_size(item)
    else:
        item = idaapi.get_item_head((end - 1))
        while (item >= start):
            (yield Line(item))
            item = idaapi.get_item_head((item - 1))

Iterate lines in range.

Args:
start: Starting address, start of IDB if `None`.
end: End address, end of IDB if `None`.
reverse: Set to true to iterate in reverse order.
selection: If set to True, replaces start and end with current selection.

Returns:
iterator of `Line` objects.


def transfer(self, payment_id, data={}, **kwargs):
    url = '{}/{}/transfers'.format(self.base_url, payment_id)
    return self.post_url(url, data, **kwargs)

Create Transfer for given Payment Id

Args:
payment_id : Id for which payment object has to be transfered

Returns:
Payment dict after getting transfered


def _gradient(self, diff, d, coords):

        denom = np.copy(d)
        denom[denom == 0] = 1e-5

        with np.errstate(divide='ignore', invalid='ignore'):
            K = -2 * diff / denom

        K[np.isnan(K)] = 0

        g = np.empty_like(coords)
        for n in range(self.n):
            for i in range(self.m):

                g[i, n] = ((coords[i, n] - coords[:, n]) * K[i, :]).sum()

        return g

Compute the gradient.

Args:
diff (`array-like`): [`m`, `m`] matrix. `D` - `d`
d (`array-like`): [`m`, `m`] matrix.
coords (`array-like`): [`m`, `n`] matrix.

Returns:
`np.array`: Gradient, shape [`m`, `n`].


def capture(self, data_buffer=None, log_time=False, debug_print=False, retry_reset=True):
    start = time.time()
    if (data_buffer is None):
        data_buffer = np.ndarray((Lepton.ROWS, Lepton.COLS, 1), dtype=np.uint16)
    elif ((data_buffer.ndim < 2) or (data_buffer.shape[0] < Lepton.ROWS) or (data_buffer.shape[1] < Lepton.COLS) or (data_buffer.itemsize < 2)):
        raise Exception('Provided input array not large enough')
    while True:
        Lepton.capture_segment(self.__handle, self.__xmit_buf, self.__msg_size, self.__capture_buf[0])
        if (retry_reset and ((self.__capture_buf[(20, 0)] & 65295) != 5120)):
            if debug_print:
                print('Garbage frame number reset waiting...')
            time.sleep(0.185)
        else:
            break
    self.__capture_buf.byteswap(True)
    data_buffer[(:, :)] = self.__capture_buf[(:, 2:)]
    end = time.time()
    if debug_print:
        print('---')
        for i in range(Lepton.ROWS):
            fid = self.__capture_buf[(i, 0, 0)]
            crc = self.__capture_buf[(i, 1, 0)]
            fnum = (fid & 4095)
            print('0x{0:04x} 0x{1:04x} : Row {2:2} : crc={1}'.format(fid, crc, fnum))
        print('---')
    if log_time:
        print('frame processed int {0}s, {1}hz'.format((end - start), (1.0 / (end - start))))
    return (data_buffer, data_buffer.sum())

Capture a frame of data.

Captures 80x60 uint16 array of non-normalized (raw 12-bit) data. Returns that frame and a frame_id (which
is currently just the sum of all pixels). The Lepton will return multiple, identical frames at a rate of up
to ~27 Hz, with unique frames at only ~9 Hz, so the frame_id can help you from doing additional work
processing duplicate frames.

Args:
data_buffer (numpy.ndarray): Optional. If specified, should be ``(60,80,1)`` with `dtype`=``numpy.uint16``.

Returns:
tuple consisting of (data_buffer, frame_id)


def are_equal(self, sp1, sp2):
    set1 = set(sp1.elements)
    set2 = set(sp2.elements)
    return (set1.issubset(set2) or set2.issubset(set1))

True if there is some overlap in composition between the species

Args:
sp1: First species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.
sp2: Second species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.

Returns:
True always


def open(self, mode='r', buffering=(- 1), encoding=None, errors=None, newline=None):
    if self._closed:
        self._raise_closed()
    return FakeFileOpen(self.filesystem, use_io=True)(self._path(), mode, buffering, encoding, errors, newline)

Open the file pointed by this path and return a fake file object.

Raises:
IOError: if the target object is a directory, the path is invalid
or permission is denied.


def assert_title(self, title, **kwargs):

        query = TitleQuery(title, **kwargs)

        @self.synchronize(wait=query.wait)
        def assert_title():
            if not query.resolves_for(self):
                raise ExpectationNotMet(query.failure_message)

            return True

        return assert_title()

Asserts that the page has the given title.

Args:
title (str | RegexObject): The string or regex that the title should match.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.

Returns:
True

Raises:
ExpectationNotMet: If the assertion hasn't succeeded during the wait time.


def _min_max_filter(t: List, min_v: str, max_v: str) -> bool:

        def tofloat(value):
            try:
                float(value)
                return float(value)
            except ValueError:
                return False

        for a_token in t:
            if not tofloat(a_token.text):
                return False
            else:
                if min_v and tofloat(min_v):
                    this_v = tofloat(a_token.text)
                    if this_v < tofloat(min_v):
                        return False
                if max_v and tofloat(max_v):
                    this_v = tofloat(a_token.text)
                    if this_v > tofloat(max_v):
                        return False

        return True

Min and Max filter
Args:
t: List, list of tokens
min_v: str
max_v: str

Returns: bool


def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary):
    source_paths = _get_pdf_filenames_at(source_directory)
    (yield len(source_paths))
    for source_path in source_paths:
        output = os.path.join(output_directory, os.path.basename(source_path))
        compress_pdf(source_path, output, ghostscript_binary)
        (yield output)

Compress all PDF files in the current directory and place the output in the
given output directory. This is a generator function that first yields the amount
of files to be compressed, and then yields the output path of each file.

Args:
source_directory (str): Filepath to the source directory.
output_directory (str): Filepath to the output directory.
ghostscript_binary (str): Name of the Ghostscript binary.

Returns:
list(str): paths to outputs.


def mean_minimum_centroid_distance(item_a, item_b, max_value):
    centroids_a = np.array([item_a.center_of_mass(t) for t in item_a.times])
    centroids_b = np.array([item_b.center_of_mass(t) for t in item_b.times])
    distance_matrix = (((centroids_a[(:, 0:1)] - centroids_b.T[0:1]) ** 2) + ((centroids_a[(:, 1:)] - centroids_b.T[1:]) ** 2))
    mean_min_distances = np.sqrt((distance_matrix.min(axis=0).mean() + distance_matrix.min(axis=1).mean()))
    return (np.minimum(mean_min_distances, max_value) / float(max_value))

RMS difference in the minimum distances from the centroids of one track to the centroids of another track

Args:
item_a: STObject from the first set in TrackMatcher
item_b: STObject from the second set in TrackMatcher
max_value: Maximum distance value used as scaling value and upper constraint.

Returns:
Distance value between 0 and 1.


def random_dna(self, random_generator: Union[types.ModuleType, random.Random, None]=None, attach_spec: bool=True, previous_dna: Optional['DNA']=None) -> 'DNA':
    random_generator = random_generator or random
    dna = self._random_dna(random_generator, previous_dna)
    if attach_spec:
        dna.use_spec(self)
    return dna

Returns a random DNA based on current spec.

Args:
random_generator: An optional Random object. If None, the global random
module will be used.
attach_spec: If True, current spec will be attached to the returned DNA.
previous_dna: An optional DNA representing previous DNA. This field might
be useful for generating stateful random DNAs.

Returns:
A random DNA based on current spec.


def _CheckStatusWorkerProcess(self, pid):

    self._RaiseIfNotRegistered(pid)

    process = self._processes_per_pid[pid]

    process_status = self._QueryProcessStatus(process)
    if process_status is None:
      process_is_alive = False
    else:
      process_is_alive = True

    process_information = self._process_information_per_pid[pid]
    used_memory = process_information.GetUsedMemory() or 0

    if self._worker_memory_limit and used_memory > self._worker_memory_limit:
      logger.warning((
          'Process: {0:s} (PID: {1:d}) killed because it exceeded the '
          'memory limit: {2:d}.').format(
              process.name, pid, self._worker_memory_limit))
      self._KillProcess(pid)

    if isinstance(process_status, dict):
      self._rpc_errors_per_pid[pid] = 0
      status_indicator = process_status.get('processing_status', None)

    else:
      rpc_errors = self._rpc_errors_per_pid.get(pid, 0) + 1
      self._rpc_errors_per_pid[pid] = rpc_errors

      if rpc_errors > self._MAXIMUM_RPC_ERRORS:
        process_is_alive = False

      if process_is_alive:
        rpc_port = process.rpc_port.value
        logger.warning((
            'Unable to retrieve process: {0:s} (PID: {1:d}) status via '
            'RPC socket: http:
                process.name, pid, rpc_port))

        processing_status_string = 'RPC error'
        status_indicator = definitions.STATUS_INDICATOR_RUNNING
      else:
        processing_status_string = 'killed'
        status_indicator = definitions.STATUS_INDICATOR_KILLED

      process_status = {
          'processing_status': processing_status_string}

    self._UpdateProcessingStatus(pid, process_status, used_memory)

    for worker_status in self._processing_status.workers_status:
      if worker_status.pid == pid:
        status_indicator = worker_status.status
        break

    if status_indicator in definitions.ERROR_STATUS_INDICATORS:
      logger.error((
          'Process {0:s} (PID: {1:d}) is not functioning correctly. '
          'Status code: {2!s}.').format(process.name, pid, status_indicator))

      self._TerminateProcessByPid(pid)

      replacement_process = None
      for replacement_process_attempt in range(
          self._MAXIMUM_REPLACEMENT_RETRIES):
        logger.info((
            'Attempt: {0:d} to start replacement worker process for '
            '{1:s}').format(replacement_process_attempt + 1, process.name))

        replacement_process = self._StartWorkerProcess(
            process.name, self._storage_writer)
        if replacement_process:
          break

        time.sleep(self._REPLACEMENT_WORKER_RETRY_DELAY)

      if not replacement_process:
        logger.error(
            'Unable to create replacement worker process for: {0:s}'.format(
                process.name))

Checks the status of a worker process.

If a worker process is not responding the process is terminated and
a replacement process is started.

Args:
pid (int): process ID (PID) of a registered worker process.

Raises:
KeyError: if the process is not registered with the engine.


def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None):
    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
    return_dict = return_dict if return_dict is not None else self.config.return_dict
    encoder_hidden_states = encoder_outputs[0]
    if encoder_attention_mask is None:
        batch_size, sequence_length = encoder_hidden_states.shape[:2]
        encoder_attention_mask = jnp.ones((batch_size, sequence_length))
    batch_size, sequence_length = decoder_input_ids.shape
    if decoder_attention_mask is None:
        decoder_attention_mask = jnp.ones((batch_size, sequence_length))
    if decoder_position_ids is None:
        if past_key_values is not None:
            raise ValueError('Make sure to provide `decoder_position_ids` when passing `past_key_values`.')
        decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
    rngs = {}
    if dropout_rng is not None:
        rngs['dropout'] = dropout_rng
    inputs = {'params': params or self.params}
    if past_key_values:
        inputs['cache'] = past_key_values
        mutable = ['cache']
    else:
        mutable = False

    def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
        decoder_module = module._get_decoder_module()
        return decoder_module(decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs)
    outputs = self.module.apply(inputs, decoder_input_ids=jnp.array(decoder_input_ids, dtype='i4'), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype='i4'), decoder_position_ids=jnp.array(decoder_position_ids, dtype='i4'), encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=jnp.array(encoder_attention_mask, dtype='i4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, mutable=mutable, method=_decoder_forward)
    if past_key_values is not None and return_dict:
        outputs, past = outputs
        outputs['past_key_values'] = unfreeze(past['cache'])
        return outputs
    elif past_key_values is not None and (not return_dict):
        outputs, past = outputs
        outputs = outputs[:1] + (unfreeze(past['cache']),) + outputs[1:]
    return outputs

Returns:

Example:

```python
>>> import jax.numpy as jnp
>>> from transformers import AutoTokenizer, FlaxBlenderbotForConditionalGeneration

>>> model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-400M-distill")
>>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot-400M-distill")

>>> text = "My friends are cool but they eat too many carbs."
>>> inputs = tokenizer(text, max_length=1024, return_tensors="jax")
>>> encoder_outputs = model.encode(**inputs)

>>> decoder_start_token_id = model.config.decoder_start_token_id
>>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id

>>> outputs = model.decode(decoder_input_ids, encoder_outputs)
>>> last_decoder_hidden_states = outputs.last_hidden_state
```


def _get_tags(self):
    tags = self.data.get('tags', None)
    if (not tags):
        return list()
    return [x['name'] for x in tags]

Return the dataset's list of tags

Returns:
List[str]: list of tags or [] if there are none


def obj_with_unit(obj, unit):

    unit_type = _UNAME2UTYPE[unit]

    if isinstance(obj, numbers.Number):
        return FloatWithUnit(obj, unit=unit, unit_type=unit_type)
    elif isinstance(obj, collections.Mapping):
        return {k: obj_with_unit(v, unit) for k,v in obj.items()}
    else:
        return ArrayWithUnit(obj, unit=unit, unit_type=unit_type)

Returns a `FloatWithUnit` instance if obj is scalar, a dictionary of
objects with units if obj is a dict, else an instance of
`ArrayWithFloatWithUnit`.

Args:
unit: Specific units (eV, Ha, m, ang, etc.).


def power(self, n):

        if n > 0:
            return super().power(n)
        return Kraus(SuperOp(self).power(n))

The matrix power of the channel.

Args:
n (int): compute the matrix power of the superoperator matrix.

Returns:
Kraus: the matrix power of the SuperOp converted to a Kraus channel.

Raises:
QiskitError: if the input and output dimensions of the
QuantumChannel are not equal, or the power is not an integer.


def _compare(self, other: Any, comparison: Callable[[Any, Any], bool]) -> bool:
    if isinstance(other, str):
        return comparison(self.path, other)
    if isinstance(other, KeyPath):
        return comparison(tuple(map(KeyPath._KeyComparisonWrapper, self.keys)), tuple(map(KeyPath._KeyComparisonWrapper, other.keys)))
    raise TypeError(f"Comparison is not supported between instances of 'KeyPath' and {type(other).__name__!r}.")

Compare to another KeyPath or a string.

Args:
other: A Keypath or a string.
comparison: A comparison operator.

Returns:
Whether or not the comparison holds true.

Raises:
TypeError: The other object is neither a Keypath nor a string.


def WriteFileHash(self, path, hash_value):

    string = '{0:s}\t{1:s}'.format(hash_value, path)

    encoded_string = self._EncodeString(string)
    print(encoded_string)

Writes the file path and hash to stdout.

Args:
path (str): path of the file.
hash_value (str): message digest hash calculated over the file data.


def get_current_user(with_domain=True):

    try:
        user_name = win32api.GetUserNameEx(win32api.NameSamCompatible)
        if user_name[-1] == '$':

            test_user = win32api.GetUserName()
            if test_user == 'SYSTEM':
                user_name = 'SYSTEM'
            elif get_sid_from_name(test_user) == 'S-1-5-18':
                user_name = 'SYSTEM'
        elif not with_domain:
            user_name = win32api.GetUserName()
    except pywintypes.error as exc:
        raise CommandExecutionError(
            'Failed to get current user: {0}'.format(exc))

    if not user_name:
        return False

    return user_name

Gets the user executing the process

Args:

with_domain (bool):
``True`` will prepend the user name with the machine name or domain
separated by a backslash

Returns:
str: The user name


def filter_collections_by_statement(data_collections, statement):
    pattern = BaseCollection.pattern_from_collections_and_statement(data_collections, statement)
    collections = [coll.filter_by_pattern(pattern) for coll in data_collections]
    return collections

Generate a filtered data collections according to a conditional statement.

Args:
data_collections: A list of aligned Data Collections to be evaluated
against the statement.
statement: A conditional statement as a string (e.g. a>25 and a%5==0).
The variable should always be named as 'a' (without quotations).

Return:
collections: A list of Data Collections that have been filtered based
on the statement.


def walknset_vars(self, task_class=None, *args, **kwargs):

    def change_task(task):
        if ((task_class is not None) and (task.__class__ is not task_class)):
            return False
        return True
    if self.is_work:
        for task in self:
            if (not change_task(task)):
                continue
            task.set_vars(*args, **kwargs)
    elif self.is_flow:
        for task in self.iflat_tasks():
            if (not change_task(task)):
                continue
            task.set_vars(*args, **kwargs)
    else:
        raise TypeError(("Don't know how to set variables for object class %s" % self.__class__.__name__))

Set the values of the ABINIT variables in the input files of the nodes

Args:
task_class: If not None, only the input files of the tasks belonging
to class `task_class` are modified.

Example:

flow.walknset_vars(ecut=10, kptopt=4)


def format_rpc(data):
    (address, rpc_id, args, resp, _status) = data
    name = rpc_name(rpc_id)
    if isinstance(args, (bytes, bytearray)):
        arg_str = hexlify(args)
    else:
        arg_str = repr(args)
    if isinstance(resp, (bytes, bytearray)):
        resp_str = hexlify(resp)
    else:
        resp_str = repr(resp)
    return ('%s called on address %d, payload=%s, response=%s' % (name, address, arg_str, resp_str))

Format an RPC call and response.

Args:
data (tuple): A tuple containing the address, rpc_id, argument and
response payloads and any error code.

Returns:
str: The formated RPC string.


def random_dna(dna_spec: DNASpec, random_generator: Union[None, types.ModuleType, random.Random]=None, attach_spec: bool=True, previous_dna: Optional[DNA]=None) -> DNA:
    return dna_spec.random_dna(random_generator or random, attach_spec, previous_dna)

Generates a random DNA from a DNASpec.

Example::

spec = pg.geno.space([
pg.geno.oneof([
pg.geno.constant(),
pg.geno.constant(),
pg.geno.constant()
]),
pg.geno.floatv(0.1, 0.2)
])

print(pg.random_dna(spec))
# DNA([2, 0.1123])

Args:
dna_spec: a DNASpec object.
random_generator: a Python random generator.
attach_spec: If True, attach the DNASpec to generated DNA.
previous_dna: An optional DNA representing previous DNA. This field might
be useful for generating stateful random DNAs.

Returns:
A DNA object.


def dummy_signatures(self):
    if (not self.signing_algorithm):
        return []
    algo_id = {'sha1': 1, 'sha384': 2}[self.signing_algorithm]
    signature = make_dummy_signature(algo_id)
    return [(algo_id, signature)]

Create a dummy signature.

This is used when initially writing the MAR header and we don't know
what the final signature data will be.

Returns:
Fake signature data suitable for writing to the header with
.write_signatures()


def get_image_data(self, ids=None, voxels=None, dense=True):

        return self.image_table.get_image_data(ids, voxels=voxels, dense=dense)

A convenience wrapper for ImageTable.get_image_data().

Args:
ids (list, array): A list or 1D numpy array of study ids to
return. If None, returns data for all studies.
voxels (list, array): A list or 1D numpy array of voxel indices
(i.e., rows) to return. If None, returns data for all voxels.


def ReplaceAll(pattern, rep, s):

  if pattern not in _regexp_compile_cache:
    _regexp_compile_cache[pattern] = sre_compile.compile(pattern)
  return _regexp_compile_cache[pattern].sub(rep, s)

Replaces instances of pattern in a string with a replacement.

The compiled regex is kept in a cache shared by Match and Search.

Args:
pattern: regex pattern
rep: replacement text
s: search string

Returns:
string with replacements made (or original string if no replacements)


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, return_dict: 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
    return_dict = return_dict if return_dict is not None else self.config.use_return_dict
    text_outputs = 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, return_dict=return_dict)
    pooled_output = text_outputs[1]
    text_features = self.text_projection(pooled_output)
    return text_features

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 [`GroupViTTextModel`].

Examples:

```python
>>> from transformers import CLIPTokenizer, GroupViTModel

>>> model = GroupViTModel.from_pretrained("nvidia/groupvit-gcc-yfcc")
>>> tokenizer = CLIPTokenizer.from_pretrained("nvidia/groupvit-gcc-yfcc")

>>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
>>> text_features = model.get_text_features(**inputs)
```


def crypto_withdraw(self, amount, currency, crypto_address):

        params = {'amount': amount,
                  'currency': currency,
                  'crypto_address': crypto_address}
        return self._send_message('post', '/withdrawals/crypto',
                                  data=json.dumps(params))

Withdraw funds to a crypto address.

Args:
amount (Decimal): The amount to withdraw
currency (str): The type of currency (eg. 'BTC')
crypto_address (str): Crypto address to withdraw to.

Returns:
dict: Withdraw details. Example::
{
"id":"593533d2-ff31-46e0-b22e-ca754147a96a",
"amount":"10.00",
"currency": "BTC",
}


def __init__(self, fetches):
    self._fetch_type = type(fetches)
    if isinstance(fetches, collections.defaultdict):
        self._type_ctor = functools.partial(collections.defaultdict, fetches.default_factory)
    else:
        self._type_ctor = self._fetch_type
    self._keys = fetches.keys()
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches.values()]
    self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)

Creates a _DictFetchMapper.

Args:
fetches: Dict of fetches.


def get_estimated_size_and_observables(self, value, nested=False):
    return (self.estimate_size(value, nested), [])

Returns estimated size of value along with any nested observables.

The list of nested observables is returned as a list of 2-tuples of
(obj, coder_impl), where obj is an instance of observable.ObservableMixin,
and coder_impl is the CoderImpl that can be used to encode elements sent by
obj to its observers.

Arguments:
value: the value whose encoded size is to be estimated.
nested: whether the value is nested.

Returns:
The estimated encoded size of the given value and a list of observables
whose elements are 2-tuples of (obj, coder_impl) as described above.


def _handle_skip_feature(self, test_dict):

        skip_reason = None

        if "skip" in test_dict:
            skip_reason = test_dict["skip"]

        elif "skipIf" in test_dict:
            skip_if_condition = test_dict["skipIf"]
            if self.session_context.eval_content(skip_if_condition):
                skip_reason = "{} evaluate to True".format(skip_if_condition)

        elif "skipUnless" in test_dict:
            skip_unless_condition = test_dict["skipUnless"]
            if not self.session_context.eval_content(skip_unless_condition):
                skip_reason = "{} evaluate to False".format(skip_unless_condition)

        if skip_reason:
            raise SkipTest(skip_reason)

handle skip feature for test
- skip: skip current test unconditionally
- skipIf: skip current test if condition is true
- skipUnless: skip current test unless condition is true

Args:
test_dict (dict): test info

Raises:
SkipTest: skip test


def __add__(self, other: Self | Processor) -> PartProcessor | Processor:
    if isinstance(other, _ChainPartProcessor):
        return _ChainPartProcessor([self] + other._processor_list)
    elif isinstance(other, _ChainProcessor):
        return _ChainProcessor([self.to_processor().call] + other._processor_list)
    elif isinstance(other, Processor):
        return _ChainProcessor([self.to_processor().call, other])
    else:
        return _ChainPartProcessor([self, other])

Adds `other` to this processor.

Args:
other: a processor to add to `self`.

Returns:
The chain of this process with `other`.


def _pearson_correlation(self, imgs_to_decode):

        x, y = imgs_to_decode.astype(float), self.feature_images.astype(float)
        return self._xy_corr(x, y)

Decode images using Pearson's r.

Computes the correlation between each input image and each feature
image across voxels.

Args:
imgs_to_decode: An ndarray of images to decode, with voxels in rows
and images in columns.

Returns:
An n_features x n_images 2D array, with each cell representing the
pearson correlation between the i'th feature and the j'th image
across all voxels.


def replace_in_file(filename: str, text_from: str, text_to: str) -> None:

    log.info("Amending {}: {} -> {}",
             filename, repr(text_from), repr(text_to))
    with open(filename) as infile:
        contents = infile.read()
    contents = contents.replace(text_from, text_to)
    with open(filename, 'w') as outfile:
        outfile.write(contents)

Replaces text in a file.

Args:
filename: filename to process (modifying it in place)
text_from: original text to replace
text_to: replacement text


def __init__(self, config: interfaces.Config | None=None):
    self._config = config or interfaces.Config()

Initializes the TopicVerbalizer.

Args:
config: The agent configuration.


def _lease_owned(self, lease, current_uuid_path):
    (prev_uuid_path, prev_uuid) = lease.metadata
    with open(current_uuid_path) as f:
        current_uuid = f.read()
    return ((current_uuid_path == prev_uuid_path) and (prev_uuid == current_uuid))

Checks if the given lease is owned by the prefix whose uuid is in
the given path

Note:
The prefix must be also in the same path it was when it took the
lease

Args:
path (str): Path to the lease
current_uuid_path (str): Path to the uuid to check ownership of

Returns:
bool: ``True`` if the given lease in owned by the prefix,
``False`` otherwise


def are_equal(self, sp1, sp2):

        comp1 = Composition(sp1)
        comp2 = Composition(sp2)
        return comp1.get_el_amt_dict() == comp2.get_el_amt_dict()

True if element:amounts are exactly the same, i.e.,
oxidation state is not considered.

Args:
sp1: First species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.
sp2: Second species. A dict of {specie/element: amt} as per the
definition in Site and PeriodicSite.

Returns:
Boolean indicating whether species are the same based on element
and amounts.


def reply(self, user, msg, errors_as_replies=True):
    return self._brain.reply(user, msg, errors_as_replies)

Fetch a reply from the RiveScript brain.

Arguments:
user (str): A unique user ID for the person requesting a reply.
This could be e.g. a screen name or nickname. It's used internally
to store user variables (including topic and history), so if your
bot has multiple users each one should have a unique ID.
msg (str): The user's message. This is allowed to contain
punctuation and such, but any extraneous data such as HTML tags
should be removed in advance.
errors_as_replies (bool): When errors are encountered (such as a
deep recursion error, no reply matched, etc.) this will make the
reply be a text representation of the error message. If you set
this to ``False``, errors will instead raise an exception, such as
a ``DeepRecursionError`` or ``NoReplyError``. By default, no
exceptions are raised and errors are set in the reply instead.

Returns:
str: The reply output.


async def execute_method(self, method, **params):
    url = self.url_builder(method, url_params=params)
    logger.info('Executing method %r', method)
    response = (await aiohttp.get(url))
    logger.info('Status: %r', response.status)
    if (response.status == 200):
        json = (await response.json())
        logger.debug('...with JSON %r', json)
        if json.get('ok'):
            return json
        raise SlackApiError(json['error'])
    else:
        raise_for_status(response)

Execute a specified Slack Web API method.

Arguments:
method (:py:class:`str`): The name of the method.
**params (:py:class:`dict`): Any additional parameters
required.

Returns:
:py:class:`dict`: The JSON data from the response.

Raises:
:py:class:`aiohttp.web_exceptions.HTTPException`: If the HTTP
request returns a code other than 200 (OK).
SlackApiError: If the Slack API is reached but the response
contains an error message.


def _scan(self, fs, dir_path, namespaces=None):
    try:
        for info in fs.scandir(dir_path, namespaces=namespaces):
            (yield info)
    except FSError as error:
        if (not self.on_error(dir_path, error)):
            six.reraise(type(error), error)

Get an iterator of `Info` objects for a directory path.

Arguments:
fs (FS): A filesystem instance.
dir_path (str): A path to a directory on the filesystem.
namespaces (list): A list of additional namespaces to
include in the `Info` objects.

Returns:
~collections.Iterator: iterator of `Info` objects for
resources within the given path.


def IsDerivedFunction(clean_lines, linenum):
    for i in xrange(linenum, max((- 1), (linenum - 10)), (- 1)):
        match = Match('^([^()]*\\w+)\\(', clean_lines.elided[i])
        if match:
            (line, _, closing_paren) = CloseExpression(clean_lines, i, len(match.group(1)))
            return ((closing_paren >= 0) and Search('\\boverride\\b', line[closing_paren:]))
    return False

Check if current line contains an inherited function.

Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier.


def oauth_aware(self, method):

    def setup_oauth(request_handler, *args, **kwargs):
        if self._in_error:
            self._display_error_message(request_handler)
            return
        user = users.get_current_user()
        if (not user):
            request_handler.redirect(users.create_login_url(request_handler.request.uri))
            return
        self._create_flow(request_handler)
        self.flow.params['state'] = _build_state_value(request_handler, user)
        self.credentials = self._storage_class(self._credentials_class, None, self._credentials_property_name, user=user).get()
        try:
            resp = method(request_handler, *args, **kwargs)
        finally:
            self.credentials = None
        return resp
    return setup_oauth

Decorator that sets up for OAuth 2.0 dance, but doesn't do it.

Does all the setup for the OAuth dance, but doesn't initiate it.
This decorator is useful if you want to create a page that knows
whether or not the user has granted access to this application.
From within a method decorated with @oauth_aware the has_credentials()
and authorize_url() methods can be called.

Args:
method: callable, to be decorated method of a webapp.RequestHandler
instance.


def matches(self, applied_ptransform):
    raise NotImplementedError

Determines whether the given AppliedPTransform matches.

Note that the matching will happen *after* Runner API proto translation.
If matching is done via type checks, to/from_runner_api[_parameter] methods
must be implemented to preserve the type (and other data) through proto
serialization.

Consider URN-based translation instead.

Args:
applied_ptransform: AppliedPTransform to be matched.

Returns:
a bool indicating whether the given AppliedPTransform is a match.


def enroll_users_in_program(cls, enterprise_customer, program_details, course_mode, emails, cohort=None):
    (existing_users, unregistered_emails) = cls.get_users_by_email(emails)
    course_ids = get_course_runs_from_program(program_details)
    successes = []
    pending = []
    failures = []
    for user in existing_users:
        succeeded = cls.enroll_user(enterprise_customer, user, course_mode, *course_ids)
        if succeeded:
            successes.append(user)
        else:
            failures.append(user)
    for email in unregistered_emails:
        pending_user = enterprise_customer.enroll_user_pending_registration(email, course_mode, *course_ids, cohort=cohort)
        pending.append(pending_user)
    return (successes, pending, failures)

Enroll existing users in all courses in a program, and create pending enrollments for nonexisting users.

Args:
enterprise_customer: The EnterpriseCustomer which is sponsoring the enrollment
program_details: The details of the program in which we're enrolling
course_mode (str): The mode with which we're enrolling in the program
emails: An iterable of email addresses which need to be enrolled

Returns:
successes: A list of users who were successfully enrolled in all courses of the program
pending: A list of PendingEnterpriseCustomerUsers who were successfully linked and had
pending enrollments created for them in the database
failures: A list of users who could not be enrolled in the program


def import_image(self, src=None, repository=None, tag=None, image=None, changes=None, stream_src=False):
    if (not (src or image)):
        raise errors.DockerException('Must specify src or image to import from')
    u = self._url('/images/create')
    params = _import_image_params(repository, tag, image, src=(src if isinstance(src, six.string_types) else None), changes=changes)
    headers = {'Content-Type': 'application/tar'}
    if (image or (params.get('fromSrc') != '-')):
        return self._result(self._post(u, data=None, params=params))
    elif isinstance(src, six.string_types):
        with open(src, 'rb') as f:
            return self._result(self._post(u, data=f, params=params, headers=headers, timeout=None))
    else:
        if stream_src:
            headers['Transfer-Encoding'] = 'chunked'
        return self._result(self._post(u, data=src, params=params, headers=headers))

Import an image. Similar to the ``docker import`` command.

If ``src`` is a string or unicode string, it will first be treated as a
path to a tarball on the local system. If there is an error reading
from that file, ``src`` will be treated as a URL instead to fetch the
image from. You can also pass an open file handle as ``src``, in which
case the data will be read from that file.

If ``src`` is unset but ``image`` is set, the ``image`` parameter will
be taken as the name of an existing image to import from.

Args:
src (str or file): Path to tarfile, URL, or file-like object
repository (str): The repository to create
tag (str): The tag to apply
image (str): Use another image like the ``FROM`` Dockerfile
parameter