def load_pickled_model(filename, dirname=None):
    if (dirname is None):
        pkg_filename = pkgutil.get_loader('dragnet').get_filename('dragnet')
        pkg_dirname = os.path.dirname(pkg_filename)
        dirname = os.path.join(pkg_dirname, 'pickled_models', model_path)
    filepath = os.path.join(dirname, filename)
    return joblib.load(filepath)

Load a pickled ``Extractor`` model from disk.

Args:
filename (str): Name of pickled model file under ``dirname``.
dirname (str): Name of directory on disk containing the pickled model.
If None, dragnet's default pickled model directory is used:
/path/to/dragnet/pickled_models/[PY_VERSION]_[SKLEARN_VERSION]

Returns:
:class:`dragnet.extractor.Extractor`


def get_percentage(a, b, i=False, r=False):
    if ((i is False) and (r is True)):
        percentage = round((100.0 * (float(a) / b)), 2)
    elif (((i is True) and (r is True)) or ((i is True) and (r is False))):
        percentage = int(round((100 * (float(a) / b))))
        if (r is False):
            warnings.warn('If integer is set to True and Round is set to False, you will still get a rounded number if you pass floating point numbers as arguments.')
    else:
        percentage = (100.0 * (float(a) / b))
    return percentage

Finds the percentage of one number over another.

Args:
a: The number that is a percent, int or float.

b: The base number that a is a percent of, int or float.

i: Optional boolean integer. True if the user wants the result returned as
a whole number. Assumes False.

r: Optional boolean round. True if the user wants the result rounded.
Rounds to the second decimal point on floating point numbers. Assumes False.

Returns:
The argument a as a percentage of b. Throws a warning if integer is set to True
and round is set to False.


def _indicator(self, indicator_data):
    if isinstance(indicator_data, dict):
        xid = indicator_data.get('xid')
    else:
        xid = indicator_data.xid
    if (self.indicators.get(xid) is not None):
        indicator_data = self.indicators.get(xid)
    elif (self.indicators_shelf.get(xid) is not None):
        indicator_data = self.indicators_shelf.get(xid)
    else:
        self.indicators[xid] = indicator_data
    return indicator_data

Return previously stored indicator or new indicator.

Args:
indicator_data (dict|obj): An Indicator dict or instance of Indicator object.

Returns:
dict|obj: The new Indicator dict/object or the previously stored dict/object.


def crowding_distance_sort(frontier: List[pg.DNA]) -> List[pg.DNA]:
    if len(frontier) <= 1:
        return frontier
    individual_num = len(frontier)
    objective_num = len(base.get_fitness(frontier[0]))
    distances = [0.0] * individual_num
    dist = [list(range(individual_num)) for i in range(objective_num)]
    for i in range(objective_num):
        dist[i] = sorted(dist[i], key=lambda idx: base.get_fitness(frontier[idx])[i])
        max_value = base.get_fitness(frontier[dist[i][individual_num - 1]])[i]
        min_value = base.get_fitness(frontier[dist[i][0]])[i]
        for j in range(individual_num):
            if j == 0 or j == individual_num - 1:
                distances[dist[i][j]] = objective_num
            elif max_value > min_value:
                distances[dist[i][j]] += (base.get_fitness(frontier[dist[i][j + 1]])[i] - base.get_fitness(frontier[dist[i][j - 1]])[i]) / (max_value - min_value)
    idx_arr = list(range(individual_num))
    idx_arr = sorted(idx_arr, key=lambda idx: distances[idx], reverse=True)
    return [frontier[idx_arr[i]] for i in range(individual_num)]

Algorithm crowding-distance-assignment implementation.

Check section III B in the original paper.

Args:
frontier: A list of Individual that need to be sorted.

Returns:
sorted list of the original list.


def set_icon_file(self, filename, rel="icon"):

        mimetype, encoding = mimetypes.guess_type(filename)
        self.add_child("favicon", '<link rel="%s" href="%s" type="%s" />'%(rel, filename, mimetype))

Allows to define an icon for the App

Args:
filename (str): the resource file name (ie. "/res:myicon.png")
rel (str): leave it unchanged (standard "icon")


def add_cmd_handler(self, handler_obj):
    for field in dir(handler_obj):
        if field.startswith('cmd_'):
            cmd = field[4:]
            fn = getattr(handler_obj, field)
            if (cmd in self.cmds):
                print('Replacing {} with {}'.format(_handler_name(self.cmds[cmd]), _handler_name(fn)), file=sys.stderr)
            self.cmds[cmd] = fn

Registers a new command handler object.

All methods on `handler_obj` whose name starts with "cmd_" are
registered as a GTP command. For example, the method cmd_genmove will
be invoked when the engine receives a genmove command.

Args:
handler_obj: the handler object to register.


def __getitem__(self, key):

        if isinstance(key, str):
            if key not in self.columns:
                raise AttributeError('Key not in columns.')
            return [row[key] if key in row else None for row in self.rows]

        elif isinstance(key, (int, slice)):
            return self.rows[key]
        else:
            raise TypeError('Invalid argument type.')

Get a column or row from the dataset.

Args:
key (str or int): String referencing a column or integer referencing a row
Returns:
:class:`list` or :class:`dict`: List of column values or a dict representing a row


def loader(self, file_name, bad_steps=None, **kwargs):

        new_tests = []
        if not os.path.isfile(file_name):
            self.logger.info("Missing file_\n   %s" % file_name)
            return None

        filesize = os.path.getsize(file_name)
        hfilesize = humanize_bytes(filesize)
        txt = "Filesize: %i (%s)" % (filesize, hfilesize)
        self.logger.debug(txt)

        temp_dir = tempfile.gettempdir()
        temp_filename = os.path.join(temp_dir, os.path.basename(file_name))
        shutil.copy2(file_name, temp_dir)

        self.logger.debug("tmp file: %s" % temp_filename)
        self.logger.debug("HERE WE LOAD THE DATA")

        data = DataSet()
        fid = FileID(file_name)

        test_no = 1
        data.test_no = test_no
        data.loaded_from = file_name

        data.channel_index = None
        data.channel_number = None
        data.creator = None
        data.item_ID = None
        data.schedule_file_name = None
        data.start_datetime = None
        data.test_ID = None
        data.test_name = None
        data.raw_data_files.append(fid)

        self.logger.debug("reading raw-data")
        self.mpr_data = None
        self.mpr_log = None
        self.mpr_settings = None

        self._load_mpr_data(temp_filename, bad_steps)
        length_of_test = self.mpr_data.shape[0]
        self.logger.debug(f"length of test: {length_of_test}")

        self.logger.debug("renaming columns")
        self._rename_headers()

        summary_df = self._create_summary_data()

        if summary_df.empty:
            txt = "\nCould not find any summary (stats-file)!"
            txt += " (summary_df.empty = True)"
            txt += "\n -> issue make_summary(use_cellpy_stat_file=False)"
            warnings.warn(txt)

        data.dfsummary = summary_df
        data.dfdata = self.mpr_data

        data.raw_data_files_length.append(length_of_test)
        new_tests.append(data)

        self._clean_up(temp_filename)
        return new_tests

Loads data from biologics .mpr files.

Args:
file_name (str): path to .res file.
bad_steps (list of tuples): (c, s) tuples of steps s
(in cycle c) to skip loading.

Returns:
new_tests (list of data objects)


def apply_activation(
    books,
    x,
    activation,
    activation_args=(),
    activation_kwargs=None):

  if activation is None:
    return x
  if activation_kwargs is None:
    activation_kwargs = {}
  y = activation(x, *activation_args, **activation_kwargs)
  if activation in (tf.nn.relu, functions.leaky_relu, functions.softplus):
    books.add_scalar_summary(
        tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)),
        '%s/zeros' % y.op.name)
  elif activation is tf.nn.relu6:
    books.add_scalar_summary(
        tf.reduce_mean(tf.cast(tf.less(x, 0.0), tf.float32)),
        '%s/zeros' % y.op.name)
    books.add_scalar_summary(
        tf.reduce_mean(tf.cast(tf.greater(x, 6.0), tf.float32)),
        '%s/sixes' % y.op.name)
  elif activation in (functions.l2_normalize, tf.nn.l2_normalize,
                      functions.l1_normalize):
    books.add_scalar_summary(
        tf.reduce_mean(tf.sqrt(tf.reduce_sum(
            tf.square(x), 1))), '%s/length' % y.op.name)
  return y

Returns activation(x, *activation_args, **activation_kwargs).

This applies the given activation and adds useful summaries specific to the
activation.

Args:
books: The bookkeeper.
x: The tensor to apply activation to.
activation: An activation function.
activation_args: Optional additional arguments for the activation.
activation_kwargs: Optional keyword args for activation.
Returns:
A tensor with activation applied to x.


def get_bool(self):
    return self.fdp.ConsumeBool()

Consume a bool.

Returns:
Consumed a bool based on input bytes and constraints.


def set_metadata(self, token, data):

        req = requests.post(self.meta_url("metadata/ocp/set/" + token),
                            json=data, verify=False)

        if req.status_code != 200:
            raise RemoteDataUploadError(
                "Could not upload metadata: " + req.json()['message']
            )
        return req.json()

Insert new metadata into the OCP metadata database.

Arguments:
token (str): Token of the datum to set
data (str): A dictionary to insert as metadata. Include `secret`.

Returns:
json: Info of the inserted ID (convenience) or an error message.

Throws:
RemoteDataUploadError: If the token is already populated, or if
there is an issue with your specified `secret` key.


def get_multi_dataset(datasets, pmf=None):
    pmf = (tf.fill([len(datasets)], (1.0 / len(datasets))) if (pmf is None) else pmf)
    samplers = [d.repeat().make_one_shot_iterator().get_next for d in datasets]
    sample = (lambda _: categorical_case(pmf, samplers))
    return tf.data.Dataset.from_tensors([]).repeat().map(sample)

Returns a Dataset that samples records from one or more Datasets.

Args:
datasets: A list of one or more Dataset objects to sample from.
pmf: A tensor of shape [len(datasets)], the probabilities to sample each
dataset with. This tensor is often constructed with the global_step. If
this is None, we sample from the datasets uniformly at random.

Returns:
A Dataset object containing records from multiple datasets. Note that
because this dataset iterates through other datasets it is stateful, thus
you will need to call make_initializable_iterator instead of
make_one_shot_iterator.


def GetAutomountMap(self, since=None, location=None):
    if location is None:
        self.log.error('A location is required to retrieve an automount map!')
        raise error.EmptyMap
    autofs_filter = '(objectclass=automount)'
    return AutomountUpdateGetter(self.conf).GetUpdates(source=self, search_base=location, search_filter=autofs_filter, search_scope='one', since=since)

Return an automount map from this source.

Note that autmount maps are stored in multiple locations, thus we expect
a caller to provide a location.  We also follow the automount spec and
set our search scope to be 'one'.

Args:
since: Get data only changed since this timestamp (inclusive) or None
for all data.
location: Currently a string containing our search base, later we
may support hostname and additional parameters.

Returns:
instance of AutomountMap


def uniform_distribution(number_of_nodes):

    number_of_states = 2 ** number_of_nodes

    return (np.ones(number_of_states) /
            number_of_states).reshape([2] * number_of_nodes)

Return the uniform distribution for a set of binary nodes, indexed by state
(so there is one dimension per node, the size of which is the number of
possible states for that node).

Args:
nodes (np.ndarray): A set of indices of binary nodes.

Returns:
np.ndarray: The uniform distribution over the set of nodes.


def _ensure_list(tensor_or_list):
    if isinstance(tensor_or_list, (list, tuple)):
        return (list(tensor_or_list), True)
    return ([tensor_or_list], False)

Converts the input arg to a list if it is not a list already.

Args:
tensor_or_list: A `Tensor` or a Python list of `Tensor`s. The argument to
convert to a list of `Tensor`s.

Returns:
A tuple of two elements. The first is a Python list of `Tensor`s containing
the original arguments. The second is a boolean indicating whether
the original argument was a list or tuple already.


def temp_dir(folder=None, delete=True):

    tempdir = get_temp_dir()
    if folder:
        tempdir = join(tempdir, folder)
    if not exists(tempdir):
        makedirs(tempdir)
    try:
        yield tempdir
    finally:
        if delete:
            rmtree(tempdir)

Get a temporary directory optionally with folder appended (and created if it doesn't exist)

Args:
folder (Optional[str]): Folder to create in temporary folder. Defaults to None.
delete (bool): Whether to delete folder on exiting with statement

Returns:
str: A temporary directory


def _apply_shadow_vars(avg_grads):

        ps_var_grads = []
        for grad, var in avg_grads:
            assert var.name.startswith('tower'), var.name
            my_name = '/'.join(var.name.split('/')[1:])
            my_name = get_op_tensor_name(my_name)[0]
            new_v = tf.get_variable(my_name, dtype=var.dtype.base_dtype,
                                    initializer=var.initial_value,
                                    trainable=True)

            ps_var_grads.append((grad, new_v))
        return ps_var_grads

Create shadow variables on PS, and replace variables in avg_grads
by these shadow variables.

Args:
avg_grads: list of (grad, var) tuples


def from_xmrs(cls, xmrs, **kwargs):

        x = cls()
        x.__dict__.update(xmrs.__dict__)
        return x

Facilitate conversion among subclasses.

Args:
xmrs (:class:`Xmrs`): instance to convert from; possibly
an instance of a subclass, such as :class:`Mrs` or
:class:`Dmrs`
**kwargs: additional keyword arguments that may be used
by a subclass's redefinition of :meth:`from_xmrs`.


def add_item(name, command, system_wide=False):
    desktop_env = system.get_name()
    if os.path.isfile(command):
        command_is_file = True
        if (not (desktop_env == 'windows')):
            sp.Popen([('chmod +x %s' % command)], shell=True)
    if (desktop_env == 'windows'):
        import winreg
        if system_wide:
            startup_dir = os.path.join(winreg.ExpandEnvironmentStrings('%PROGRAMDATA%'), 'Microsoft\\Windows\\Start Menu\\Programs\\Startup')
        else:
            startup_dir = os.path.join(get_config_dir()[0], 'Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup')
        if (not command_is_file):
            with open(os.path.join(startup_dir, (name + '.bat')), 'w') as f:
                f.write(command)
        else:
            shutil.copy(command, startup_dir)
    elif (desktop_env == 'mac'):
        sp.Popen((['launchctl submit -l %s -- %s'] % (name, command)), shell=True)
    elif (desktop_env == 'unknown'):
        if system_wide:
            login_file = '/etc/profile'
        else:
            login_file = os.path.expanduser('~/.profile')
        with open(login_file, 'a') as f:
            f.write(command)
    else:
        try:
            desktop_file_name = (name + '.desktop')
            startup_file = os.path.join(get_config_dir('autostart', system_wide=system_wide)[0], desktop_file_name)
            desktop_str = desktopfile.construct(name=name, exec_=command, additional_opts={'X-GNOME-Autostart-enabled': 'true'})
            with open(startup_file, 'w') as f:
                f.write(desktop_str)
        except:
            pass

Adds a program to startup.

Adds a program to user startup.

Args:
name        (str) : The name of the startup entry.
command     (str) : The command to run.
system_wide (bool): Add to system-wide startup.

Note:
``system_wide`` requires superuser/admin privileges.


def reduce(self, initial_state, reduce_func, name=None):
    with ops.name_scope('initial_state'):
        initial_state = structure.normalize_element(initial_state)
    state_structure = structure.type_spec_from_value(initial_state)
    need_to_rerun = True
    while need_to_rerun:
        wrapped_func = structured_function.StructuredFunctionWrapper(reduce_func, 'reduce()', input_structure=(state_structure, self.element_spec), add_to_graph=False)
        output_classes = wrapped_func.output_classes
        state_classes = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_classes(), state_structure)
        for new_state_class, state_class in zip(nest.flatten(output_classes), nest.flatten(state_classes)):
            if not issubclass(new_state_class, state_class):
                raise TypeError(f'The element classes for the new state must match the initial state. Expected {state_classes} but got {wrapped_func.output_classes}.')
        output_types = wrapped_func.output_types
        state_types = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_types(), state_structure)
        for new_state_type, state_type in zip(nest.flatten(output_types), nest.flatten(state_types)):
            if new_state_type != state_type:
                raise TypeError(f'The element types for the new state must match the initial state. Expected {state_types} but got {wrapped_func.output_types}.')
        output_shapes = wrapped_func.output_shapes
        state_shapes = nest.map_structure(lambda component_spec: component_spec._to_legacy_output_shapes(), state_structure)
        flat_state_shapes = nest.flatten(state_shapes)
        flat_new_state_shapes = nest.flatten(output_shapes)
        weakened_state_shapes = [original.most_specific_compatible_shape(new) for original, new in zip(flat_state_shapes, flat_new_state_shapes)]
        need_to_rerun = False
        for original_shape, weakened_shape in zip(flat_state_shapes, weakened_state_shapes):
            if original_shape.ndims is not None and (weakened_shape.ndims is None or original_shape.as_list() != weakened_shape.as_list()):
                need_to_rerun = True
                break
        if need_to_rerun:
            state_structure = structure.convert_legacy_structure(state_types, nest.pack_sequence_as(state_shapes, weakened_state_shapes), state_classes)
    reduce_func = wrapped_func.function
    reduce_func.add_to_graph(ops.get_default_graph())
    dataset = self._apply_debug_options()
    metadata = dataset_metadata_pb2.Metadata()
    if name:
        metadata.name = _validate_and_encode(name)
    return structure.from_compatible_tensor_list(state_structure, gen_dataset_ops.reduce_dataset(dataset._variant_tensor, structure.to_tensor_list(state_structure, initial_state), reduce_func.captured_inputs, f=reduce_func, output_shapes=structure.get_flat_tensor_shapes(state_structure), output_types=structure.get_flat_tensor_types(state_structure), metadata=metadata.SerializeToString()))

Reduces the input dataset to a single element.

The transformation calls `reduce_func` successively on every element of
the input dataset until the dataset is exhausted, aggregating information in
its internal state. The `initial_state` argument is used for the initial
state and the final state is returned as the result.

>>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, _: x +
...   1).numpy().item()
5
>>> tf.data.Dataset.range(5).reduce(np.int64(0), lambda x, y: x +
...   y).numpy().item()
10

Args:
initial_state: An element representing the initial state of the
transformation.
reduce_func: A function that maps `(old_state, input_element)` to
`new_state`. It must take two arguments and return a new element The
structure of `new_state` must match the structure of `initial_state`.
name: (Optional.) A name for the tf.data operation.

Returns:
A dataset element corresponding to the final state of the transformation.


def update_query_params(uri, params):
    parts = urllib.parse.urlparse(uri)
    query_params = parse_unique_urlencoded(parts.query)
    query_params.update(params)
    new_query = urllib.parse.urlencode(query_params)
    new_parts = parts._replace(query=new_query)
    return urllib.parse.urlunparse(new_parts)

Updates a URI with new query parameters.

If a given key from ``params`` is repeated in the ``uri``, then
the URI will be considered invalid and an error will occur.

If the URI is valid, then each value from ``params`` will
replace the corresponding value in the query parameters (if
it exists).

Args:
uri: string, A valid URI, with potential existing query parameters.
params: dict, A dictionary of query parameters.

Returns:
The same URI but with the new query parameters added.


def return_dict(self):
    output_dict = {}
    output_dict['general'] = self._iterate_through_class(self.general.__dict__)
    output_dict['figure'] = self._iterate_through_class(self.figure.__dict__)
    if (self.total_plots > 1):
        trans_dict = {str(i): self._iterate_through_class(axis.__dict__) for (i, axis) in enumerate(self.ax)}
        output_dict['plot_info'] = trans_dict
    else:
        output_dict['plot_info'] = {'0': self._iterate_through_class(self.ax.__dict__)}
    if self.print_input:
        print(output_dict)
    return output_dict

Output dictionary for ``make_plot.py`` input.

Iterates through the entire MainContainer class turning its contents
into dictionary form. This dictionary becomes the input for ``make_plot.py``.

If `print_input` attribute is True, the entire dictionary will be printed
prior to returning the dicitonary.

Returns:
- **output_dict** (*dict*): Dicitonary for input into ``make_plot.py``.


def GetKeyByScriptHash(self, script_hash):

        contract = self.GetContract(script_hash)
        if contract:
            return self.GetKey(contract.PublicKeyHash)
        return None

Get the KeyPair belonging to the script hash.

Args:
script_hash (UInt160): a bytearray (len 20) representing the public key.

Returns:
KeyPair: If successful, the KeyPair belonging to the public key hash, otherwise None


def get_user_roles(self, user):

        return self.service.get_user_roles(
            user, self.url_prefix, self.auth, self.session, self.session_send_opts)

Get roles associated with the given user.

Args:
user (string): User name.

Returns:
(list): List of roles that user has.

Raises:
requests.HTTPError on failure.


def report(self, name, **kwargs):
    group_obj = Report(name, **kwargs)
    return self._group(group_obj)

Add Report data to Batch object.

Args:
name (str): The name for this Group.
file_name (str): The name for the attached file for this Group.
date_added (str, kwargs): The date timestamp the Indicator was created.
file_content (str;method, kwargs): The file contents or callback method to retrieve
file content.
publish_date (str, kwargs): The publish datetime expression for this Group.
xid (str, kwargs): The external id for this Group.

Returns:
obj: An instance of Report.


def dbmin20years(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 `dbmin20years`'.format(value))

        self._dbmin20years = value

Corresponds to IDD Field `dbmin20years`
20-year return period values for minimum extreme dry-bulb temperature

Args:
value (float): value for IDD Field `dbmin20years`
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 __call__(self, request: beam.Row, *args, **kwargs):
    embedded_query = request['text']
    query = {'size': self.size, 'query': {'knn': {self.vector_field: {'vector': embedded_query, 'k': self.k}}}}
    results = self.client.search(body=query, index=self.index_name)
    logger.info('Enrichment_results', results)
    return (beam.Row(text=embedded_query), beam.Row(docs=results))

Reads a row from the opensearch Vector DB and returns
a `Tuple` of request and response.

Args:
request: the input `beam.Row` to enrich.


def _build_key_wrapping_specification(self, value):
    if (value is None):
        return None
    if (not isinstance(value, dict)):
        raise TypeError('Key wrapping specification must be a dictionary.')
    encryption_key_info = self._build_encryption_key_information(value.get('encryption_key_information'))
    mac_signature_key_info = self._build_mac_signature_key_information(value.get('mac_signature_key_information'))
    key_wrapping_specification = cobjects.KeyWrappingSpecification(wrapping_method=value.get('wrapping_method'), encryption_key_information=encryption_key_info, mac_signature_key_information=mac_signature_key_info, attribute_names=value.get('attribute_names'), encoding_option=value.get('encoding_option'))
    return key_wrapping_specification

Build a KeyWrappingSpecification struct from a dictionary.

Args:
value (dict): A dictionary containing the key/value pairs for a
KeyWrappingSpecification struct.

Returns:
KeyWrappingSpecification: a KeyWrappingSpecification struct

Raises:
TypeError: if the input argument is invalid


def memory_write8(self, addr, data, zone=None):
    return self.memory_write(addr, data, zone, 8)

Writes bytes to memory of a target system.

Args:
self (JLink): the ``JLink`` instance
addr (int): start address to write to
data (list): list of bytes to write
zone (str): optional memory zone to access

Returns:
Number of bytes written to target.

Raises:
JLinkException: on memory access error.


def _transform_col(self, x, i):

        return x.fillna(NAN_INT).map(self.label_encoders[i]).fillna(0)

Encode one categorical column into labels.

Args:
x (pandas.Series): a categorical column to encode
i (int): column index

Returns:
x (pandas.Series): a column with labels.


def remat(f):

    def wrapped(*args, **kwargs):
        return torch.utils.checkpoint.checkpoint(f, *args, use_reentrant=False)
    return wrapped

Implementation of rematerialization.

Args:
f: The function or operation to rematerialize.
Returns:
A function wrapping f that defines a custom gradient, which
recomputes f on the backwards pass of a gradient call.


def creationlog(base, package, stackdepth=_def_stackdepth):

    @staticmethod
    def wrapnew(cls, *argl, **argd):
        global _atdepth_new, _cstack_new, streamlining
        origstream = None
        if not (decorating or streamlining):
            entry, _atdepth_new = _pre_create(cls, _atdepth_new,
                                              stackdepth, *argl, **argd)
            _cstack_new.append(cls)

            fqdn = cls.__fqdn__
            if fqdn in _streamlines and _streamlines[fqdn]:

                msg.std("Streamlining {}.".format(fqdn), 2)
                origstream = streamlining
                streamlining = True

        try:
            if six.PY2:
                result = base.__old__(cls, *argl, **argd)
            else:

                if base.__old__ is object.__new__:
                    result = base.__old__(cls)
                else:
                    result = base.__old__(cls, *argl, **argd)

        except TypeError:

            import sys
            xcls, xerr = sys.exc_info()[0:2]
            referral = xerr.args[0].split()[-1]
            if ".__new__()" in referral:
                t = eval(referral.split('.')[0])
                result = t.__new__(cls, *argl, **argd)
            else:
                raise
                result = None

        if result is not None and hasattr(cls, "__init__"):
            try:
                cls.__init__(result, *argl, **argd)
            except:
                print(cls, argl, argd)
                raise
        else:
            msg.err("Object initialize failed for {}.".format(base.__name__))

        if origstream is not None:

            streamlining = origstream

        if not (decorating or streamlining):
            _cstack_new.pop()
            if len(_cstack_new) == 0:
                _atdepth_new = False
            _post_create(_atdepth_new, entry, result)

        return result
    return wrapnew

Decorator for wrapping the creation of class instances that are being logged
by acorn.

Args:
base: base class used to call __new__ for the construction.
package (str): name of (global) package the class belongs to.
stackdepth (int): if the calling stack is less than this depth, than
include the entry in the log; otherwise ignore it.


def input_shape(self):
    return nest.map_structure(backend.int_shape, self.input)

Retrieves the input shape(s) of a layer.

Only applicable if the layer has exactly one input,
i.e. if it is connected to one incoming layer, or if all inputs
have the same shape.

Returns:
Input shape, as an integer shape tuple
(or list of shape tuples, one tuple per input tensor).

Raises:
AttributeError: if the layer has no defined input_shape.
RuntimeError: if called in Eager mode.


def ExpandWindowsPath(cls, path, environment_variables):

    if environment_variables is None:
      environment_variables = []

    lookup_table = {}
    if environment_variables:
      for environment_variable in environment_variables:
        attribute_name = environment_variable.name.upper()
        attribute_value = environment_variable.value
        if not isinstance(attribute_value, py2to3.STRING_TYPES):
          continue

        lookup_table[attribute_name] = attribute_value

    path_segments = path.split('\\')

    for index, path_segment in enumerate(list(path_segments)):
      if (len(path_segment) <= 2 or not path_segment.startswith('%') or
          not path_segment.endswith('%')):
        continue

      path_segment_upper_case = path_segment.upper()
      if path_segment_upper_case.startswith('%%ENVIRON_'):
        lookup_key = path_segment_upper_case[10:-2]
      else:
        lookup_key = path_segment_upper_case[1:-1]
      path_segment = lookup_table.get(lookup_key, path_segment)
      path_segment = path_segment.split('\\')

      expanded_path_segments = list(path_segments[:index])
      expanded_path_segments.extend(path_segment)
      expanded_path_segments.extend(path_segments[index + 1:])

      path_segments = expanded_path_segments

    if cls._IsWindowsDrivePathSegment(path_segments[0]):
      path_segments[0] = ''

    return '\\'.join(path_segments)

Expands a Windows path containing environment variables.

Args:
path (str): Windows path with environment variables.
environment_variables (list[EnvironmentVariableArtifact]): environment
variables.

Returns:
str: expanded Windows path.


def formula_double_format(afloat, ignore_ones=True, tol=1e-08):
    if (ignore_ones and (afloat == 1)):
        return ''
    elif (abs((afloat - int(afloat))) < tol):
        return str(int(afloat))
    else:
        return str(round(afloat, 8))

This function is used to make pretty formulas by formatting the amounts.
Instead of Li1.0 Fe1.0 P1.0 O4.0, you get LiFePO4.

Args:
afloat (float): a float
ignore_ones (bool): if true, floats of 1 are ignored.
tol (float): Tolerance to round to nearest int. i.e. 2.0000000001 -> 2

Returns:
A string representation of the float for formulas.


def singleprint_from_fingerprint_proto(export_dir: str) -> str:
    try:
        return fingerprinting_pywrap.SingleprintFromFP(export_dir)
    except FingerprintException as e:
        raise ValueError(e) from None

Returns the singleprint of `fingerprint.pb` in `export_dir`.

Args:
export_dir: The directory that contains `fingerprint.pb`.

Returns:
A string containing the singleprint of `fingerprint.pb` in `export_dir`.

Raises:
ValueError: If a valid singleprint cannot be constructed from
`fingerprint.pb`.


def get_template_files(self, template_id, filename):
    url = (self.TEMPLATE_GET_FILES_URL + template_id)
    request = self._get_request()
    return request.get_file(url, filename)

Download a PDF copy of a template's original files

Args:

template_id (str):  The id of the template to retrieve.

filename (str):     Filename to save the PDF file to. This should be a full path.

Returns:
Returns a PDF file


def ref_for_message_type(self, message_type):

    name = self.__normalized_name(message_type)
    if name not in self.__schemas:
      raise KeyError('Message has not been parsed: %s', name)
    return name

Returns the JSON Schema id for the given message.

Args:
message_type: protorpc.message.Message class to be parsed.

Returns:
string, The JSON Schema id.

Raises:
KeyError: if the message hasn't been parsed via add_message().


def VerifyRow(self, parser_mediator, row):

    if row['md5'] != '0' and not self._MD5_RE.match(row['md5']):
      return False

    for column_name in (
        'uid', 'gid', 'size', 'atime', 'mtime', 'ctime', 'crtime'):
      column_value = row.get(column_name, None)
      if not column_value:
        continue

      try:
        int(column_value, 10)
      except (TypeError, ValueError):
        return False

    return True

Verifies if a line of the file is in the expected format.

Args:
parser_mediator (ParserMediator): mediates interactions between
parsers and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified in COLUMNS.

Returns:
bool: True if this is the correct parser, False otherwise.


def run(self, command, block=True, cwd=None, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE):

        if cwd is None:
            cwd = self.cwd

        return ShellCommand(command=command, logger=self.logger, block=block, cwd=cwd, stdin=stdin, stdout=stdout, stderr=stderr).run()

Create an instance of :class:`~ShellCommand` and run it

Args:
command (str): :class:`~ShellCommand`
block (bool): See :class:`~ShellCommand`
cwd (str): Override the runner cwd. Useb by the :class:`~ShellCommand` instance


def lt(self, other, axis="columns", level=None):

        return self._binary_op("lt", other, axis=axis, level=level)

Checks element-wise that this is less than other.

Args:
other: A DataFrame or Series or scalar to compare to.
axis: The axis to perform the lt over.
level: The Multilevel index level to apply lt over.

Returns:
A new DataFrame filled with Booleans.


def cysparse_real_type_from_real_cysparse_complex_type(cysparse_type):

    r_type = None

    if cysparse_type in ['COMPLEX64_t']:
        r_type = 'FLOAT32_t'
    elif cysparse_type in ['COMPLEX128_t']:
        r_type = 'FLOAT64_t'
    elif cysparse_type in ['COMPLEX256_t']:
        r_type = 'FLOAT128_t'
    else:
        raise TypeError("Not a recognized complex type")

    return r_type

Returns the **real** type for the real or imaginary part of a **real** complex type.

For instance:

COMPLEX128_t -> FLOAT64_t

Args:
cysparse:


def barycentric_coords(coords, simplex):

    coords = np.atleast_2d(coords)

    t = np.transpose(simplex[:-1, :]) - np.transpose(simplex[-1, :])[:, None]
    all_but_one = np.transpose(
        np.linalg.solve(t, np.transpose(coords - simplex[-1])))
    last_coord = 1 - np.sum(all_but_one, axis=-1)[:, None]
    return np.append(all_but_one, last_coord, axis=-1)

Converts a list of coordinates to barycentric coordinates, given a
simplex with d+1 points. Only works for d >= 2.

Args:
coords: list of n coords to transform, shape should be (n,d)
simplex: list of coordinates that form the simplex, shape should be
(d+1, d)

Returns:
a LIST of barycentric coordinates (even if the original input was 1d)


def last_modified(self) -> str:
    if ('last_modified' in self.attrs):
        return self.attrs['last_modified']
    elif (self.mode == 'r+'):
        self.attrs['last_modified'] = timestamp()
        return self.attrs['last_modified']
    return timestamp()

Return an ISO8601 timestamp indicating when the file was last modified

Returns:
An ISO8601 timestamp indicating when the file was last modified

Remarks:
If the file has no timestamp, and mode is 'r+', a new timestamp is created and returned.
Otherwise, the current time in UTC is returned


def with_resource_hints(self, **kwargs):
    self.get_resource_hints().update(resources.parse_resource_hints(kwargs))
    return self

Adds resource hints to the :class:`PTransform`.

Resource hints allow users to express constraints on the environment where
the transform should be executed.  Interpretation of the resource hints is
defined by Beam Runners. Runners may ignore the unsupported hints.

Args:
**kwargs: key-value pairs describing hints and their values.

Raises:
ValueError: if provided hints are unknown to the SDK. See
:mod:`apache_beam.transforms.resources` for a list of known hints.

Returns:
PTransform: A reference to the instance of this particular
:class:`PTransform` object.


def _worker(self, constructor, conn):

    try:
      env = constructor()
      while True:
        try:

          if not conn.poll(0.1):
            continue
          message, payload = conn.recv()
        except (EOFError, KeyboardInterrupt):
          break
        if message == self._ACCESS:
          name = payload
          result = getattr(env, name)
          conn.send((self._RESULT, result))
          continue
        if message == self._CALL:
          name, args, kwargs = payload
          result = getattr(env, name)(*args, **kwargs)
          conn.send((self._RESULT, result))
          continue
        if message == self._CLOSE:
          assert payload is None
          break
        raise KeyError('Received message of unknown type {}'.format(message))
    except Exception:
      stacktrace = ''.join(traceback.format_exception(*sys.exc_info()))
      tf.logging.error('Error in environment process: {}'.format(stacktrace))
      conn.send((self._EXCEPTION, stacktrace))
    conn.close()

The process waits for actions and sends back environment results.

Args:
constructor: Constructor for the OpenAI Gym environment.
conn: Connection for communication to the main process.

Raises:
KeyError: When receiving a message of unknown type.


def is_all_initialized(self):
    return (frozenset(self._class_map.keys()) == frozenset(self._instance_map.keys()))

Return whether all the instances have been initialized.

Returns:
bool


def verbose_ping(dest_addr: str, count: int=4, *args, **kwargs):
    timeout = kwargs.get('timeout')
    src = kwargs.get('src')
    unit = kwargs.setdefault('unit', 'ms')
    for i in range(count):
        output_text = "ping '{}'".format(dest_addr)
        output_text += (" from '{}'".format(src) if src else '')
        output_text += ' ... '
        print(output_text, end='')
        delay = ping(dest_addr, *args, seq=i, **kwargs)
        if (delay is None):
            print(('Timeout > {}s'.format(timeout) if timeout else 'Timeout'))
        else:
            print('{value}{unit}'.format(value=int(delay), unit=unit))

Send pings to destination address with the given timeout and display the result.

Args:
dest_addr: The destination address. Ex. "192.168.1.1"/"example.com"
count: How many pings should be sent. Default is 4, same as Windows CMD. (default 4)
*args and **kwargs: And all the other arguments available in ping() except `seq`.

Returns:
Formatted ping results printed.


def set_scope(self, include=None, exclude=None):
    if include:
        self.scope = u'document.querySelector("{}")'.format(u', '.join(include))
    else:
        self.scope = 'null'
    if (exclude is not None):
        raise NotImplementedError('The argument `exclude` has not been implemented in AxsAuditConfig.set_scope method.')

Sets `scope`, the "start point" for the audit.

Args:

include: A list of css selectors specifying the elements that
contain the portion of the page that should be audited.
Defaults to auditing the entire document.
exclude: This arg is not implemented in this ruleset.

Examples:

To check only the `div` with id `foo`::

page.a11y_audit.config.set_scope(["div#foo"])

To reset the scope to check the whole document::

page.a11y_audit.config.set_scope()


def update_resharding_callback(self, callback: checkpoint_adapter.ReshardCallback):
    if not issubclass(checkpoint_adapter.ReshardCallback, type(self.callback)):
        raise TypeError('Cannot override resharding callback, already set to non trivial.')
    self.callback = callback

Add a resharding callback to the checkpoint.

This will be applied to the checkpoint value before being supplied to the
restore ops.

Args:
callback: Reshard callback for resharding this checkpoint position. Maybe
None.


def ReadFromFile(self, path):

    self._definitions = {}

    with open(path, 'r') as file_object:
      for preset_definition in self._ReadPresetsFromFileObject(file_object):
        self._definitions[preset_definition.name] = preset_definition

Reads parser and parser plugin presets from a file.

Args:
path (str): path of file that contains the the parser and parser plugin
presets configuration.

Raises:
MalformedPresetError: if one or more plugin preset definitions are
malformed.


def PushTask(self, task):

    storage_file_size = getattr(task, 'storage_file_size', None)
    if not storage_file_size:
      raise ValueError('Task storage file size not set.')

    if task.file_entry_type == dfvfs_definitions.FILE_ENTRY_TYPE_DIRECTORY:
      weight = 1
    else:
      weight = storage_file_size

    task.merge_priority = weight

    heap_values = (weight, task)
    heapq.heappush(self._heap, heap_values)
    self._task_identifiers.add(task.identifier)

Pushes a task onto the heap.

Args:
task (Task): task.

Raises:
ValueError: if the size of the storage file is not set in the task.


def ParseMessage(self, parser_mediator, key, date_time, tokens):
    if (key not in ('failed_connection', 'login', 'opened_connection')):
        raise ValueError('Unknown grammar key: {0:s}'.format(key))
    if (key == 'login'):
        event_data = SSHLoginEventData()
    elif (key == 'failed_connection'):
        event_data = SSHFailedConnectionEventData()
    elif (key == 'opened_connection'):
        event_data = SSHOpenedConnectionEventData()
    event_data.address = tokens.get('address', None)
    event_data.authentication_method = tokens.get('authentication_method', None)
    event_data.body = tokens.get('body', None)
    event_data.fingerprint = tokens.get('fingerprint', None)
    event_data.hostname = tokens.get('hostname', None)
    event_data.offset = 0
    event_data.pid = tokens.get('pid', None)
    event_data.protocol = tokens.get('protocol', None)
    event_data.port = tokens.get('port', None)
    event_data.reporter = tokens.get('reporter', None)
    event_data.severity = tokens.get('severity', None)
    event_data.username = tokens.get('username', None)
    event = time_events.DateTimeValuesEvent(date_time, definitions.TIME_DESCRIPTION_WRITTEN)
    parser_mediator.ProduceEventWithEventData(event, event_data)

Produces an event from a syslog body that matched one of the grammars.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
key (str): name of the matching grammar.
date_time (dfdatetime.DateTimeValues): date and time values.
tokens (dict[str, str]): tokens derived from a syslog message based on
the defined grammar.

Raises:
ValueError: If an unknown key is provided.


def make_method(ctx, node, name, params=None, posonly_count=0, kwonly_params=None, return_type=None, self_param=None, varargs=None, kwargs=None, kind=pytd.MethodKind.METHOD):

    def _process_annotation(param):

        param_type = param.typ
        if not param_type:
            return
        elif isinstance(param_type, cfg.Variable):
            types = param_type.data
            if len(types) == 1:
                annotations[param.name] = types[0].cls
            else:
                t = abstract.Union([t.cls for t in types], ctx)
                annotations[param.name] = t
        else:
            annotations[param.name] = param_type
    params = params or []
    kwonly_params = kwonly_params or []
    if kind in (pytd.MethodKind.METHOD, pytd.MethodKind.PROPERTY):
        self_param = [self_param or Param('self', None, None)]
    elif kind == pytd.MethodKind.CLASSMETHOD:
        self_param = [Param('cls', None, None)]
    else:
        assert kind == pytd.MethodKind.STATICMETHOD
        self_param = []
    annotations = {}
    params = self_param + params
    return_param = Param('return', return_type, None) if return_type else None
    special_params = [x for x in (return_param, varargs, kwargs) if x]
    for param in special_params + params + kwonly_params:
        _process_annotation(param)
    names = lambda xs: tuple((x.name for x in xs))
    param_names = names(params)
    kwonly_names = names(kwonly_params)
    defaults = {x.name: x.default for x in params + kwonly_params if x.default}
    varargs_name = varargs.name if varargs else None
    kwargs_name = kwargs.name if kwargs else None
    ret = abstract.SimpleFunction.build(name=name, param_names=param_names, posonly_count=posonly_count, varargs_name=varargs_name, kwonly_params=kwonly_names, kwargs_name=kwargs_name, defaults=defaults, annotations=annotations, ctx=ctx)
    ret.signature.check_defaults(ctx)
    retvar = ret.to_variable(node)
    if kind in (pytd.MethodKind.METHOD, pytd.MethodKind.PROPERTY):
        return retvar
    if kind == pytd.MethodKind.CLASSMETHOD:
        decorator = ctx.vm.load_special_builtin('classmethod')
    else:
        assert kind == pytd.MethodKind.STATICMETHOD
        decorator = ctx.vm.load_special_builtin('staticmethod')
    args = function.Args(posargs=(retvar,))
    return decorator.call(node, func=None, args=args)[1]

Make a method from params.

Args:
ctx: The context
node: Node to create the method variable at
name: The method name
params: Positional params [type: [Param]]
posonly_count: Number of positional-only parameters
kwonly_params: Keyword only params [type: [Param]]
return_type: Return type [type: PARAM_TYPES]
self_param: Self param [type: Param, defaults to self: Any]
varargs: Varargs param [type: Param, allows *args to be named and typed]
kwargs: Kwargs param [type: Param, allows **kwargs to be named and typed]
kind: The method kind

Returns:
A new method wrapped in a variable.


def on_snapshot(self, callback):
    return Watch.for_query(self, callback, document.DocumentSnapshot, document.DocumentReference)

Monitor the documents in this collection that match this query.

This starts a watch on this query using a background thread. The
provided callback is run on the snapshot of the documents.

Args:
callback(~.firestore.query.QuerySnapshot): a callback to run when
a change occurs.

Example:
from google.cloud import firestore_v1beta1

db = firestore_v1beta1.Client()
query_ref = db.collection(u'users').where("user", "==", u'Ada')

def on_snapshot(docs, changes, read_time):
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))

# Watch this query
query_watch = query_ref.on_snapshot(on_snapshot)

# Terminate this watch
query_watch.unsubscribe()


def _parse_ISBN_EAN(details):
    isbn_ean = _get_td_or_none(details, 'ctl00_ContentPlaceHolder1_tblRowIsbnEan')
    if (not isbn_ean):
        return (None, None)
    ean = None
    isbn = None
    if ('/' in isbn_ean):
        (isbn, ean) = isbn_ean.split('/')
        isbn = isbn.strip()
        ean = ean.strip()
    else:
        isbn = isbn_ean.strip()
    if (not isbn):
        isbn = None
    return (isbn, ean)

Parse ISBN and EAN.

Args:
details (obj): HTMLElement containing slice of the page with details.

Returns:
(ISBN, EAN): Tuple with two string or two None.


def _ParseFileEntryWithParser(self, parser_mediator, parser, file_entry, file_object=None):
    if (not isinstance(parser, (parsers_interface.FileEntryParser, parsers_interface.FileObjectParser))):
        raise TypeError('Unsupported parser object type.')
    parser_mediator.ClearParserChain()
    reference_count = parser_mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)
    parser_mediator.SampleStartTiming(parser.NAME)
    try:
        if isinstance(parser, parsers_interface.FileEntryParser):
            parser.Parse(parser_mediator)
        elif isinstance(parser, parsers_interface.FileObjectParser):
            parser.Parse(parser_mediator, file_object)
        result = self._PARSE_RESULT_SUCCESS
    except (IOError, dfvfs_errors.BackEndError) as exception:
        display_name = parser_mediator.GetDisplayName(file_entry)
        logger.warning('{0:s} unable to parse file: {1:s} with error: {2!s}'.format(parser.NAME, display_name, exception))
        result = self._PARSE_RESULT_FAILURE
    except errors.UnableToParseFile as exception:
        display_name = parser_mediator.GetDisplayName(file_entry)
        logger.debug('{0:s} unable to parse file: {1:s} with error: {2!s}'.format(parser.NAME, display_name, exception))
        result = self._PARSE_RESULT_UNSUPPORTED
    finally:
        parser_mediator.SampleStopTiming(parser.NAME)
        parser_mediator.SampleMemoryUsage(parser.NAME)
        new_reference_count = parser_mediator.resolver_context.GetFileObjectReferenceCount(file_entry.path_spec)
        if (reference_count != new_reference_count):
            display_name = parser_mediator.GetDisplayName(file_entry)
            logger.warning('[{0:s}] did not explicitly close file-object for file: {1:s}.'.format(parser.NAME, display_name))
    return result

Parses a file entry with a specific parser.

Args:
parser_mediator (ParserMediator): parser mediator.
parser (BaseParser): parser.
file_entry (dfvfs.FileEntry): file entry.
file_object (Optional[file]): file-like object to parse.
If not set the parser will use the parser mediator to open
the file entry's default data stream as a file-like object.

Returns:
int: parse result which is _PARSE_RESULT_FAILURE if the file entry
could not be parsed, _PARSE_RESULT_SUCCESS if the file entry
successfully was parsed or _PARSE_RESULT_UNSUPPORTED when
UnableToParseFile was raised.

Raises:
TypeError: if parser object is not a supported parser type.


def auth_proxy(self, method):

    def _proxy(*args, **kwargs):
        'The actual proxy, which instantiates and authenticates the API.\n\n            Args:\n                *args (mixed): Args to send to class instantiation.\n                **kwargs (mixed): Kwargs to send to class instantiation.\n\n            Returns:\n                mixed: The result of the authenticated callable.\n            '
        return method(self.session, *args, **kwargs)
    return _proxy

Authentication proxy for API requests.

This is required because the API objects are naive of ``HelpScout``,
so they would otherwise be unauthenticated.

Args:
method (callable): A method call that should be authenticated. It
should accept a ``requests.Session`` as its first parameter,
which should be used for the actual API call.

Returns:
mixed: The results of the authenticated callable.


def mds(means, weights, d):

    X = dim_reduce(means, weights, d)
    if X.shape[0]==2:
        return X.dot(weights)
    else:
        return X.T.dot(weights)

Dimensionality reduction using MDS.

Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality

Returns:
W_reduced (array): array of shape (d, cells)


def release(self, subnets):

        if isinstance(subnets, str) or isinstance(subnets, IPNetwork):
            subnets = [subnets]
        subnets_iter = (
            str(subnet) if isinstance(subnet, IPNetwork) else subnet
            for subnet in subnets
        )
        try:
            with self._create_lock():
                for subnet in subnets_iter:
                    self._release(self.create_lease_object_from_subnet(subnet))
        except (utils.TimerException, IOError):
            raise LagoSubnetLeaseLockException(self.path)

Free the lease of the given subnets

Args:
subnets (list of str or netaddr.IPAddress): dotted ipv4 subnet in
CIDR notation (for example ```192.168.200.0/24```) or IPAddress
object.

Raises:
LagoSubnetLeaseException: If subnet is a str and can't be parsed
LagoSubnetLeaseLockException:
If the lock to self.path can't be acquired.


def check_attribute_being_used(config_class, attributes, default_value, source_strings):
    attribute_used = False
    for attribute in attributes:
        for modeling_source in source_strings:
            if f'config.{attribute}' in modeling_source or f'getattr(config, "{attribute}"' in modeling_source or f'getattr(self.config, "{attribute}"' in modeling_source or ('TextConfig' in config_class.__name__ and f'config.get_text_config().{attribute}' in modeling_source):
                attribute_used = True
            elif re.search(f'getattr[ \\t\\v\\n\\r\\f]*\\([ \\t\\v\\n\\r\\f]*(self\\.)?config,[ \\t\\v\\n\\r\\f]*"{attribute}"', modeling_source) is not None:
                attribute_used = True
            if attribute_used:
                break
        if attribute_used:
            break
    attributes_to_allow = ['initializer_range', 'bos_index', 'eos_index', 'pad_index', 'unk_index', 'mask_index', 'image_token_id', 'video_token_id', 'image_seq_length', 'video_seq_length', 'image_size', 'text_config', 'use_cache', 'out_features', 'out_indices', 'sampling_rate', 'use_pretrained_backbone', 'backbone', 'backbone_config', 'use_timm_backbone', 'backbone_kwargs', 'rope_theta', 'partial_rotary_factor', 'pretraining_tp', 'boi_token_id', 'eoi_token_id']
    attributes_used_in_generation = ['encoder_no_repeat_ngram_size']
    case_allowed = True
    if not attribute_used:
        case_allowed = False
        for attribute in attributes:
            if attribute in ['is_encoder_decoder'] and default_value is True:
                case_allowed = True
            elif attribute in ['tie_word_embeddings'] and default_value is False:
                case_allowed = True
            elif attribute in attributes_to_allow + attributes_used_in_generation:
                case_allowed = True
            elif attribute.endswith('_token_id'):
                case_allowed = True
            if not case_allowed:
                allowed_cases = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, [])
                case_allowed = allowed_cases is True or attribute in allowed_cases
    return attribute_used or case_allowed

Check if any name in `attributes` is used in one of the strings in `source_strings`

Args:
config_class (`type`):
The configuration class for which the arguments in its `__init__` will be checked.
attributes (`List[str]`):
The name of an argument (or attribute) and its variant names if any.
default_value (`Any`):
A default value for the attribute in `attributes` assigned in the `__init__` of `config_class`.
source_strings (`List[str]`):
The python source code strings in the same modeling directory where `config_class` is defined. The file
containing the definition of `config_class` should be excluded.


def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None):

        countriesdata = cls.countriesdata(use_live=use_live)
        iso2 = countriesdata['iso2iso3'].get(iso3.upper())
        if iso2 is not None:
            return iso2

        if exception is not None:
            raise exception
        return None

Get ISO2 from ISO3 code

Args:
iso3 (str): ISO3 code for which to get ISO2 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to None.

Returns:
Optional[str]: ISO2 code


def preprocess(train_data_path: str, feature_thres: int, val_data_path: typing.Optional[str]=None) -> typing.Tuple[Dataset, typing.List[str], typing.Optional[Dataset]]:
    features = extract_features(train_data_path, feature_thres)
    feature_index = dict(((feature, i) for i, feature in enumerate(features)))
    train_dataset = load_dataset(train_data_path, feature_index)
    val_dataset = load_dataset(val_data_path, feature_index) if val_data_path else None
    return (train_dataset, features, val_dataset)

Loads entries and translates them into JAX arrays. The boolean matrix of
the input data is represented by row indices and column indices of True values
instead of the matrix itself for memory efficiency, assuming the matrix is
highly sparse. Row and column indices are not guaranteed to be sorted.

Args:
train_data_path (str): A file path to the training data file.
feature_thres (str): A threshold to filter out features whose number of
occurances does not exceed the value.
val_data_path (str, optional): A file path to the validation data file.

Returns:
A tuple of following items:
- train_dataset (Dataset): The training dataset.
- features (List[str]): The list of features.
- val_dataset (Optional[Dataset]): The validation dataset.
This becomes None if val_data_path is None.


def CEscape(text, as_utf8):
    Ord = (ord if isinstance(text, six.string_types) else (lambda x: x))
    if as_utf8:
        return ''.join((_cescape_utf8_to_str[Ord(c)] for c in text))
    return ''.join((_cescape_byte_to_str[Ord(c)] for c in text))

Escape a bytes string for use in an ascii protocol buffer.

text.encode('string_escape') does not seem to satisfy our needs as it
encodes unprintable characters using two-digit hex escapes whereas our
C++ unescaping function allows hex escapes to be any length.  So,
"\0011".encode('string_escape') ends up being "\\x011", which will be
decoded in C++ as a single-character string with char code 0x11.

Args:
text: A byte string to be escaped
as_utf8: Specifies if result should be returned in UTF-8 encoding
Returns:
Escaped string


def linear_add(self, other, scale_factor=1.0):

        if self.structure != other.structure:
            raise ValueError("Adding or subtraction operations can only be "
                             "performed for volumetric data with the exact "
                             "same structure.")

        data = {}
        for k in self.data.keys():
            data[k] = self.data[k] + scale_factor * other.data[k]
        return VolumetricData(self.structure, data, self._distance_matrix)

Method to do a linear sum of volumetric objects. Used by + and -
operators as well. Returns a VolumetricData object containing the
linear sum.

Args:
other (VolumetricData): Another VolumetricData object
scale_factor (float): Factor to scale the other data by.

Returns:
VolumetricData corresponding to self + scale_factor * other.


def GetMessages(self, formatter_mediator, event):

    if self.DATA_TYPE != event.data_type:
      raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
          event.data_type))

    event_values = event.CopyToDict()

    document_type = event_values.get('document_type', None)
    if document_type:
      event_values['document_type'] = self._DOC_TYPES.get(
          document_type, 'UNKNOWN')

    shared = event_values.get('shared', False)
    if shared:
      event_values['shared'] = 'Shared'
    else:
      event_values['shared'] = 'Private'

    return self._ConditionalFormatMessages(event_values)

Determines the formatted message strings for an event object.

Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.

Returns:
tuple(str, str): formatted message string and short message string.

Raises:
WrongFormatter: if the event object cannot be formatted by the formatter.


def job(self):
    if (self._submitter and hasattr(self._submitter, '_job_access')):
        return self._submitter._job_access()
    return None

REST binding for the job associated with the submitted build.

Returns:
Job: REST binding for running job or ``None`` if connection information was not available or no job was submitted.


def _ParseAccountsData(self, account_data):

    if not account_data:
      return {}
    lines = [line for line in account_data.splitlines() if line]
    user_map = {}
    for line in lines:
      if not all(ord(c) < 128 for c in line):
        self.logger.info('SSH key contains non-ascii character: %s.', line)
        continue
      split_line = line.split(':', 1)
      if len(split_line) != 2:
        self.logger.info('SSH key is not a complete entry: %s.', split_line)
        continue
      user, key = split_line
      if self._HasExpired(key):
        self.logger.debug('Expired SSH key for user %s: %s.', user, key)
        continue
      if user not in user_map:
        user_map[user] = []
      user_map[user].append(key)
    logging.debug('User accounts: %s.', user_map)
    return user_map

Parse the SSH key data into a user map.

Args:
account_data: string, the metadata server SSH key attributes data.

Returns:
dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.


def Filter(self, function=None):
    flat = (lambda x: (x if isinstance(x, str) else ''.join([flat(y) for y in x])))
    if (function is None):
        function = (lambda row: bool(flat(row.values)))
    new_table = self.__class__()
    new_table._table = [self.header]
    for row in self:
        if (function(row) is True):
            new_table.Append(row)
    return new_table

Construct Textable from the rows of which the function returns true.

Args:
function: A function applied to each row which returns a bool. If
function is None, all rows with empty column values are
removed.
Returns:
A new TextTable()

Raises:
TableError: When an invalid row entry is Append()'d


def paginate(db_query, items_per_page, offset=0, start_page=1):
    return Paginator(db_query, items_per_page, offset=offset, start_page=start_page)

Instantiates a Paginator instance for database queries.

Args:
db_query: The SQLAlchemy database query to paginate.
items_per_page: The desired number of items per page.
offset: The number of items to skip when paginating.
start_page: The number of the first page when reporting on page numbers.


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

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

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

Returns:
UInt160:


def add_note(path, filename='note.txt'):
    path = os.path.expanduser(path)
    assert os.path.isdir(path), '{} is not a valid directory.'.format(path)
    filepath = os.path.join(path, filename)
    exists = os.path.isfile(filepath)
    try:
        subprocess.call([EDITOR, filepath])
    except Exception as exc:
        logger.error('Editing note failed!')
        raise exc
    if exists:
        print('Note updated at:', filepath)
    else:
        print('Note created at:', filepath)

Opens a txt file at the given path where user can add and save notes.

Args:
path (str): Directory where note will be saved.
filename (str): Name of note. Defaults to "note.txt"


def create(self, document_data):

        batch = self._client.batch()
        batch.create(self, document_data)
        write_results = batch.commit()
        return _first_write_result(write_results)

Create the current document in the Firestore database.

Args:
document_data (dict): Property names and values to use for
creating a document.

Returns:
google.cloud.firestore_v1beta1.types.WriteResult: The
write result corresponding to the committed document. A write
result contains an ``update_time`` field.

Raises:
~google.cloud.exceptions.Conflict: If the document already exists.


def keep_alive(self):
    txn_response = self.api.http_request('POST', ('%sfcr:tx' % self.root), data=None, headers=None)
    if (txn_response.status_code == 204):
        logger.debug(('continuing transaction: %s' % self.root))
        self.active = True
        self.expires = txn_response.headers['Expires']
        return True
    elif (txn_response.status_code == 410):
        logger.debug(('transaction does not exist: %s' % self.root))
        self.active = False
        return False
    else:
        raise Exception(('HTTP %s, could not continue transaction' % txn_response.status_code))

Keep current transaction alive, updates self.expires

Args:
None

Return:
None: sets new self.expires


def coarse_graining(network, state, internal_indices):

    max_phi = float('-inf')
    max_coarse_grain = CoarseGrain((), ())

    for coarse_grain in all_coarse_grains(internal_indices):
        try:
            subsystem = MacroSubsystem(network, state, internal_indices,
                                       coarse_grain=coarse_grain)
        except ConditionallyDependentError:
            continue

        phi = compute.phi(subsystem)
        if (phi - max_phi) > constants.EPSILON:
            max_phi = phi
            max_coarse_grain = coarse_grain

    return (max_phi, max_coarse_grain)

Find the maximal coarse-graining of a micro-system.

Args:
network (Network): The network in question.
state (tuple[int]): The state of the network.
internal_indices (tuple[int]): Nodes in the micro-system.

Returns:
tuple[int, CoarseGrain]: The phi-value of the maximal |CoarseGrain|.


def _as_node_def_input(self):
    assert self._op.name
    if self.value_index == 0:
        return self._op.name
    else:
        return '%s:%d' % (self._op.name, self.value_index)

Return a value to use for the NodeDef "input" attribute.

The returned string can be used in a NodeDef "input" attribute
to indicate that the NodeDef uses this Tensor as input.

Raises:
ValueError: if this Tensor's Operation does not have a name.

Returns:
a string.


def serve(args):

    port = args.serve_port or PORT
    host = "0.0.0.0"

    dir_path = Path().absolute()
    web_dir = dir_path / "site"

    utils.set_routes()

    if args.offline:
        os.environ["MKINX_OFFLINE"] = "true"
        _ = subprocess.check_output("mkdocs build > /dev/null", shell=True)
        utils.make_offline()

    class MkinxHTTPHandler(SimpleHTTPRequestHandler):

        def translate_path(self, path):

            location = str(web_dir)
            route = location

            if len(path) != 0 and path != "/":
                for key, loc in utils.get_routes():
                    if path.startswith(key):
                        location = loc
                        path = path[len(key) :]
                        break

            if location[-1] == "/" or not path or path[0] == "/":
                route = location + path
            else:
                route = location + "/" + path

            return route.split("?")[0]

    success = False
    count = 0
    print("Waiting for server port...")
    try:
        while not success:
            try:
                httpd = socketserver.TCPServer((host, port), MkinxHTTPHandler)
                success = True
            except OSError:
                count += 1
            finally:
                if not success and count > 20:
                    s = "port {} seems occupied. Try with {} ? (y/n)"
                    if "y" in input(s.format(port, port + 1)):
                        port += 1
                        count = 0
                    else:
                        print("You can specify a custom port with mkinx serve -s")
                        return
                time.sleep(0.5)
    except KeyboardInterrupt:
        print("Aborting.")
        return

    httpd.allow_reuse_address = True
    print("\nServing at http:
    thread = threading.Thread(target=httpd.serve_forever)
    thread.daemon = True
    thread.start()

    event_handler = utils.MkinxFileHandler(
        patterns=["*.rst", "*.md", "*.yml", "*.yaml"]
    )
    observer = Observer()
    observer.schedule(event_handler, path=str(dir_path), recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
        httpd.server_close()
    observer.join()

Start a server which will watch .md and .rst files for changes.
If a md file changes, the Home Documentation is rebuilt. If a .rst
file changes, the updated sphinx project is rebuilt

Args:
args (ArgumentParser): flags from the CLI


def _BuildParser():
    parser = argparse.ArgumentParser(prog='yapf', description='Formatter for Python code.')
    parser.add_argument('-v', '--version', action='version', version='%(prog)s {}'.format(__version__))
    diff_inplace_quiet_group = parser.add_mutually_exclusive_group()
    diff_inplace_quiet_group.add_argument('-d', '--diff', action='store_true', help='print the diff for the fixed source')
    diff_inplace_quiet_group.add_argument('-i', '--in-place', action='store_true', help='make changes to files in place')
    diff_inplace_quiet_group.add_argument('-q', '--quiet', action='store_true', help='output nothing and set return value')
    lines_recursive_group = parser.add_mutually_exclusive_group()
    lines_recursive_group.add_argument('-r', '--recursive', action='store_true', help='run recursively over directories')
    lines_recursive_group.add_argument('-l', '--lines', metavar='START-END', action='append', default=None, help='range of lines to reformat, one-based')
    parser.add_argument('-e', '--exclude', metavar='PATTERN', action='append', default=None, help='patterns for files to exclude from formatting')
    parser.add_argument('--style', action='store', help='specify formatting style: either a style name (for example "pep8" or "google"), or the name of a file with style settings. The default is pep8 unless a %s or %s or %s file located in the same directory as the source or one of its parent directories (for stdin, the current directory is used).' % (style.LOCAL_STYLE, style.SETUP_CONFIG, style.PYPROJECT_TOML))
    parser.add_argument('--style-help', action='store_true', help='show style settings and exit; this output can be saved to .style.yapf to make your settings permanent')
    parser.add_argument('--no-local-style', action='store_true', help="don't search for local style definition")
    parser.add_argument('-p', '--parallel', action='store_true', help='run YAPF in parallel when formatting multiple files.')
    parser.add_argument('-m', '--print-modified', action='store_true', help='print out file names of modified files')
    parser.add_argument('-vv', '--verbose', action='store_true', help='print out file names while processing')
    parser.add_argument('files', nargs='*', help='reads from stdin when no files are specified.')
    return parser

Constructs the parser for the command line arguments.

Returns:
An ArgumentParser instance for the CLI.


def group_pairs(pair_list):
    groupid_to_items = defaultdict(list)
    for (item, groupid) in pair_list:
        groupid_to_items[groupid].append(item)
    return groupid_to_items

Groups a list of items using the first element in each pair as the item and
the second element as the groupid.

Args:
pair_list (list): list of 2-tuples (item, groupid)

Returns:
dict: groupid_to_items: maps a groupid to a list of items

SeeAlso:
group_items


def store_work_results(self, results, collection, md5):

        results['md5'] = md5
        results['__time_stamp'] = datetime.datetime.utcnow()

        if 'mod_time' not in results:
            results['mod_time'] = results['__time_stamp']

        try:
            self.database[collection].update({'md5':md5}, self.clean_for_storage(results), True)
        except pymongo.errors.OperationFailure:

            print 'Could not update exising object in capped collection, punting...'
            print 'collection: %s md5:%s' % (collection, md5)

Store the output results of the worker.

Args:
results: a dictionary.
collection: the database collection to store the results in.
md5: the md5 of sample data to be updated.


def run_pip_command(command_args, pip_version=None, python_version=None):

    pip_exe, context = find_pip(pip_version, python_version)
    command = [pip_exe] + list(command_args)

    if context is None:
        return popen(command)
    else:
        return context.execute_shell(command=command, block=False)

Run a pip command.

Args:
command_args (list of str): Args to pip.

Returns:
`subprocess.Popen`: Pip process.


def get_op_or_tensor_by_name(name):

    G = tfv1.get_default_graph()

    def f(n):
        if len(n) >= 3 and n[-2] == ':':
            return G.get_tensor_by_name(n)
        else:
            return G.get_operation_by_name(n)

    if not isinstance(name, list):
        return f(name)
    else:
        return list(map(f, name))

Get either tf.Operation of tf.Tensor from names.

Args:
name (list[str] or str): names of operations or tensors.

Raises:
KeyError, if the name doesn't exist


def process(self, metrics, config):
    LOG.debug('Process called')
    for metric in metrics:
        metric.tags['instance-id'] = config['instance-id']
    return metrics

Processes metrics.

This method is called by the Snap deamon during the process phase
of the execution of a Snap workflow.  Examples of processing metrics
include applying filtering, max, min, average functions as well as
adding additional context to the metrics to name just a few.

In this example we are adding a tag called 'context' to every metric.

Args:
metrics (obj:`list` of `snap_plugin.v1.Metric`):
List of metrics to be processed.

Returns:
:obj:`list` of `snap_plugin.v1.Metric`:
List of processed metrics.


def get_rel_pos(self, q_size: int, k_size: int, rel_pos: tf.Tensor) -> tf.Tensor:
    max_rel_dist = int(2 * max(q_size, k_size) - 1)
    if rel_pos.shape[0] != max_rel_dist:
        rel_pos_resized = tf.image.resize(tf.reshape(rel_pos, (1, rel_pos.shape[0], -1)), size=(max_rel_dist, rel_pos.shape[1]), method='bilinear')
        rel_pos_resized = tf.reshape(rel_pos_resized, (-1, max_rel_dist))
    else:
        rel_pos_resized = rel_pos
    q_coords = tf.expand_dims(tf.range(q_size, dtype=tf.float32), 1) * max(k_size / q_size, 1.0)
    k_coords = tf.expand_dims(tf.range(k_size, dtype=tf.float32), 0) * max(q_size / k_size, 1.0)
    relative_coords = q_coords - k_coords + (k_size - 1) * max(q_size / k_size, 1.0)
    return tf.gather(rel_pos_resized, tf.cast(relative_coords, tf.int32))

Get relative positional embeddings according to the relative positions of
query and key sizes.

Args:
q_size (int):
size of the query.
k_size (int):
size of key k.
rel_pos (`tf.Tensor`):
relative position embeddings (L, channel).

Returns:
Extracted positional embeddings according to relative positions.


def find_by_or(cls, payload):
    if (not isinstance(payload, dict)):
        raise ValueError("The 'payload' parameter must be provided a dictionary object.")
    url = os.path.join(cls.URL, 'find_by_or')
    payload = {'find_by_or': payload}
    cls.debug_logger.debug('Searching Pulsar {} for {}'.format(cls.__name__, json.dumps(payload, indent=4)))
    res = requests.post(url=url, json=payload, headers=HEADERS, verify=False)
    cls.write_response_html_to_file(res, 'bob.html')
    if res:
        try:
            res = res[cls.MODEL_NAME]
        except KeyError:
            pass
    return res

Searches the model in question by OR joining the query parameters.

Implements a Railsy way of looking for a record using a method by the same name and passing
in the query as a string (for the OR operator joining to be specified).

Only the first hit is returned, and there is not particular ordering specified in the server-side
API method.

Args:
payload: `dict`. The attributes of a record to search for by using OR operator joining
for each query parameter.

Returns:
`dict`: The JSON serialization of the record, if any, found by the API call.
`None`: If the API call didnt' return any results.


def _is_working_path(dom, path, element):

    def i_or_none(el, i):
        '\n        Return ``el[i]`` if the list is not blank, or None otherwise.\n\n        Args:\n            el (list, tuple): Any indexable object.\n            i (int): Index.\n\n        Returns:\n            obj: Element at index `i` if `el` is not blank, or ``None``.\n        '
        if (not el):
            return None
        return el[i]
    path_functions = {'find': (lambda el, index, params: i_or_none(el.find(*params), index)), 'wfind': (lambda el, index, params: i_or_none(el.wfind(*params).childs, index)), 'match': (lambda el, index, params: i_or_none(el.match(*params), index)), 'left_neighbour_tag': (lambda el, index, neigh_data: i_or_none(el.find(neigh_data.tag_name, neigh_data.params, fn=utils.has_neigh(*neigh_data.fn_params, left=True)), index)), 'right_neighbour_tag': (lambda el, index, neigh_data: i_or_none(el.find(neigh_data.tag_name, neigh_data.params, fn=utils.has_neigh(*neigh_data.fn_params, left=False)), index))}
    el = None
    if isinstance(path, PathCall):
        el = path_functions[path.call_type](dom, path.index, path.params)
    elif isinstance(path, Chained):
        for path in path.chain:
            dom = path_functions[path.call_type](dom, path.index, path.params)
            if (not dom):
                return False
        el = dom
    else:
        raise UserWarning(('Unknown type of path parameters! (%s)' % str(path)))
    if (not el):
        return False
    return (el.getContent().strip() == element.getContent().strip())

Check whether the path is working or not.

Aply proper search function interpreting `path` to `dom` and check, if
returned object is `element`. If so, return ``True``, otherwise ``False``.

Args:
dom (obj): HTMLElement DOM.
path (obj): :class:`.PathCall` Instance containing informations about
path and which function it require to obtain element the
path is pointing to.
element (obj): HTMLElement instance used to decide whether `path`
points to correct `element` or not.

Returns:
bool: True if `path` correctly points to proper `element`.


def delete(self, teamId):

        check_type(teamId, basestring, may_be_none=False)

        self._session.delete(API_ENDPOINT + '/' + teamId)

Delete a team.

Args:
teamId(basestring): The ID of the team to be deleted.

Raises:
TypeError: If the parameter types are incorrect.
ApiError: If the Webex Teams cloud returns an error.


def get_repeated_from_extensions(extension_list: List[message.Message], repeated_cls: Type[_T]) -> List[_T]:
    result = []
    if not extension_list:
        return result
    url = annotation_utils.get_structure_definition_url(repeated_cls.DESCRIPTOR)
    for extension in extension_list:
        if cast(Any, extension).url.value == url:
            msg = extension_to_message(extension, repeated_cls)
            result.append(msg)
    return result

Extracts matching extensions from extension_list and serializes to protos.

Args:
extension_list: The list of FHIR extensions to examine.
repeated_cls: The type of message to serialize to.

Returns:
A list of protos of instance repeated_cls representing the extensions within
extension_list.


def is_symbolic_tensor(tensor) -> bool:
    return isinstance(tensor, SymbolicTensor)

Test if `tensor` is a symbolic Tensor.

Args:
tensor: a tensor-like object

Returns:
True if `tensor` is a symbolic tensor (not an eager tensor).


def paginator(limit, offset, record_count, base_uri, page_nav_tpl='&limit={}&offset={}'):
    total_pages = int(math.ceil((record_count / limit)))
    next_cond = ((limit + offset) <= record_count)
    prev_cond = (offset >= limit)
    next_page = ((base_uri + page_nav_tpl.format(limit, (offset + limit))) if next_cond else None)
    prev_page = ((base_uri + page_nav_tpl.format(limit, (offset - limit))) if prev_cond else None)
    return OrderedDict([('total_count', record_count), ('total_pages', total_pages), ('next_page', next_page), ('prev_page', prev_page)])

Compute pagination info for collection filtering.

Args:
limit (int): Collection filter limit.
offset (int): Collection filter offset.
record_count (int): Collection filter total record count.
base_uri (str): Collection filter base uri (without limit, offset)
page_nav_tpl (str): Pagination template.

Returns:
A mapping of pagination info.


def find_subclasses_in_module(base_classes, module):
    subclasses = []
    for _, module_member in module.__dict__.items():
        if inspect.isclass(module_member):
            for base_class in base_classes:
                if issubclass(module_member, base_class):
                    subclasses.append(module_member)
    return subclasses

Finds the subclasses of the given classes in the given module.

Args:
base_classes: list of classes, the base classes to look for the
subclasses of in the module.
module: module, the module to look for the subclasses in.

Returns:
A list of all of the subclasses found in the module.


def _get_value_type(cls, value):
    type_ = cls.typeDict.get(type(value))
    if type_ is None:
        type_ = 'CLASS' if inspect.isclass(value) else None
    if type_ is None and value is None:
        type_ = 'STRING'
    return type_

Infers the type of a given value.

Args:
value: The value whose type needs to be inferred. For 'DURATION' and
'TIMESTAMP', the corresponding Python type is datetime.timedelta and
datetime.datetime respectively. For Python classes, the API type is
just 'STRING' at the moment.

Returns:
One of 'STRING', 'INTEGER', 'FLOAT', 'CLASS', 'DURATION', or
'TIMESTAMP', depending on the type of the value.


def __init__(self, server_port, dump_dir, toggle_watch_on_core_metadata=None):
    self.core_metadata_json_strings = []
    self.partition_graph_defs = []
    self.debug_tensor_values = collections.defaultdict(list)
    self._initialize_toggle_watch_state(toggle_watch_on_core_metadata)
    grpc_debug_server.EventListenerBaseServicer.__init__(self, server_port, functools.partial(EventListenerTestStreamHandler, dump_dir, self))
    self._call_types = []
    self._call_keys = []
    self._origin_stacks = []
    self._origin_id_to_strings = []
    self._graph_tracebacks = []
    self._graph_versions = []
    self._source_files = []

Constructor of EventListenerTestServicer.

Args:
server_port: (int) The server port number.
dump_dir: (str) The root directory to which the data files will be
dumped. If empty or None, the received debug data will not be dumped
to the file system: they will be stored in memory instead.
toggle_watch_on_core_metadata: A list of
(node_name, output_slot, debug_op) tuples to toggle the
watchpoint status during the on_core_metadata calls (optional).


def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]:
    sep = [self.sep_token_id]
    cls = [self.cls_token_id]
    if token_ids_1 is None:
        return cls + token_ids_0 + sep
    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. An ALBERT 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 set_servo_angle(self, goalangle, goaltime, led):

        if (self.servomodel==0x06) or (self.servomodel == 0x04):
            goalposition = scale(goalangle, -159.9, 159.6, 10627, 22129)
        else:
            goalposition = scale(goalangle, -150, 150, 21, 1002)

        self.set_servo_position(goalposition, goaltime, led)

Sets the servo angle (in degrees)

Enable torque using torque_on function before calling this

Args:
goalangle (int): The desired angle in degrees, range -150 to 150
goaltime (int): the time taken to move from present
position to goalposition
led (int): the LED color
0x00 LED off
0x04 GREEN
0x08 BLUE
0x10 RED


def get_request_message(cls, remote_info):

    if remote_info in cls.__remote_info_cache:
      return cls.__remote_info_cache[remote_info]
    else:
      return remote_info.request_type()

Gets request message or container from remote info.

Args:
remote_info: Instance of protorpc.remote._RemoteMethodInfo corresponding
to a method.

Returns:
Either an instance of the request type from the remote or the
ResourceContainer that was cached with the remote method.


def _initial_population_gsa(population_size, solution_size, lower_bounds, upper_bounds):
    if ((len(lower_bounds) != solution_size) or (len(upper_bounds) != solution_size)):
        raise ValueError('Lower and upper bounds much have a length equal to the problem size.')
    return common.make_population(population_size, common.random_real_solution, solution_size, lower_bounds, upper_bounds)

Create a random initial population of floating point values.

Args:
population_size: an integer representing the number of solutions in the population.
problem_size: the number of values in each solution.
lower_bounds: a list, each value is a lower bound for the corresponding
part of the solution.
upper_bounds: a list, each value is a upper bound for the corresponding
part of the solution.

Returns:
list; A list of random solutions.


def get_node_details(self, node_id: list) -> dict:

        if not self._manager:
            raise RuntimeError('Only the Swarm manager node can '
                               'retrieve node details.')

        node = self._client.nodes.get(node_id)
        return node.attrs

Get details of a node.

Only the manager nodes can retrieve details of a node

Args:
node_id (list): List of node ID

Returns:
dict, details of the node


def from_celery(cls, broker_dict):
    return BrokerStats(hostname=broker_dict['hostname'], port=broker_dict['port'], transport=broker_dict['transport'], virtual_host=broker_dict['virtual_host'])

Create a BrokerStats object from the dictionary returned by celery.

Args:
broker_dict (dict): The dictionary as returned by celery.

Returns:
BrokerStats: A fully initialized BrokerStats object.


def simple_repr(obj: Any, attrnames: List[str],
                with_addr: bool = False, joiner: str = COMMA_SPACE) -> str:

    elements = ["{}={}".format(name, repr(getattr(obj, name)))
                for name in attrnames]
    return repr_result(obj, elements, with_addr=with_addr, joiner=joiner)

Convenience function for :func:`__repr__`.
Works its way through a list of attribute names, and creates a ``repr()``
representation assuming that parameters to the constructor have the same
names.

Args:
obj: object to display
attrnames: names of attributes to include
with_addr: include the memory address of ``obj``
joiner: string with which to join the elements

Returns:
string: :func:`repr`-style representation


def remove_hallucinated_references(self, text: str) -> str:
    lines = text.split('\n')
    if len(lines) == 0:
        return ''
    clean_lines = remove_numbers(lines)
    slices = get_slices(lines, clean_lines)
    to_delete = []
    for slice in slices:
        to_delete.append(remove_slice_from_lines(lines, clean_lines, slice))
    for to_delete in reversed(to_delete):
        text = text.replace(to_delete, '\n\n[MISSING_PAGE_POST]\n\n')
    text = re.sub('
    return text

Remove hallucinated or missing references from the text.

This function identifies and removes references that are marked as missing or hallucinated from the input text.

Args:
text (`str`):
The input text containing references.

Returns:
`str`: The text with hallucinated references removed.


def create(configs):
    if not configs:
        raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG)
    elif configs == ANDROID_DEVICE_PICK_ALL_TOKEN:
        ads = get_all_instances()
    elif not isinstance(configs, list):
        raise Error(ANDROID_DEVICE_NOT_LIST_CONFIG_MSG)
    elif isinstance(configs[0], dict):
        ads = get_instances_with_configs(configs)
    elif isinstance(configs[0], str):
        ads = get_instances(configs)
    else:
        raise Error('No valid config found in: %s' % configs)
    _start_services_on_ads(ads)
    return ads

Creates AndroidDevice controller objects.

Args:
configs: Represents configurations for Android devices, this can take one of
the following forms:
* str, only asterisk symbol is accepted, indicating that all connected
Android devices will be used
* A list of dict, each representing a configuration for an Android device.
* A list of str, each representing the serial number of Android device.

Returns:
A list of AndroidDevice objects.


def fastcc(model, epsilon, solver):
    reaction_set = set(model.reactions)
    subset = set((reaction_id for reaction_id in reaction_set if (model.limits[reaction_id].lower >= 0)))
    logger.info('Checking {} irreversible reactions...'.format(len(subset)))
    logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
    p = FastcoreProblem(model, solver, epsilon=epsilon)
    p.lp7(subset)
    consistent_subset = set((reaction_id for reaction_id in model.reactions if (abs(p.get_flux(reaction_id)) >= (0.999 * epsilon))))
    logger.debug('|A| = {}, A = {}'.format(len(consistent_subset), consistent_subset))
    for reaction in (subset - consistent_subset):
        (yield reaction)
    subset = ((reaction_set - subset) - consistent_subset)
    logger.info('Checking reversible reactions...')
    logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
    flipped = False
    singleton = False
    while (len(subset) > 0):
        logger.info('{} reversible reactions left to check...'.format(len(subset)))
        if singleton:
            reaction = next(iter(subset))
            subset_i = {reaction}
            logger.debug('LP3 on {}'.format(subset_i))
            p.maximize({reaction: ((- 1) if p.is_flipped(reaction) else 1)})
        else:
            subset_i = subset
            logger.debug('LP7 on {}'.format(subset_i))
            p.lp7(subset_i)
        consistent_subset.update((reaction_id for reaction_id in subset if abs((p.get_flux(reaction_id) >= (0.999 * epsilon)))))
        logger.debug('|A| = {}, A = {}'.format(len(consistent_subset), consistent_subset))
        if (not subset.isdisjoint(consistent_subset)):
            subset -= consistent_subset
            logger.debug('|J| = {}, J = {}'.format(len(subset), subset))
            flipped = False
        else:
            subset_rev_i = (subset_i & model.reversible)
            if (flipped or (len(subset_rev_i) == 0)):
                flipped = False
                if singleton:
                    subset -= subset_rev_i
                    for reaction in subset_rev_i:
                        logger.info('Inconsistent: {}'.format(reaction))
                        (yield reaction)
                else:
                    singleton = True
            else:
                p.flip(subset_rev_i)
                flipped = True
                logger.info('Flipped {} reactions'.format(len(subset_rev_i)))

Check consistency of model reactions.

Yield all reactions in the model that are not part of the consistent
subset.

Args:
model: :class:`MetabolicModel` to solve.
epsilon: Flux threshold value.
solver: LP solver instance to use.


def take_reference_screenshot(webdriver, file_name):

        folder_location = os.path.join(ProjectUtils.get_project_root(),
                                       WebScreenShotUtil.REFERENCE_SCREEN_SHOT_LOCATION)

        WebScreenShotUtil.__capture_screenshot(
            webdriver, folder_location, file_name + ".png")

Captures a screenshot as a reference screenshot.

Args:
webdriver (WebDriver) - Selenium webdriver.
file_name (str) - File name to save screenshot as.


def get_course_current_grades(self, course_id):
    resp = self.requester.get(urljoin(self.base_url, '/api/grades/v1/courses/{course_key}/'.format(course_key=course_id)))
    resp.raise_for_status()
    resp_json = resp.json()
    if ('results' in resp_json):
        grade_entries = [CurrentGrade(entry) for entry in resp_json['results']]
        while (resp_json['next'] is not None):
            resp = self.requester.get(resp_json['next'])
            resp.raise_for_status()
            resp_json = resp.json()
            grade_entries.extend((CurrentGrade(entry) for entry in resp_json['results']))
    else:
        grade_entries = [CurrentGrade(entry) for entry in resp_json]
    return CurrentGradesByCourse(grade_entries)

Returns a CurrentGradesByCourse object for all users in the specified course.

Args:
course_id (str): an edX course ids.

Returns:
CurrentGradesByCourse: object representing the student current grades

Authorization:
The authenticated user must have staff permissions to see grades for all users
in a course.


def extract_q_df(self, state_key, action_key):
    q = 0.0
    if (self.q_df is None):
        self.save_q_df(state_key, action_key, q)
        return q
    q_df = self.q_df[(self.q_df.state_key == state_key)]
    q_df = q_df[(q_df.action_key == action_key)]
    if q_df.shape[0]:
        q = float(q_df['q_value'])
    else:
        self.save_q_df(state_key, action_key, q)
    return q

Extract Q-Value from `self.q_df`.

Args:
state_key:      The key of state.
action_key:     The key of action.

Returns:
Q-Value.


def cache_value(self, api_name, key, value):

        self._cache.setdefault(api_name, {})
        self._cache[api_name][key] = value

Add the value of an API call to the cache.

Args:
api_name: a string name of the API. Keys and values are segmented by api_name.
key: a string key for the specific call.
value: the value of the call using the specific key


def completer(*commands):

    def decorated_func(f):
        f.__complete_targets__ = list(commands)
        return f
    return decorated_func

Decorate a function to be the completer function of commands.

Arguments:
commands: Names of command that should trigger this function object.

------------------------------
Interface of completer methods:

@completer('some-other_command')
def complete_foo(self, args, text):
'''
Arguments:
args: A list of arguments. The first token, i.e, the command
itself, is not included.
text: The scope of text being replaced.

A few examples, with '$' representing the shell prompt and
'|' represents the cursor position:
$ |
$ history|
handled by the __driver_completer() method
$ history |
args = []
text = ''
$ history cle|
args = []
text = 'cle'
$ history clear |
args = ['clear']
text = ''

Returns:
A list of candidates. If no candidate was found, return
either [] or None.
'''
pass


def tf_action_exploration(self, action, exploration, action_spec):

        action_shape = tf.shape(input=action)
        exploration_value = exploration.tf_explore(
            episode=self.global_episode,
            timestep=self.global_timestep,
            shape=action_spec['shape']
        )
        exploration_value = tf.expand_dims(input=exploration_value, axis=0)

        if action_spec['type'] == 'bool':
            action = tf.where(
                condition=(tf.random_uniform(shape=action_shape) < exploration_value),
                x=(tf.random_uniform(shape=action_shape) < 0.5),
                y=action
            )

        elif action_spec['type'] == 'int':
            action = tf.where(
                condition=(tf.random_uniform(shape=action_shape) < exploration_value),
                x=tf.random_uniform(shape=action_shape, maxval=action_spec['num_actions'], dtype=util.tf_dtype('int')),
                y=action
            )

        elif action_spec['type'] == 'float':
            noise = tf.random_normal(shape=action_shape, dtype=util.tf_dtype('float'))
            action += noise * exploration_value
            if 'min_value' in action_spec:
                action = tf.clip_by_value(
                    t=action,
                    clip_value_min=action_spec['min_value'],
                    clip_value_max=action_spec['max_value']
                )

        return action

Applies optional exploration to the action (post-processor for action outputs).

Args:
action (tf.Tensor): The original output action tensor (to be post-processed).
exploration (Exploration): The Exploration object to use.
action_spec (dict): Dict specifying the action space.
Returns:
The post-processed action output tensor.


def refund(request, invoice_id):
    current_invoice = InvoiceController.for_id_or_404(invoice_id)
    try:
        current_invoice.refund()
        messages.success(request, 'This invoice has been refunded.')
    except ValidationError as ve:
        messages.error(request, ve)
    return redirect('invoice', invoice_id)

Marks an invoice as refunded and requests a credit note for the
full amount paid against the invoice.

This view requires a login, and the logged in user must be staff.

Arguments:
invoice_id (castable to int): The ID of the invoice to refund.

Returns:
redirect:
Redirects to ``invoice``.


def _OpenFileObject(self, path_spec):

    if not path_spec.HasParent():
      raise errors.PathSpecError(
          'Unsupported path specification without parent.')

    resolver.Resolver.key_chain.ExtractCredentialsFromPathSpec(path_spec)

    file_object = resolver.Resolver.OpenFileObject(
        path_spec.parent, resolver_context=self._resolver_context)
    fvde_volume = pyfvde.volume()
    fvde.FVDEVolumeOpen(
        fvde_volume, path_spec, file_object, resolver.Resolver.key_chain)
    return fvde_volume

Opens the file-like object defined by path specification.

Args:
path_spec (PathSpec): path specification.

Returns:
FileIO: a file-like object.

Raises:
PathSpecError: if the path specification is incorrect.


class MeanAbsoluteError(MeanMetricWrapper):

    def __init__(self, name='mean_absolute_error', dtype=None):
        super(MeanAbsoluteError, self).__init__(mean_absolute_error, name, dtype=dtype)

Computes the mean absolute error between the labels and predictions.

Args:
name: (Optional) string name of the metric instance.
dtype: (Optional) data type of the metric result.

Standalone usage:

>>> m = tf.keras.metrics.MeanAbsoluteError()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]])
>>> m.result().numpy()
0.25

>>> m.reset_state()
>>> m.update_state([[0, 1], [0, 0]], [[1, 1], [0, 0]],
...                sample_weight=[1, 0])
>>> m.result().numpy()
0.5

Usage with `compile()` API:

```python
model.compile(
optimizer='sgd',
loss='mse',
metrics=[tf.keras.metrics.MeanAbsoluteError()])
```


def normalize_build_spec(self, build_spec):

        for cmd in build_spec:
            if not cmd:
                continue
            cmd_name = cmd.keys()[0]
            cmd_options = cmd.values()[0]
            cmd_handler = self.get_cmd_handler(cmd_name)
            self.build_cmds.append(cmd_handler(cmd_options))

Convert a build spec into a list of Command tuples.
After running this command, self.build_cmds should hold all
the commands that should be run on the disk in self.disk_path.

Args:
build_spec (dict): The buildspec part from the init file


def begin_episode(self, agent_indices):
    with tf.name_scope('begin_episode/'):
        if (self._last_state is None):
            reset_state = tf.no_op()
        else:
            reset_state = utility.reinit_nested_vars(self._last_state, agent_indices)
        reset_buffer = self._current_episodes.clear(agent_indices)
        with tf.control_dependencies([reset_state, reset_buffer]):
            return tf.constant('')

Reset the recurrent states and stored episode.

Args:
agent_indices: Tensor containing current batch indices.

Returns:
Summary tensor.