def assert_input_compatibility(input_spec, inputs, layer_name):
    if not input_spec:
        return
    input_spec = nest.flatten(input_spec)
    if isinstance(inputs, dict):
        names = [spec.name for spec in input_spec]
        if all(names):
            list_inputs = []
            for name in names:
                if name not in inputs:
                    raise ValueError('Missing data for input "%s". You passed a data dictionary with keys %s. Expected the following keys: %s' % (name, list(inputs.keys()), names))
                list_inputs.append(inputs[name])
            inputs = list_inputs
    inputs = nest.flatten(inputs)
    for x in inputs:
        if not hasattr(x, 'shape'):
            raise TypeError('Inputs to a layer should be tensors. Got: %s' % (x,))
    if len(inputs) != len(input_spec):
        raise ValueError('Layer ' + layer_name + ' expects ' + str(len(input_spec)) + ' input(s), but it received ' + str(len(inputs)) + ' input tensors. Inputs received: ' + str(inputs))
    for input_index, (x, spec) in enumerate(zip(inputs, input_spec)):
        if spec is None:
            continue
        shape = tensor_shape.TensorShape(x.shape)
        if shape.rank is None:
            return
        if spec.ndim is not None and (not spec.allow_last_axis_squeeze):
            ndim = shape.rank
            if ndim != spec.ndim:
                raise ValueError('Input ' + str(input_index) + ' of layer ' + layer_name + ' is incompatible with the layer: expected ndim=' + str(spec.ndim) + ', found ndim=' + str(ndim) + '. Full shape received: ' + str(tuple(shape)))
        if spec.max_ndim is not None:
            ndim = x.shape.rank
            if ndim is not None and ndim > spec.max_ndim:
                raise ValueError('Input ' + str(input_index) + ' of layer ' + layer_name + ' is incompatible with the layer: expected max_ndim=' + str(spec.max_ndim) + ', found ndim=' + str(ndim))
        if spec.min_ndim is not None:
            ndim = x.shape.rank
            if ndim is not None and ndim < spec.min_ndim:
                raise ValueError('Input ' + str(input_index) + ' of layer ' + layer_name + ' is incompatible with the layer: : expected min_ndim=' + str(spec.min_ndim) + ', found ndim=' + str(ndim) + '. Full shape received: ' + str(tuple(shape)))
        if spec.dtype is not None:
            if x.dtype.name != spec.dtype:
                raise ValueError('Input ' + str(input_index) + ' of layer ' + layer_name + ' is incompatible with the layer: expected dtype=' + str(spec.dtype) + ', found dtype=' + str(x.dtype))
        shape_as_list = shape.as_list()
        if spec.axes:
            for axis, value in spec.axes.items():
                if hasattr(value, 'value'):
                    value = value.value
                if value is not None and shape_as_list[int(axis)] not in {value, None}:
                    raise ValueError('Input ' + str(input_index) + ' of layer ' + layer_name + ' is incompatible with the layer: expected axis ' + str(axis) + ' of input shape to have value ' + str(value) + ' but received input with shape ' + display_shape(x.shape))
        if spec.shape is not None and shape.rank is not None:
            spec_shape = spec.shape
            if spec.allow_last_axis_squeeze:
                if shape_as_list and shape_as_list[-1] == 1:
                    shape_as_list = shape_as_list[:-1]
                if spec_shape and spec_shape[-1] == 1:
                    spec_shape = spec_shape[:-1]
            for spec_dim, dim in zip(spec_shape, shape_as_list):
                if spec_dim is not None and dim is not None:
                    if spec_dim != dim:
                        raise ValueError('Input ' + str(input_index) + ' is incompatible with layer ' + layer_name + ': expected shape=' + str(spec.shape) + ', found shape=' + display_shape(x.shape))

Checks compatibility between the layer and provided inputs.

This checks that the tensor(s) `inputs` verify the input assumptions
of a layer (if any). If not, a clear and actional exception gets raised.

Args:
input_spec: An InputSpec instance, list of InputSpec instances, a nested
structure of InputSpec instances, or None.
inputs: Input tensor, list of input tensors, or a nested structure of
input tensors.
layer_name: String, name of the layer (for error message formatting).

Raises:
ValueError: in case of mismatch between
the provided inputs and the expectations of the layer.


def macro_state(self, micro_state):
    assert (len(micro_state) == len(self.micro_indices))
    reindexed = self.reindex()
    micro_state = np.array(micro_state)
    return tuple(((0 if (sum(micro_state[list(reindexed.partition[i])]) in self.grouping[i][0]) else 1) for i in self.macro_indices))

Translate a micro state to a macro state

Args:
micro_state (tuple[int]): The state of the micro nodes in this
coarse-graining.

Returns:
tuple[int]: The state of the macro system, translated as specified
by this coarse-graining.

Example:
>>> coarse_grain = CoarseGrain(((1, 2),), (((0,), (1, 2)),))
>>> coarse_grain.macro_state((0, 0))
(0,)
>>> coarse_grain.macro_state((1, 0))
(1,)
>>> coarse_grain.macro_state((1, 1))
(1,)


def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_3):
    if (kmip_version < enums.KMIPVersion.KMIP_1_3):
        raise exceptions.VersionNotSupported('KMIP {} does not support the CapabilityInformation object.'.format(kmip_version.value))
    local_buffer = BytearrayStream()
    if self._streaming_capability:
        self._streaming_capability.write(local_buffer, kmip_version=kmip_version)
    if self._asynchronous_capability:
        self._asynchronous_capability.write(local_buffer, kmip_version=kmip_version)
    if self._attestation_capability:
        self._attestation_capability.write(local_buffer, kmip_version=kmip_version)
    if (kmip_version >= enums.KMIPVersion.KMIP_1_4):
        if self._batch_undo_capability:
            self._batch_undo_capability.write(local_buffer, kmip_version=kmip_version)
        if self._batch_continue_capability:
            self._batch_continue_capability.write(local_buffer, kmip_version=kmip_version)
    if self._unwrap_mode:
        self._unwrap_mode.write(local_buffer, kmip_version=kmip_version)
    if self._destroy_action:
        self._destroy_action.write(local_buffer, kmip_version=kmip_version)
    if self._shredding_algorithm:
        self._shredding_algorithm.write(local_buffer, kmip_version=kmip_version)
    if self._rng_mode:
        self._rng_mode.write(local_buffer, kmip_version=kmip_version)
    self.length = local_buffer.length()
    super(CapabilityInformation, self).write(output_buffer, kmip_version=kmip_version)
    output_buffer.write(local_buffer.buffer)

Write the CapabilityInformation structure encoding to the data stream.

Args:
output_buffer (stream): A data stream in which to encode
CapabilityInformation structure data, supporting a write
method.
kmip_version (enum): A KMIPVersion enumeration defining the KMIP
version with which the object will be encoded. Optional,
defaults to KMIP 2.0.

Raises:
VersionNotSupported: Raised when a KMIP version is provided that
does not support the CapabilityInformation structure.


def disambiguate_text(self, text, language=None, entities=None):

        body = {
            "text": text,
            "entities": [],
            "onlyNER": "false",
            "customisation": "generic"
        }

        if language:
            body['language'] = {"lang": language}

        if entities:
            body['entities'] = entities

        result, status_code = self._process_query(body)

        if status_code != 200:
            logger.debug('Disambiguation failed.')

        return result, status_code

Call the disambiguation service in order to get meanings.

Args:
text (str): Text to be disambiguated.
language (str): language of text (if known)
entities (list): list of entities or mentions to be supplied by
the user.

Returns:
dict, int: API response and API status.


def generate_nearest_neighbour_lookup_table(self):
    self.jump_probability = {}
    for site_label_1 in self.connected_site_pairs:
        self.jump_probability[site_label_1] = {}
        for site_label_2 in self.connected_site_pairs[site_label_1]:
            self.jump_probability[site_label_1][site_label_2] = {}
            for coordination_1 in range(self.max_coordination_per_site[site_label_1]):
                self.jump_probability[site_label_1][site_label_2][coordination_1] = {}
                for coordination_2 in range(1, (self.max_coordination_per_site[site_label_2] + 1)):
                    self.jump_probability[site_label_1][site_label_2][coordination_1][coordination_2] = self.relative_probability(site_label_1, site_label_2, coordination_1, coordination_2)

Construct a look-up table of relative jump probabilities for a nearest-neighbour interaction Hamiltonian.

Args:
None.

Returns:
None.


def wait_until_page_ready(page_object, timeout=WTF_TIMEOUT_MANAGER.NORMAL):

        try:
            do_until(lambda: page_object.webdriver.execute_script("return document.readyState").lower()
                     == 'complete', timeout)
        except wait_utils.OperationTimeoutError:
            raise PageUtilOperationTimeoutError(
                "Timeout occurred while waiting for page to be ready.")

Waits until document.readyState == Complete (e.g. ready to execute javascript commands)

Args:
page_object (PageObject) : PageObject class

Kwargs:
timeout (number) : timeout period


def infer_from_frame_stack(self, ob_stack):
    (logits, vf) = self.sess.run([self.logits_t, self.value_function_t], feed_dict={self.obs_t: ob_stack})
    return (logits, vf)

Infer policy from stack of observations.

Args:
ob_stack: array of shape (1, frame_stack_size, height, width, channels)

Returns:
logits and vf.


def update(self, measurement, measurement_matrix):

        measurement_matrix = np.atleast_2d(measurement_matrix)
        expected_meas_mat_shape = (measurement.mean.shape[0], self.state_length)
        if measurement_matrix.shape != expected_meas_mat_shape:
            raise ValueError("Measurement matrix is wrong shape ({}). " \
                    "Expected: {}".format(
                        measurement_matrix.shape, expected_meas_mat_shape))

        self.measurements[-1].append(measurement)
        self.measurement_matrices[-1].append(measurement_matrix)

        prior = self.posterior_state_estimates[-1]

        innovation = measurement.mean - measurement_matrix.dot(prior.mean)
        innovation_cov = measurement_matrix.dot(prior.cov).dot(
            measurement_matrix.T)
        innovation_cov += measurement.cov
        kalman_gain = prior.cov.dot(measurement_matrix.T).dot(
            np.linalg.inv(innovation_cov))

        post = self.posterior_state_estimates[-1]
        self.posterior_state_estimates[-1] = MultivariateNormal(
            mean=post.mean + kalman_gain.dot(innovation),
            cov=post.cov - kalman_gain.dot(measurement_matrix).dot(prior.cov)
        )

After each :py:meth:`predict`, this method may be called repeatedly to
provide additional measurements for each time step.

Args:
measurement (MultivariateNormal): Measurement for this
time step with specified mean and covariance.
measurement_matrix (array): Measurement matrix for this measurement.


def find(self, predicate, first_n=0, device_name=None, exclude_node_names=None):
    if exclude_node_names:
        exclude_node_names = re.compile(exclude_node_names)
    matched_data = []
    for device in self._dump_tensor_data if device_name is None else (self._dump_tensor_data[device_name],):
        for datum in self._dump_tensor_data[device]:
            if exclude_node_names and exclude_node_names.match(datum.node_name):
                continue
            if predicate(datum, datum.get_tensor()):
                matched_data.append(datum)
                if first_n > 0 and len(matched_data) >= first_n:
                    return matched_data
    return matched_data

Find dumped tensor data by a certain predicate.

Args:
predicate: A callable that takes two input arguments:

```python
def predicate(debug_tensor_datum, tensor):
# returns a bool
```

where `debug_tensor_datum` is an instance of `DebugTensorDatum`, which
carries the metadata, such as the `Tensor`'s node name, output slot
timestamp, debug op name, etc.; and `tensor` is the dumped tensor value
as a `numpy.ndarray`.
first_n: (`int`) return only the first n `DebugTensotDatum` instances (in
time order) for which the predicate returns True. To return all the
`DebugTensotDatum` instances, let first_n be <= 0.
device_name: optional device name.
exclude_node_names: Optional regular expression to exclude nodes with
names matching the regular expression.

Returns:
A list of all `DebugTensorDatum` objects in this `DebugDumpDir` object
for which predicate returns True, sorted in ascending order of the
timestamp.


def select_copula(cls, X):

        frank = Bivariate(CopulaTypes.FRANK)
        frank.fit(X)

        if frank.tau <= 0:
            selected_theta = frank.theta
            selected_copula = CopulaTypes.FRANK
            return selected_copula, selected_theta

        copula_candidates = [frank]
        theta_candidates = [frank.theta]

        try:
            clayton = Bivariate(CopulaTypes.CLAYTON)
            clayton.fit(X)
            copula_candidates.append(clayton)
            theta_candidates.append(clayton.theta)
        except ValueError:

            pass

        try:
            gumbel = Bivariate(CopulaTypes.GUMBEL)
            gumbel.fit(X)
            copula_candidates.append(gumbel)
            theta_candidates.append(gumbel.theta)
        except ValueError:

            pass

        z_left, L, z_right, R = cls.compute_empirical(X)
        left_dependence, right_dependence = cls.get_dependencies(
            copula_candidates, z_left, z_right)

        cost_L = [np.sum((L - l) ** 2) for l in left_dependence]
        cost_R = [np.sum((R - r) ** 2) for r in right_dependence]
        cost_LR = np.add(cost_L, cost_R)

        selected_copula = np.argmax(cost_LR)
        selected_theta = theta_candidates[selected_copula]
        return CopulaTypes(selected_copula), selected_theta

Select best copula function based on likelihood.

Args:
X: 2-dimensional `np.ndarray`

Returns:
tuple: `tuple(CopulaType, float)` best fit and model param.


def are_equal_elements(a_el, b_el):
    if (a_el.tagName != b_el.tagName):
        return False
    if (sorted(a_el.attributes.items()) != sorted(b_el.attributes.items())):
        return False
    if (len(a_el.childNodes) != len(b_el.childNodes)):
        return False
    for (a_child_el, b_child_el) in zip(a_el.childNodes, b_el.childNodes):
        if (a_child_el.nodeType != b_child_el.nodeType):
            return False
        if ((a_child_el.nodeType == a_child_el.TEXT_NODE) and (a_child_el.data != b_child_el.data)):
            return False
        if ((a_child_el.nodeType == a_child_el.ELEMENT_NODE) and (not are_equal_elements(a_child_el, b_child_el))):
            return False
    return True

Normalize and compare ElementTrees for equality.

Args:
a_el: ElementTree
b_el: ElementTree
ElementTrees to compare for equality.

Returns:
bool: ``True`` if the ElementTrees are semantically equivalent.


def get_unspent_outputs(self):
    cursor = backend.query.get_unspent_outputs(self.connection)
    return (record for record in cursor)

Get the utxoset.

Returns:
generator of unspent_outputs.


def pull(self, project, run=None, entity=None):

        project, run = self.parse_slug(project, run=run)
        urls = self.download_urls(project, run, entity)
        responses = []
        for fileName in urls:
            _, response = self.download_write_file(urls[fileName])
            if response:
                responses.append(response)

        return responses

Download files from W&B

Args:
project (str): The project to download
run (str, optional): The run to upload to
entity (str, optional): The entity to scope this project to.  Defaults to wandb models

Returns:
The requests library response object


def obtain_all_variant_tensor_ops(dataset):
    return _traverse(dataset, lambda op: op.outputs[0].dtype == dtypes.variant)

Given an input dataset, finds all dataset ops used for construction.

A series of transformations would have created this dataset with each
transformation including zero or more Dataset ops, each producing a dataset
variant tensor. This method outputs all of them.

Args:
dataset: Dataset to find variant tensors for.

Returns:
A list of variant_tensor producing dataset ops used to construct this
dataset.


def download_supplementary_files(self, directory='./', download_sra=True, email=None, sra_kwargs=None):
    directory_path = os.path.abspath(os.path.join(directory, ('%s_%s_%s' % ('Supp', self.get_accession(), re.sub('[\\s\\*\\?\\(\\),\\.;]', '_', self.metadata['title'][0])))))
    utils.mkdir_p(os.path.abspath(directory_path))
    downloaded_paths = dict()
    if (sra_kwargs is None):
        sra_kwargs = {}
    blacklist = ('NONE',)
    for (metakey, metavalue) in iteritems(self.metadata):
        if ('supplementary_file' in metakey):
            assert ((len(metavalue) == 1) and (metavalue != ''))
            if (metavalue[0] in blacklist):
                logger.warn(("%s value is blacklisted as '%s' - skipping" % (metakey, metavalue[0])))
                continue
            if ('sra' not in metavalue[0]):
                download_path = os.path.abspath(os.path.join(directory, os.path.join(directory_path, metavalue[0].split('/')[(- 1)])))
                try:
                    utils.download_from_url(metavalue[0], download_path)
                    downloaded_paths[metavalue[0]] = download_path
                except Exception as err:
                    logger.error(('Cannot download %s supplementary file (%s)' % (self.get_accession(), err)))
    if download_sra:
        try:
            downloaded_files = self.download_SRA(email, directory=directory, **sra_kwargs)
            downloaded_paths.update(downloaded_files)
        except Exception as err:
            logger.error(('Cannot download %s SRA file (%s)' % (self.get_accession(), err)))
    return downloaded_paths

Download all supplementary data available for the sample.

Args:
directory (:obj:`str`): Directory to download the data (in this directory
function will create new directory with the files).
Defaults to "./".
download_sra (:obj:`bool`): Indicates whether to download SRA raw
data too. Defaults to True.
email (:obj:`str`): E-mail that will be provided to the Entrez.
It is mandatory if download_sra=True. Defaults to None.
sra_kwargs (:obj:`dict`, optional): Kwargs passed to the
download_SRA method. Defaults to None.

Returns:
:obj:`dict`: A key-value pair of name taken from the metadata and
paths downloaded, in the case of SRA files the key is ``SRA``.


def make_iaf_stack(total_event_size,
                   num_hidden_layers=2,
                   seed=None,
                   dtype=tf.float32):

  seed = tfd.SeedStream(seed, 'make_iaf_stack')

  def make_iaf():

    initializer = tf.compat.v2.keras.initializers.VarianceScaling(
        2 * 0.01, seed=seed() % (2**31 - 1))

    made = tfb.AutoregressiveLayer(
        params=2,
        event_shape=[total_event_size],
        hidden_units=[total_event_size] * num_hidden_layers,
        activation=tf.nn.elu,
        kernel_initializer=initializer,
        dtype=dtype)

    def shift_and_scale(x):

      x.set_shape(
          x.shape.merge_with([None] * (x.shape.ndims - 1) + [total_event_size]))
      return tf.unstack(made(x), num=2, axis=-1)

    return tfb.Invert(tfb.MaskedAutoregressiveFlow(shift_and_scale))

  def make_swap():

    permutation = list(reversed(range(total_event_size)))
    return tfb.Permute(permutation)

  bijector = make_iaf()
  bijector = make_swap()(bijector)
  bijector = make_iaf()(bijector)
  bijector = make_swap()(bijector)
  bijector = make_iaf()(bijector)
  bijector = make_swap()(bijector)

  return bijector

Creates an stacked IAF bijector.

This bijector operates on vector-valued events.

Args:
total_event_size: Number of dimensions to operate over.
num_hidden_layers: How many hidden layers to use in each IAF.
seed: Random seed for the initializers.
dtype: DType for the variables.

Returns:
bijector: The created bijector.


def addColumn(self, header, values=[]):
    if (len(values) == 0):
        self._impl.addColumn(header)
    else:
        assert (len(values) == self.getNumRows())
        if any((isinstance(value, basestring) for value in values)):
            values = list(map(str, values))
            self._impl.addColumnStr(header, values)
        elif all((isinstance(value, Real) for value in values)):
            values = list(map(float, values))
            self._impl.addColumnDbl(header, values)
        else:
            raise NotImplementedError

Add a new column with the corresponding header and values to the
dataframe.

Args:
header: The name of the new column.

values: A list of size :func:`~amplpy.DataFrame.getNumRows` with
all the values of the new column.


def unpack(self, buff, offset=0):

        try:
            self._value = struct.unpack_from(self._fmt, buff, offset)[0]
            if self.enum_ref:
                self._value = self.enum_ref(self._value)
        except (struct.error, TypeError, ValueError) as exception:
            msg = '{}; fmt = {}, buff = {}, offset = {}.'.format(exception,
                                                                 self._fmt,
                                                                 buff, offset)
            raise UnpackException(msg)

Unpack *buff* into this object.

This method will convert a binary data into a readable value according
to the attribute format.

Args:
buff (bytes): Binary buffer.
offset (int): Where to begin unpacking.

Raises:
:exc:`~.exceptions.UnpackException`: If unpack fails.


def ldap_sync(self, **kwargs):

        path = '/groups/%s/ldap_sync' % self.get_id()
        self.manager.gitlab.http_post(path, **kwargs)

Sync LDAP groups.

Args:
**kwargs: Extra options to send to the server (e.g. sudo)

Raises:
GitlabAuthenticationError: If authentication is not correct
GitlabCreateError: If the server cannot perform the request


def ensure_value_spec(value_spec: class_schema.ValueSpec, src_spec: class_schema.ValueSpec, root_path: typing.Optional[utils.KeyPath]=None) -> typing.Optional[class_schema.ValueSpec]:
    if isinstance(value_spec, Union):
        value_spec = value_spec.get_candidate(src_spec)
    if isinstance(value_spec, Any):
        return None
    if not src_spec.is_compatible(value_spec):
        raise TypeError(utils.message_on_path(f'Source spec {src_spec} is not compatible with destination spec {value_spec}.', root_path))
    return value_spec

Extract counter part from value spec that matches dest spec type.

Args:
value_spec: Value spec.
src_spec: Destination value spec.
root_path: An optional path for the value to include in error message.

Returns:
value_spec of src_spec_type

Raises:
TypeError: When value_spec cannot match src_spec_type.


def _SetUnknownFlag(self, name, value):

    setter = self.__dict__['__set_unknown']
    if setter:
      try:
        setter(name, value)
        return value
      except (TypeError, ValueError):
        raise exceptions.IllegalFlagValueError('"{1}" is not valid for --{0}'
                                               .format(name, value))
      except NameError:
        pass
    raise exceptions.UnrecognizedFlagError(name, value)

Returns value if setting flag |name| to |value| returned True.

Args:
name: Name of the flag to set.
value: Value to set.

Returns:
Flag value on successful call.

Raises:
UnrecognizedFlagError
IllegalFlagValueError


def from_composition_and_entries(comp, entries_in_chemsys, working_ion_symbol='Li'):
    pd = PhaseDiagram(entries_in_chemsys)
    return ConversionElectrode.from_composition_and_pd(comp, pd, working_ion_symbol)

Convenience constructor to make a ConversionElectrode from a
composition and all entries in a chemical system.

Args:
comp: Starting composition for ConversionElectrode, e.g.,
Composition("FeF3")
entries_in_chemsys: Sequence containing all entries in a
chemical system. E.g., all Li-Fe-F containing entries.
working_ion_symbol: Element symbol of working ion. Defaults to Li.


def adb_cmd(self, command, **kwargs):

        kwargs['timeout'] = kwargs.get('timeout', self._adb_shell_timeout)
        if isinstance(command, list) or isinstance(command, tuple):
            return self.adb_device.run_cmd(*list(command), **kwargs)
        return self.adb_device.run_cmd(command, **kwargs)

Run adb command, for example: adb(['pull', '/data/local/tmp/a.png'])

Args:
command: string or list of string

Returns:
command output


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 get_nodes_lines(self, **kwargs):
    params = {'Nodes': util.ints_to_string(kwargs.get('nodes', []))}
    result = self.make_request('bus', 'get_nodes_lines', **params)
    if (not util.check_result(result)):
        return (False, result.get('resultDescription', 'UNKNOWN ERROR'))
    values = util.response_list(result, 'resultValues')
    return (True, [emtype.NodeLinesItem(**a) for a in values])

Obtain stop IDs, coordinates and line information.

Args:
nodes (list[int] | int): nodes to query, may be empty to get
all nodes.

Returns:
Status boolean and parsed response (list[NodeLinesItem]), or message
string in case of error.


def google_api_initilaize(config, api_call, alias=None):
    if api_call['function'].endswith('list') or alias == 'list':
        api_call['iterate'] = True
    if api_call['api'] == 'dfareporting':
        if not api_call['function'].startswith('userProfiles'):
            is_superuser, profile_id = get_profile_for_api(config, api_call['auth'], api_call['kwargs']['id'] if api_call['function'] == 'accounts.get' else api_call['kwargs']['accountId'])
            api_call['kwargs']['profileId'] = profile_id
            if is_superuser:
                api_call['version'] = 'prerelease'
            elif 'accountId' in api_call['kwargs']:
                del api_call['kwargs']['accountId']

Some Google API calls require a lookup or pre-call, add it here.

Modifies the API call before actual execution with any data
specifically required by an endpoint.  Currently:

> dfa-reporting - look up user profile and add to call.

Args:
api_call (dict): the JSON for the API call as defined in recipe.
alias (string): mostly used to signal a list behavior (change to iterate in future?)

Returns (dict):
A modified JSON with additional API values added.
Currently mostly used by dfareporting API to add profile and account.

Raises:
ValueError: If a required key in the recipe is missing.


def __truediv__(self, other):

        return self.__class__(self.x, self.y.__truediv__(other), *self._args,
                              **self._kwargs)

True division of y
Args:
other: The divisor

Returns:
Spectrum object with y values divided


def bridge_create(br, may_exist=True, parent=None, vlan=None):
    param_may_exist = _param_may_exist(may_exist)
    if ((parent is not None) and (vlan is None)):
        raise ArgumentValueError('If parent is specified, vlan must also be specified.')
    if ((vlan is not None) and (parent is None)):
        raise ArgumentValueError('If vlan is specified, parent must also be specified.')
    param_parent = ('' if (parent is None) else ' {0}'.format(parent))
    param_vlan = ('' if (vlan is None) else ' {0}'.format(vlan))
    cmd = 'ovs-vsctl {1}add-br {0}{2}{3}'.format(br, param_may_exist, param_parent, param_vlan)
    result = __salt__['cmd.run_all'](cmd)
    return _retcode_to_bool(result['retcode'])

Creates a new bridge.

Args:
br: A string - bridge name
may_exist: Bool, if False - attempting to create a bridge that exists returns False.
parent: String, the name of the parent bridge (if the bridge shall be
created as a fake bridge). If specified, vlan must also be
specified.
vlan: Int, the VLAN ID of the bridge (if the bridge shall be created as
a fake bridge). If specified, parent must also be specified.

Returns:
True on success, else False.

.. versionadded:: 2016.3.0

CLI Example:
.. code-block:: bash

salt '*' openvswitch.bridge_create br0


def enableEditing(self, enabled):

        for button in self.buttons[1:]:
            button.setEnabled(enabled)
            if button.isChecked():
                button.setChecked(False)

        model = self.tableView.model()

        if model is not None:
            model.enableEditing(enabled)

Enable the editing buttons to add/remove rows/columns and to edit the data.

This method is also a slot.
In addition, the data of model will be made editable,
if the `enabled` parameter is true.

Args:
enabled (bool): This flag indicates, if the buttons
shall be activated.


def destringize(self, string):
    m = read_tuple_destr_pattern.match(string)
    if (not m):
        smbl.messages.error("'{}' is not a valid read name with respect to the RNF specification".format(string), program='RNFtools', subprogram='RNF format', exception=ValueError)
    groups = m.groups()
    self.prefix = groups[0]
    read_tuple_id = groups[1]
    self.read_tuple_id = int(read_tuple_id, 16)
    self.segments = []
    segments_str = groups[2:(- 1)]
    for b_str in segments_str:
        if (b_str is not None):
            if (b_str[0] == ','):
                b_str = b_str[1:]
            b = rnftools.rnfformat.Segment()
            b.destringize(b_str)
            self.segments.append(b)
    self.suffix = groups[(- 1)]

Get RNF values for this read from its textual representation and save them
into this object.

Args:
string(str): Textual representation of a read.

Raises:
ValueError


def doMove(self, orgresource, dstresource, dummy = 56184, stresource = 'F', bShareFireCopy = 'false'):

        url = nurls['doMove']

        data = {'userid': self.user_id,
                'useridx': self.useridx,
                'dummy': dummy,
                'orgresource': orgresource,
                'dstresource': dstresource,
                'overwrite': overwrite,
                'bShareFireCopy': bShareFireCopy,
                }

        r = self.session.post(url = url, data = data)

        try:
            j = json.loads(r.text)
        except:
            print '[*] Success checkUpload: 0 result'

            return False

        return self.resultManager(r.text)

DoMove

Args:
dummy: ???
orgresource: Path for a file which you want to move
dstresource: Destination path
bShareFireCopy: ???

Returns:
True: Move success
False: Move failed


def list_classes(mod_name):

    mod = sys.modules[mod_name]
    return [cls.__name__ for cls in mod.__dict__.values()
            if is_mod_class(mod, cls)]

Lists all classes declared in a module.

Args:
mod_name: the module name
Returns:
A list of functions declared in that module.


def write_input(self, output_dir, make_dir_if_not_present=True, include_cif=False):
    vinput = self.get_vasp_input()
    vinput.write_input(output_dir, make_dir_if_not_present=make_dir_if_not_present)
    if include_cif:
        s = vinput['POSCAR'].structure
        fname = (Path(output_dir) / ('%s.cif' % re.sub('\\s', '', s.formula)))
        s.to(filename=fname)

Writes a set of VASP input to a directory.

Args:
output_dir (str): Directory to output the VASP input files
make_dir_if_not_present (bool): Set to True if you want the
directory (and the whole path) to be created if it is not
present.
include_cif (bool): Whether to write a CIF file in the output
directory for easier opening by VESTA.


def validate_key(self, key):
    if (not models.PasswordResetToken.valid_tokens.filter(key=key).exists()):
        raise serializers.ValidationError(_('The provided reset token does not exist, or is expired.'))
    return key

Validate the provided reset key.

Returns:
The validated key.

Raises:
serializers.ValidationError:
If the provided key does not exist.


def _is_part_processor_protocol(obj: Any) -> bool:

    def _full_name(obj: Any) -> str:

        return obj.__module__ + '.' + getattr(obj, '__qualname__', '')
    if not callable(obj):
        return False
    if isinstance(obj, types.FunctionType):
        type_hint = typing.get_type_hints(obj)
    else:
        type_hint = typing.get_type_hints(obj.__call__)
    if 'return' not in type_hint:
        return False
    return_type = type_hint.pop('return')
    if len(type_hint) != 1:
        return False
    if len(typing.get_args(return_type)) != 1:
        return False
    if return_type.__qualname__ != 'AsyncIterable' or _full_name(typing.get_args(return_type)[0]) != _full_name(content_api.ProcessorPart):
        return False
    if _full_name(next(iter(type_hint.values()))) != _full_name(content_api.ProcessorPart):
        return False
    return True

Returns True if `obj` implements PartProcessorFn.

This function is needed as Processors and PartProcessors are Protocols and do
not have proper runtime type checking.

Args:
obj: any object or function


def _Open(self, path_spec, mode='rb'):

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

    resolver.Resolver.key_chain.ExtractCredentialsFromPathSpec(path_spec)

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

    try:
      fvde.FVDEVolumeOpen(
          fvde_volume, path_spec, file_object, resolver.Resolver.key_chain)
    except:
      file_object.close()
      raise

    self._fvde_volume = fvde_volume
    self._file_object = file_object

Opens the file system defined by path specification.

Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode. The default is 'rb'
read-only binary.

Raises:
AccessError: if the access to open the file was denied.
IOError: if the file system could not be opened.
PathSpecError: if the path specification is incorrect.
ValueError: if the path specification is invalid.


def update_user_groups(self, user, claims):
    if (settings.GROUPS_CLAIM is not None):
        django_groups = [group.name for group in user.groups.all()]
        if (settings.GROUPS_CLAIM in claims):
            claim_groups = claims[settings.GROUPS_CLAIM]
            if (not isinstance(claim_groups, list)):
                claim_groups = [claim_groups]
        else:
            logger.debug("The configured groups claim '{}' was not found in the access token".format(settings.GROUPS_CLAIM))
            claim_groups = []
        groups_to_remove = (set(django_groups) - set(claim_groups))
        groups_to_add = (set(claim_groups) - set(django_groups))
        for group_name in groups_to_remove:
            group = Group.objects.get(name=group_name)
            user.groups.remove(group)
            logger.debug("User removed from group '{}'".format(group_name))
        for group_name in groups_to_add:
            try:
                if settings.MIRROR_GROUPS:
                    (group, _) = Group.objects.get_or_create(name=group_name)
                    logger.debug("Created group '{}'".format(group_name))
                else:
                    group = Group.objects.get(name=group_name)
                user.groups.add(group)
                logger.debug("User added to group '{}'".format(group_name))
            except ObjectDoesNotExist:
                pass

Updates user group memberships based on the GROUPS_CLAIM setting.

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


def is_valid_op(self, symmop):
    coords = self.centered_mol.cart_coords
    for site in self.centered_mol:
        coord = symmop.operate(site.coords)
        ind = find_in_coord_list(coords, coord, self.tol)
        if (not ((len(ind) == 1) and (self.centered_mol[ind[0]].species == site.species))):
            return False
    return True

Check if a particular symmetry operation is a valid symmetry operation
for a molecule, i.e., the operation maps all atoms to another
equivalent atom.

Args:
symmop (SymmOp): Symmetry operation to test.

Returns:
(bool): Whether SymmOp is valid for Molecule.


def multiply(self, other):

        if not isinstance(other, Number):
            raise QiskitError("other is not a number")
        return Chi(other * self._data, self._input_dims, self._output_dims)

Return the QuantumChannel self + other.

Args:
other (complex): a complex number.

Returns:
Chi: the scalar multiplication other * self as a Chi object.

Raises:
QiskitError: if other is not a valid scalar.


def get_nested_plot_frame(obj, key_map, cached=False):

    clone = obj.map(lambda x: x)

    for it1, it2 in zip(obj.traverse(lambda x: x), clone.traverse(lambda x: x)):
        if isinstance(it1, DynamicMap):
            with disable_constant(it2.callback):
                it2.callback.inputs = it1.callback.inputs
    with item_check(False):
        return clone.map(lambda x: get_plot_frame(x, key_map, cached=cached),
                         [DynamicMap, HoloMap], clone=False)

Extracts a single frame from a nested object.

Replaces any HoloMap or DynamicMap in the nested data structure,
with the item corresponding to the supplied key.

Args:
obj: Nested Dimensioned object
key_map: Dictionary mapping between dimensions and key value
cached: Whether to allow looking up key in cache

Returns:
Nested datastructure where maps are replaced with single frames


def get_board(self, id, name=None):
    return self.create_board(dict(id=id, name=name))

Get a board

Returns:
Board: The board with the given `id`


def list(cls, session, mailbox):
    endpoint = ('/mailboxes/%d/conversations.json' % mailbox.id)
    return super(Conversations, cls).list(session, endpoint)

Return conversations in a mailbox.

Args:
session (requests.sessions.Session): Authenticated session.
mailbox (helpscout.models.Mailbox): Mailbox to list.

Returns:
RequestPaginator(output_type=helpscout.models.Conversation):
Conversations iterator.


def _GetMaxSizeFromNestedMaximumIterations(value, while_ctxt):
    value_name = value.name
    curr_ctxt = ops.get_default_graph()._get_control_flow_context()
    curr_ctxt_name = curr_ctxt.name if curr_ctxt is not None else ''
    max_size = constant_op.constant(1)
    while while_ctxt not in (None, curr_ctxt):
        max_iter = while_ctxt.maximum_iterations
        if max_iter is None:
            raise ValueError("Cannot create a gradient accumulator for tensor '%s' inside XLA while_loop because maximum_iterations was not passed to the tf.while_loop call ('%s')." % (value_name, while_ctxt.name))
        max_iter_ctxt = max_iter.op._get_control_flow_context()
        if util.IsContainingContext(curr_ctxt, max_iter_ctxt):
            max_size *= max_iter
        else:
            const_max_iter = tensor_util.constant_value(max_iter)
            if const_max_iter is None:
                raise ValueError("Cannot create a gradient accumulator for tensor '%s' inside XLA while_loop. maximum_iterations tensor '%s' for while_loop context '%s' must be statically known (e.g. a constant value or known shape dimension), or be defined at or outside the while loop context '%s' (currently defined in '%s')." % (value_name, max_iter.name, while_ctxt.name, curr_ctxt_name, max_iter_ctxt.name))
            max_size *= const_max_iter
        while_ctxt = util.GetContainingWhileContext(while_ctxt.outer_context, stop_ctxt=curr_ctxt)
    return max_size

Calculate a max_size for use by stack ops inside an XLA while_loop.

Args:
value: The value inside the while_loop forward context.  Used for printing
error messages.
while_ctxt: The forward context inside which value resides.  This does not
always match the value's immediate context, as `value` may be inside e.g.
a cond context inside the while_loop.

Returns:
A tensor containing the `max_size` to feed to a Stack initializer.

Raises:
ValueError: If `value` is nested inside a `while_loop` that either
lacks a `maximum_iterations` parameter, or the `maximum_iterations`
parameter:

- is inside a `while_loop` that is a parent of the calling context, and
- cannot be evaluated at graph build time to a constant.


def isempty(self, tables=None):
    tables = (tables or self.tables)
    for table in tables:
        if (self.num_rows(table) > 0):
            return False
    return True

Return whether a table or the entire database is empty.

A database is empty is if it has no tables. A table is empty
if it has no rows.

Arguments:

tables (sequence of str, optional): If provided, check
that the named tables are empty. If not provided, check
that all tables are empty.

Returns:

bool: True if tables are empty, else false.

Raises:

sql.OperationalError: If one or more of the tables do not
exist.


def remote_upload(self, remote_url, folder_id=None, headers=None):
    kwargs = {'folder': folder_id, 'headers': headers}
    params = {'url': remote_url}
    params.update({key: value for (key, value) in kwargs.items() if value})
    return self._get('remotedl/add', params=params)

Used to make a remote file upload to openload.co

Note:
If folder_id is not provided, the file will be uploaded to ``Home`` folder.

Args:
remote_url (str): direct link of file to be remotely downloaded.
folder_id (:obj:`str`, optional): folder-ID to upload to.
headers (:obj:`dict`, optional): additional HTTP headers (e.g. Cookies or HTTP Basic-Auth)

Returns:
dict: dictionary containing ("id": uploaded file id, "folderid"). ::

{
"id": "12",
"folderid": "4248"
}


def disassemble_instruction(self, instruction):

        if not util.is_integer(instruction):
            raise TypeError('Expected instruction to be an integer.')

        buf_size = self.MAX_BUF_SIZE
        buf = (ctypes.c_char * buf_size)()
        res = self._dll.JLINKARM_DisassembleInst(ctypes.byref(buf), buf_size, instruction)
        if res < 0:
            raise errors.JLinkException('Failed to disassemble instruction.')

        return ctypes.string_at(buf).decode()

Disassembles and returns the assembly instruction string.

Args:
self (JLink): the ``JLink`` instance.
instruction (int): the instruction address.

Returns:
A string corresponding to the assembly instruction string at the
given instruction address.

Raises:
JLinkException: on error.
TypeError: if ``instruction`` is not a number.


def remove_send_message(self, connection):
    if (connection in self._send_message):
        del self._send_message[connection]
        LOGGER.debug('Removed send_message function for connection %s', connection)
    else:
        LOGGER.warning('Attempted to remove send_message function for connection %s, but no send_message function was registered', connection)

Removes a send_message function previously registered
with the Dispatcher.

Args:
connection (str): A locally unique identifier provided
by the receiver of messages.


def adjust_internal_tacking_values(self,
                                       min_non_zero_index,
                                       max_index,
                                       total_added):

        if max_index >= 0:
            max_value = self.get_highest_equivalent_value(self.get_value_from_index(max_index))
            self.max_value = max(self.max_value, max_value)
        if min_non_zero_index >= 0:
            min_value = self.get_value_from_index(min_non_zero_index)
            self.min_value = min(self.min_value, min_value)
        self.total_count += total_added

Called during decoding and add to adjust the new min/max value and
total count

Args:
min_non_zero_index min nonzero index of all added counts (-1 if none)
max_index max index of all added counts (-1 if none)


def run_trials(runs):
    inside_runs = 0
    for _ in range(runs):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        inside_runs += 1 if x * x + y * y <= 1.0 else 0
    return (runs, inside_runs, 0)

Run trials and return a 3-tuple representing the results.

Args:
runs: Number of trial runs to be executed.

Returns:
A 3-tuple (total trials, inside trials, 0).

The final zero is needed solely to make sure that the combine_results function
has same type for inputs and outputs (a requirement for combiner functions).


def significant_control(self, num, entity_id, entity_type='individual', **kwargs):
    entities = {'individual': 'individual', 'corporate': 'corporate-entity', 'legal': 'legal-person', 'statements': 'persons-with-significant-control-statements', 'secure': 'super-secure'}
    try:
        entity = entities[entity_type]
    except KeyError as e:
        msg = ('Wrong entity_type supplied. Please choose from ' + 'individual, corporate, legal, statements or secure')
        raise Exception(msg) from e
    baseuri = ((self._BASE_URI + 'company/{}/persons-with-significant-control/'.format(num)) + '{}/{}'.format(entity, entity_id))
    res = self.session.get(baseuri, params=kwargs)
    self.handle_http_error(res)
    return res

Get details of a specific entity with significant control.

Args:
num (str, int): Company number to search on.
entity_id (str, int): Entity id to request details for
entity_type (str, int): What type of entity to search for. Defaults
to 'individual'. Other possible opetions are
'corporate' (for corporate entitys), 'legal' (for legal
persons), 'statements' (for a person with significant control
statement) and 'secure' (for a super secure person).
kwargs (dict): additional keywords passed into requests.session.get
*params* keyword.


def createCategoryFilter(self, positiveExamples):

        categoryFilter = self._fullClient.createCategoryFilter("CategoryFilter", positiveExamples)
        return categoryFilter.positions

Creates a filter fingerprint.
Args:
positiveExamples, list(str): The list of positive example texts.
Returns:
list of int: the positions representing the filter representing the texts
Raises:
CorticalioException: if the request was not successful


def __init__(self, port_no=None, queue_id=None):

        super().__init__()
        self.port_no = port_no
        self.queue_id = queue_id

Create a QueueStatsRequest with the optional parameters below.

Args:
port_no (:class:`int`, :class:`~pyof.v0x01.common.phy_port.Port`):
All ports if :attr:`.Port.OFPP_ALL`.
queue_id (int): All queues if OFPQ_ALL (``0xfffffff``).


def get_angle(v1, v2, units='degrees'):
    d = ((np.dot(v1, v2) / np.linalg.norm(v1)) / np.linalg.norm(v2))
    d = min(d, 1)
    d = max(d, (- 1))
    angle = math.acos(d)
    if (units == 'degrees'):
        return math.degrees(angle)
    elif (units == 'radians'):
        return angle
    else:
        raise ValueError('Invalid units {}'.format(units))

Calculates the angle between two vectors.

Args:
v1: Vector 1
v2: Vector 2
units: "degrees" or "radians". Defaults to "degrees".

Returns:
Angle between them in degrees.


def __init__(self, name, context=None):

    if context is None:
      context = google.datalab.Context.default()
    self._context = context
    self._api = _api.Api(context)
    self._name_parts = _utils.parse_dataset_name(name, self._api.project_id)
    self._full_name = '%s.%s' % self._name_parts
    self._info = None
    try:
      self._info = self._get_info()
    except google.datalab.utils.RequestException:
      pass

Initializes an instance of a Dataset.

Args:
name: the name of the dataset, as a string or (project_id, dataset_id) tuple.
context: an optional Context object providing project_id and credentials. If a specific
project id or credentials are unspecified, the default ones configured at the global
level are used.
Raises:
Exception if the name is invalid.


def to_script(self, wf_name='wf'):

        self._closed()

        script = []

        params = []
        returns = []
        for name, typ in self.wf_inputs.items():
            params.append('{}=\'{}\''.format(name, typ))
            returns.append(name)
        script.append('{} = {}.add_inputs({})'.format(
            ', '.join(returns), wf_name, ', '.join(params)))

        returns = []
        for name, step in self.wf_steps.items():
            pyname = step.python_name
            returns = ['{}_{}'.format(pyname, o) for o in step['out']]
            params = ['{}={}'.format(name, python_name(param))
                      for name, param in step['in'].items()]
            script.append('{} = {}.{}({})'.format(
                ', '.join(returns), wf_name, pyname, ', '.join(params)))

        params = []
        for name, details in self.wf_outputs.items():
            params.append('{}={}'.format(
                name, python_name(details['outputSource'])))
        script.append('{}.add_outputs({})'.format(wf_name, ', '.join(params)))

        return '\n'.join(script)

Generated and print the scriptcwl script for the currunt workflow.

Args:
wf_name (str): string used for the WorkflowGenerator object in the
generated script (default: ``wf``).


def url_to_text(self, url):

        path, headers = urllib.request.urlretrieve(url)
        return self.path_to_text(path)

Download PDF file and transform its document to string.

Args:
url:   PDF url.

Returns:
string.


def _validate_compose_list(destination_file, file_list, files_metadata=None, number_of_files=32):
    common.validate_file_path(destination_file)
    bucket = destination_file[0:(destination_file.index('/', 1) + 1)]
    try:
        if isinstance(file_list, types.StringTypes):
            raise TypeError
        list_len = len(file_list)
    except TypeError:
        raise TypeError('file_list must be a list')
    if (list_len > number_of_files):
        raise ValueError(('Compose attempted to create composite with too many(%i) components; limit is (%i).' % (list_len, number_of_files)))
    if (list_len <= 0):
        raise ValueError('Compose operation requires at least one component; 0 provided.')
    if (files_metadata is None):
        files_metadata = []
    elif (len(files_metadata) > list_len):
        raise ValueError(('files_metadata contains more entries(%i) than file_list(%i)' % (len(files_metadata), list_len)))
    list_of_files = []
    for (source_file, meta_data) in itertools.izip_longest(file_list, files_metadata):
        if (not isinstance(source_file, str)):
            raise TypeError('Each item of file_list must be a string')
        if source_file.startswith('/'):
            logging.warn('Detected a "/" at the start of the file, Unless the file name contains a "/" it  may cause files to be misread')
        if source_file.startswith(bucket):
            logging.warn('Detected bucket name at the start of the file, must not specify the bucket when listing file_names. May cause files to be misread')
        common.validate_file_path((bucket + source_file))
        list_entry = {}
        if (meta_data is not None):
            list_entry.update(meta_data)
        list_entry['Name'] = source_file
        list_of_files.append(list_entry)
    return (list_of_files, bucket)

Validates the file_list and merges the file_list, files_metadata.

Args:
destination: Path to the file (ie. /destination_bucket/destination_file).
file_list: List of files to compose, see compose for details.
files_metadata: Meta details for each file in the file_list.
number_of_files: Maximum number of files allowed in the list.

Returns:
A tuple (list_of_files, bucket):
list_of_files: Ready to use dict version of the list.
bucket: bucket name extracted from the file paths.


def is_github_repo_owner_the_official_one(context, repo_owner):
    official_repo_owner = context.config['official_github_repos_owner']
    if (not official_repo_owner):
        raise ConfigError('This worker does not have a defined owner for official GitHub repositories. Given "official_github_repos_owner": {}'.format(official_repo_owner))
    return (official_repo_owner == repo_owner)

Given a repo_owner, check if it matches the one configured to be the official one.

Args:
context (scriptworker.context.Context): the scriptworker context.
repo_owner (str): the repo_owner to verify

Raises:
scriptworker.exceptions.ConfigError: when no official owner was defined

Returns:
bool: True when ``repo_owner`` matches the one configured to be the official one


def get_key(self, key, request_only=False):
    values = {}
    requested_names = [x.name for x in self._package_requests if (not x.conflict)]
    for pkg in self.resolved_packages:
        if ((not request_only) or (pkg.name in requested_names)):
            value = getattr(pkg, key)
            if (value is not None):
                values[pkg.name] = (pkg, value)
    return values

Get a data key value for each resolved package.

Args:
key (str): String key of property, eg 'tools'.
request_only (bool): If True, only return the key from resolved
packages that were also present in the request.

Returns:
Dict of {pkg-name: (variant, value)}.


def validate(self, config):
    if (not isinstance(config, dict)):
        raise errors.SchemeValidationError('Scheme can only validate a dictionary config, but was given {} (type: {})'.format(config, type(config)))
    for arg in self.args:
        if (arg.name in config):
            arg.validate(config[arg.name])
        elif arg.required:
            raise errors.SchemeValidationError('Option "{}" is required, but not found.'.format(arg.name))

Validate the given config against the `Scheme`.

Args:
config (dict): The configuration to validate.

Raises:
errors.SchemeValidationError: The configuration fails
validation against the `Schema`.


def get_label_set(self, type_str=None):

        return {v.label_str for v in self.node_gen if type_str in (None, v.type_str)}

Get a set of label_str for the tree rooted at this node.

Args:
type_str:
SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include
information from nodes of that type.

Returns:
set: The labels of the nodes leading up to this node from the root.


def test_src_dir_path(relative_path):
    return os.path.join(os.environ['TEST_SRCDIR'], 'org_tensorflow/tensorflow', relative_path)

Creates an absolute test srcdir path given a relative path.

Args:
relative_path: a path relative to tensorflow root.
e.g. "contrib/session_bundle/example".

Returns:
An absolute path to the linked in runfiles.


def extractSchedule(self, schedule, period):
    ret = namedtuple('ret', ['Hour', 'Min', 'Tariff', 'Period', 'Schedule'])
    work_table = self.m_schd_1_to_4
    if (Schedules.Schedule_5 <= schedule <= Schedules.Schedule_6):
        work_table = self.m_schd_5_to_6
    period += 1
    schedule += 1
    ret.Period = str(period)
    ret.Schedule = str(schedule)
    if ((schedule < 1) or (schedule > Extents.Schedules) or (period < 0) or (period > Extents.Periods)):
        ekm_log(((('Out of bounds: tariff ' + str(period)) + ' for schedule ') + str(schedule)))
        ret.Hour = ret.Min = ret.Tariff = str(0)
        return ret
    idxhr = (((('Schedule_' + str(schedule)) + '_Period_') + str(period)) + '_Hour')
    idxmin = (((('Schedule_' + str(schedule)) + '_Period_') + str(period)) + '_Min')
    idxrate = (((('Schedule_' + str(schedule)) + '_Period_') + str(period)) + '_Tariff')
    if (idxhr not in work_table):
        ekm_log(('Incorrect index: ' + idxhr))
        ret.Hour = ret.Min = ret.Tariff = str(0)
        return ret
    if (idxmin not in work_table):
        ekm_log(('Incorrect index: ' + idxmin))
        ret.Hour = ret.Min = ret.Tariff = str(0)
        return ret
    if (idxrate not in work_table):
        ekm_log(('Incorrect index: ' + idxrate))
        ret.Hour = ret.Min = ret.Tariff = str(0)
        return ret
    ret.Hour = work_table[idxhr][MeterData.StringValue]
    ret.Min = work_table[idxmin][MeterData.StringValue].zfill(2)
    ret.Tariff = work_table[idxrate][MeterData.StringValue]
    return ret

Read a single schedule tariff from meter object buffer.

Args:
schedule (int): A :class:`~ekmmeters.Schedules` value or in range(Extent.Schedules).
tariff (int): A :class:`~ekmmeters.Tariffs` value or in range(Extent.Tariffs).

Returns:
bool: True on completion.


def _parse_logging(log_values: dict, service_config: dict):

        for log_key, log_value in log_values.items():
            if 'driver' in log_key:
                service_config['log_driver'] = log_value
            if 'options' in log_key:
                service_config['log_driver_options'] = log_value

Parse log key.

Args:
log_values (dict): logging configuration values
service_config (dict): Service specification


def getWindow(title, exact=False):
    titles = getWindows()
    hwnd = titles.get(title, None)
    if ((not hwnd) and (not exact)):
        for (k, v) in titles.items():
            if (title in k):
                hwnd = v
                break
    if hwnd:
        return Window(hwnd)
    else:
        return None

Return Window object if 'title' or its part found in visible windows titles, else return None

Return only 1 window found first
Args:
title: unicode string
exact (bool): True if search only exact match


def connectivity_array(self):
    cart_coords = np.array(self.s.cart_coords)
    all_sites = (cart_coords[(:, None, :)] + self.cart_offsets[(None, :, :)])
    vt = Voronoi(all_sites.reshape(((- 1), 3)))
    n_images = all_sites.shape[1]
    cs = (len(self.s), len(self.s), len(self.cart_offsets))
    connectivity = np.zeros(cs)
    vts = np.array(vt.vertices)
    for ((ki, kj), v) in vt.ridge_dict.items():
        atomi = (ki
        atomj = (kj
        imagei = (ki % n_images)
        imagej = (kj % n_images)
        if ((imagei != (n_images
            continue
        if (imagei == (n_images
            val = solid_angle(vt.points[ki], vts[v])
            connectivity[(atomi, atomj, imagej)] = val
        if (imagej == (n_images
            val = solid_angle(vt.points[kj], vts[v])
            connectivity[(atomj, atomi, imagei)] = val
        if ((- 10.101) in vts[v]):
            warn('Found connectivity with infinite vertex. Cutoff is too low, and results may be incorrect')
    return connectivity

Provides connectivity array.

Returns:
connectivity: An array of shape [atomi, atomj, imagej]. atomi is
the index of the atom in the input structure. Since the second
atom can be outside of the unit cell, it must be described
by both an atom index and an image index. Array data is the
solid angle of polygon between atomi and imagej of atomj


def run_config_diagnostics(config_path=CONFIG_PATH):
    config = read_config(config_path)
    missing_sections = set()
    malformed_entries = defaultdict(set)
    for (section, expected_section_keys) in SECTION_KEYS.items():
        section_content = config.get(section)
        if (not section_content):
            missing_sections.add(section)
        else:
            for option in expected_section_keys:
                option_value = section_content.get(option)
                if (not option_value):
                    malformed_entries[section].add(option)
    return (config_path, missing_sections, malformed_entries)

Run diagnostics on the configuration file.

Args:
config_path (str): Path to the configuration file.
Returns:
str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing
sections and a dict that maps each section to the entries that have either missing or empty
options.


def add_arguments(self, parser):

        parser.add_argument('name', nargs=1, choices=['kinetis'],
                            help='name of MCU to unlock')
        return self.add_common_arguments(parser, True)

Adds the unlock command arguments to the parser.

Args:
self (UnlockCommand): the ``UnlockCommand`` instance
parser (argparse.ArgumentParser): the parser to add the arguments to

Returns:
``None``


def acquaint_insides(swap_gate: ops.Gate, acquaintance_gate: ops.Operation, qubits: Sequence[ops.Qid], before: bool, layers: Layers, mapping: Dict[(ops.Qid, int)]) -> None:
    max_reach = _get_max_reach(len(qubits), round_up=before)
    reaches = itertools.chain(range(1, (max_reach + 1)), range(max_reach, (- 1), (- 1)))
    offsets = ((0, 1) * max_reach)
    swap_gate = SwapPermutationGate(swap_gate)
    ops = []
    for (offset, reach) in zip(offsets, reaches):
        if (offset == before):
            ops.append(acquaintance_gate)
        for dr in range(offset, reach, 2):
            ops.append(swap_gate(*qubits[dr:(dr + 2)]))
    intrastitial_layer = getattr(layers, ('pre' if before else 'post'))
    intrastitial_layer += ops
    interstitial_layer = getattr(layers, (('prior' if before else 'posterior') + '_interstitial'))
    interstitial_layer.append(acquaintance_gate)
    reached_qubits = qubits[:(max_reach + 1)]
    positions = list((mapping[q] for q in reached_qubits))
    mapping.update(zip(reached_qubits, reversed(positions)))

Acquaints each of the qubits with another set specified by an
acquaintance gate.

Args:
qubits: The list of qubits of which half are individually acquainted
with another list of qubits.
layers: The layers to put gates into.
acquaintance_gate: The acquaintance gate that acquaints the end qubit
with another list of qubits.
before: Whether the acquainting is done before the shift.
swap_gate: The gate used to swap logical indices.
mapping: The mapping from qubits to logical indices. Used to keep track
of the effect of inside-acquainting swaps.


def log(self, metric):
    message = self.LOGFMT.format(**metric)
    if metric['context']:
        message += ' context: {context}'.format(context=metric['context'])
    self._logger.log(self.level, message)

Format and output metric.

Args:
metric (dict): Complete metric.


def split_input(cls, mapper_spec):

    batch_size = int(_get_params(mapper_spec).get(
        cls.BATCH_SIZE_PARAM, cls._BATCH_SIZE))
    shard_count = mapper_spec.shard_count
    namespace_ranges = namespace_range.NamespaceRange.split(shard_count,
                                                            contiguous=True)
    return [NamespaceInputReader(ns_range, batch_size)
            for ns_range in namespace_ranges]

Returns a list of input readers for the input spec.

Args:
mapper_spec: The MapperSpec for this InputReader.

Returns:
A list of InputReaders.


def Validate(self, expression):

    parsed = self._Load(expression)

    if not parsed:
      raise DefinitionError("Empty StatFilter expression.")

    bad_keys = set(parsed) - self._KEYS
    if bad_keys:
      raise DefinitionError("Invalid parameters: %s" % ",".join(bad_keys))

    if self.cfg.mask and not self.cfg.mode:
      raise DefinitionError("mode can only be set when mask is also defined.")

    if self.cfg.mask:
      if len(self.cfg.mask) > 1:
        raise DefinitionError("Too many mask values defined.")
      if not self._PERM_RE.match(self.cfg.mask[0]):
        raise DefinitionError("mask=%s is not octal, e.g. 0600" % self.cfg.mask)

    if self.cfg.mode:
      if len(self.cfg.mode) > 1:
        raise DefinitionError("Too many mode values defined.")
      if not self._PERM_RE.match(self.cfg.mode[0]):
        raise DefinitionError("mode=%s is not octal, e.g. 0600" % self.cfg.mode)

    if self.cfg.gid:
      for gid in self.cfg.gid:
        matched = self._UID_GID_RE.match(gid)
        if not matched:
          raise DefinitionError("gid: %s is not an integer preceded by "
                                "!, >, < or =." % gid)

    if self.cfg.uid:
      for uid in self.cfg.uid:
        matched = self._UID_GID_RE.match(uid)
        if not matched:
          raise DefinitionError("uid: %s is not an integer preceded by "
                                "!, >, < or =." % uid)

    if self.cfg.file_re:
      if len(self.cfg.file_re) > 1:
        raise DefinitionError("Too many regexes defined: %s" % self.cfg.file_re)
      try:
        self.file_re = re.compile(self.cfg.file_re[0])
      except (re.error, TypeError) as e:
        raise DefinitionError("Invalid file regex: %s" % e)

    if self.cfg.path_re:
      if len(self.cfg.path_re) > 1:
        raise DefinitionError("Too many regexes defined: %s" % self.cfg.path_re)
      try:
        self.path_re = re.compile(self.cfg.path_re[0])
      except (re.error, TypeError) as e:
        raise DefinitionError("Invalid path regex: %s" % e)

    if self.cfg.file_type:
      if len(self.cfg.file_type) > 1:
        raise DefinitionError(
            "Too many file types defined: %s" % self.cfg.file_type)
      file_type = self.cfg.file_type[0].upper()
      if file_type not in self._TYPES:
        raise DefinitionError("Unsupported file type %s" % file_type)

    self._Initialize()
    if not self.matchers:
      raise DefinitionError("StatFilter has no actions: %s" % expression)
    return True

Validates that a parsed rule entry is valid for fschecker.

Args:
expression: A rule expression.

Raises:
DefinitionError: If the filter definition could not be validated.

Returns:
True if the expression validated OK.


def gpio_get(self, pins=None):
    if (pins is None):
        pins = range(4)
    size = len(pins)
    indices = (ctypes.c_uint8 * size)(*pins)
    statuses = (ctypes.c_uint8 * size)()
    result = self._dll.JLINK_EMU_GPIO_GetState(ctypes.byref(indices), ctypes.byref(statuses), size)
    if (result < 0):
        raise errors.JLinkException(result)
    return list(statuses)

Returns a list of states for the given pins.

Defaults to the first four pins if an argument is not given.

Args:
self (JLink): the ``JLink`` instance
pins (list): indices of the GPIO pins whose states are requested

Returns:
A list of states.

Raises:
JLinkException: on error.


def add_primitives_path(path):

    if path not in _PRIMITIVES_PATHS:
        if not os.path.isdir(path):
            raise ValueError('Invalid path: {}'.format(path))

        LOGGER.debug('Adding new primitives path %s', path)
        _PRIMITIVES_PATHS.insert(0, os.path.abspath(path))

Add a new path to look for primitives.

The new path will be inserted in the first place of the list,
so any primitive found in this new folder will take precedence
over any other primitive with the same name that existed in the
system before.

Args:
path (str): path to add

Raises:
ValueError: A `ValueError` will be raised if the path is not valid.


def is45(msg):

    if allzeros(msg):
        return False

    d = hex2bin(data(msg))

    if wrongstatus(d, 1, 2, 3):
        return False

    if wrongstatus(d, 4, 5, 6):
        return False

    if wrongstatus(d, 7, 8, 9):
        return False

    if wrongstatus(d, 10, 11, 12):
        return False

    if wrongstatus(d, 13, 14, 15):
        return False

    if wrongstatus(d, 16, 17, 26):
        return False

    if wrongstatus(d, 27, 28, 38):
        return False

    if wrongstatus(d, 39, 40, 51):
        return False

    if bin2int(d[51:56]) != 0:
        return False

    temp = temp45(msg)
    if temp:
        if temp > 60 or temp < -80:
            return False

    return True

Check if a message is likely to be BDS code 4,5.

Meteorological hazard report

Args:
msg (String): 28 bytes hexadecimal message string

Returns:
bool: True or False


def get_reduced_structure(self, reduction_algo='niggli'):
    if (reduction_algo == 'niggli'):
        reduced_latt = self._lattice.get_niggli_reduced_lattice()
    elif (reduction_algo == 'LLL'):
        reduced_latt = self._lattice.get_lll_reduced_lattice()
    else:
        raise ValueError('Invalid reduction algo : {}'.format(reduction_algo))
    if (reduced_latt != self.lattice):
        return self.__class__(reduced_latt, self.species_and_occu, self.cart_coords, coords_are_cartesian=True, to_unit_cell=True, site_properties=self.site_properties, charge=self._charge)
    else:
        return self.copy()

Get a reduced structure.

Args:
reduction_algo (str): The lattice reduction algorithm to use.
Currently supported options are "niggli" or "LLL".


def trace(src, options=None):
    options = options or config.Options.create()
    with config.verbosity_from(options):
        loader = load_pytd.create_loader(options)
        ret = analyze.infer_types(src=src, options=options, loader=loader)
        pytd_module = ret.ast
        raw_traces = []
        for op, symbol, data in ret.context.vm.opcode_traces:
            raw_traces.append((op, symbol, tuple((_to_pytd(d, loader, pytd_module) for d in data))))
    return source.Code(src, raw_traces, TypeTrace, options.input)

Generates type traces for the given source code.

Args:
src: The source text.
options: A pytype.config.Options object that can be used to specify options
such as the target Python version.

Returns:
A source.Code object.


def get_attr_location(self, name, location):
    line, _ = location
    src_line = self.line(line)
    attr = name.split('.')[-1]
    dot_attr = '.' + attr
    if dot_attr in src_line:
        col = src_line.index(dot_attr)
        return (Location(line, col + 1), len(attr))
    else:
        attr_loc = self._get_multiline_location(location, 5, dot_attr)
        if attr_loc:
            return (Location(attr_loc.line, attr_loc.column + 1), len(attr))
        else:
            for l in self.get_closest_line_range(line, line + 5):
                if self.line(l).endswith('.'):
                    next_line = self.next_non_comment_line(l)
                    text = self.line(next_line)
                    if text.lstrip().startswith(attr):
                        c = text.index(attr)
                        return (Location(next_line, c), len(attr))
        return (location, len(name))

Returns the location and span of the attribute in an attribute access.

Args:
name: The attribute name.
location: The location of the value the attribute is accessed on.


def __init__(self, server_id):

        data = datatools.get_data()

        self.server_id = server_id
        self.logger = logging.getLogger("{}.{}".format(__name__, self.server_id))

        self.songcache_dir = "{}/{}".format(_root_songcache_dir, self.server_id)
        self.songcache_next_dir = "{}/{}/next".format(_root_songcache_dir, self.server_id)
        self.output_format = "{}/{}".format(self.songcache_dir, file_format)
        self.output_format_next = "{}/{}".format(self.songcache_next_dir, file_format)

        self.vchannel = None
        self.vclient = None
        self.streamer = None
        self.current_duration = 0
        self.current_download_elapsed = 0
        self.is_live = False
        self.queue = []
        self.prev_queue = []
        self.prev_queue_max = 500
        self.volume = 20

        self.vclient_starttime = None
        self.vclient_task = None
        self.pause_time = None
        self.prev_time = ""

        self.loop_type = 'off'

        self.mready = False
        self.vready = False
        self.state = 'off'

        self.mchannel = None
        self.embed = None
        self.queue_display = 9
        self.nowplayinglog = logging.getLogger("{}.{}.nowplaying".format(__name__, self.server_id))
        self.nowplayinglog.setLevel("DEBUG")
        self.nowplayingauthorlog = logging.getLogger("{}.{}.nowplayingauthor".format(__name__, self.server_id))
        self.nowplayingauthorlog.setLevel("DEBUG")
        self.nowplayingsourcelog = logging.getLogger("{}.{}.nowplayingsource".format(__name__, self.server_id))
        self.nowplayingsourcelog.setLevel("DEBUG")
        self.timelog = logging.getLogger("{}.{}.time".format(__name__, self.server_id))
        self.timelog.setLevel("DEBUG")
        self.timelog.propagate = False
        self.queuelog = logging.getLogger("{}.{}.queue".format(__name__, self.server_id))
        self.queuelog.setLevel("DEBUG")
        self.queuelog.propagate = False
        self.queuelenlog = logging.getLogger("{}.{}.queuelen".format(__name__, self.server_id))
        self.queuelenlog.setLevel("DEBUG")
        self.queuelenlog.propagate = False
        self.volumelog = logging.getLogger("{}.{}.volume".format(__name__, self.server_id))
        self.volumelog.setLevel("DEBUG")
        self.statuslog = logging.getLogger("{}.{}.status".format(__name__, self.server_id))
        self.statuslog.setLevel("DEBUG")
        self.statustimer = None

        self.clear_cache()

        self.topic = ""
        self.topicchannel = None

        if "topic_id" in data["discord"]["servers"][self.server_id][_data.modulename]:
            topic_id = data["discord"]["servers"][self.server_id][_data.modulename]["topic_id"]
            if topic_id is not None and topic_id != "":
                logger.debug("Topic channel id: {}".format(topic_id))
                self.topicchannel = client.get_channel(topic_id)

        if "volume" in data["discord"]["servers"][self.server_id][_data.modulename]:
            self.volume = data["discord"]["servers"][self.server_id][_data.modulename]["volume"]
        else:
            self.write_volume()

Locks onto a server for easy management of various UIs

Args:
server_id (str): The Discord ID of the server to lock on to


def flip_channel_order(self, image):
    self._ensure_format_supported(image)
    if isinstance(image, PIL.Image.Image):
        image = self.to_numpy_array(image)
    return image[::-1, :, :]

Flips the channel order of `image` from RGB to BGR, or vice versa. Note that this will trigger a conversion of
`image` to a NumPy array if it's a PIL Image.

Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel dimension should
be first.


def get_random_value(length=10, character_sets=[string.ascii_uppercase, string.ascii_lowercase]):
    return ''.join((random.choice(''.join(character_sets)) for i in range(length)))

Get a random string with the given length.

Args:
length (int): The length of the string to return.
character_sets list(str): The caracter sets to use.

Returns:
str: The random string.


def _DownloadAuthUrl(self, url, dest_dir):

    dest_file = tempfile.NamedTemporaryFile(dir=dest_dir, delete=False)
    dest_file.close()
    dest = dest_file.name

    self.logger.info(
        'Downloading url from %s to %s using authentication token.', url, dest)

    if not self.token:
      response = self.watcher.GetMetadata(
          self.token_metadata_key, recursive=False, retry=False)

      if not response:
        self.logger.info(
            'Authentication token not found. Attempting unauthenticated '
            'download.')
        return self._DownloadUrl(url, dest_dir)

      self.token = '%s %s' % (
          response.get('token_type', ''), response.get('access_token', ''))

    try:
      request = urlrequest.Request(url)
      request.add_unredirected_header('Metadata-Flavor', 'Google')
      request.add_unredirected_header('Authorization', self.token)
      content = urlrequest.urlopen(request).read().decode('utf-8')
    except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
      self.logger.warning('Could not download %s. %s.', url, str(e))
      return None

    with open(dest, 'wb') as f:
      f.write(content)

    return dest

Download a Google Storage URL using an authentication token.

If the token cannot be fetched, fallback to unauthenticated download.

Args:
url: string, the URL to download.
dest_dir: string, the path to a directory for storing metadata scripts.

Returns:
string, the path to the file storing the metadata script.


def uses_star_args_in_call(node):
    if sys.version_info[:2] >= (3, 5):
        for arg in node.args:
            if isinstance(arg, ast.Starred):
                return True
    elif node.starargs:
        return True
    return False

Check if an ast.Call node uses arbitrary-length positional *args.

This function works with the AST call node format of Python3.5+
as well as the different AST format of earlier versions of Python.

Args:
node: The ast.Call node to check arg values for.

Returns:
True if the node uses starred variadic positional args or keyword args.
False if it does not.


def sign(self, byts):
    chosen_hash = c_hashes.SHA256()
    hasher = c_hashes.Hash(chosen_hash, default_backend())
    hasher.update(byts)
    digest = hasher.finalize()
    return self.priv.sign(digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash)))

Compute the ECC signature for the given bytestream.

Args:
byts (bytes): The bytes to sign.

Returns:
bytes: The RSA Signature bytes.


def load_metrics(event_dir, epoch):
    metrics = {}
    for filename in tf.gfile.ListDirectory(event_dir):
        path = os.path.join(event_dir, filename)
        for event in tf.train.summary_iterator(path):
            if ((event.step == epoch) and event.HasField('summary')):
                value = event.summary.value[0]
                metrics[value.tag] = value.simple_value
    return metrics

Loads metrics for this epoch if they have already been written.

This reads the entire event file but it's small with just per-epoch metrics.

Args:
event_dir: TODO(koz4k): Document this.
epoch: TODO(koz4k): Document this.

Returns:
metrics.


def RegisterMessage(self, message):

    desc = message.DESCRIPTOR
    self._classes[desc.full_name] = message
    self.pool.AddDescriptor(desc)
    return message

Registers the given message type in the local database.

Calls to GetSymbol() and GetMessages() will return messages registered here.

Args:
message: a message.Message, to be registered.

Returns:
The provided message.


def GetSectionByIndex(self, section_index):

    if not self._is_parsed:
      self._Parse()
      self._is_parsed = True

    if section_index < 0 or section_index >= len(self._sections):
      return None

    return self._sections[section_index]

Retrieves a specific section based on the index.

Args:
section_index (int): index of the section.

Returns:
VolumeExtent: a volume extent or None if not available.


def run_commands(self, commands, encoding='json', send_enable=True, **kwargs):
    commands = make_iterable(commands)
    commands = [({'cmd': c.split('MULTILINE:')[0], 'input': ('%s\n' % c.split('MULTILINE:')[1].strip())} if ('MULTILINE:' in c) else c) for c in commands]
    if send_enable:
        if self._enablepwd:
            commands.insert(0, {'cmd': 'enable', 'input': self._enablepwd})
        else:
            commands.insert(0, 'enable')
    response = self._connection.execute(commands, encoding, **kwargs)
    if send_enable:
        response['result'].pop(0)
    return response['result']

Sends the commands over the transport to the device

This method sends the commands to the device using the nodes
transport.  This is a lower layer function that shouldn't normally
need to be used, preferring instead to use config() or enable().

Args:
commands (list): The ordered list of commands to send to the
device using the transport
encoding (str): The encoding method to use for the request and
excpected response.
send_enable (bool): If True the enable command will be
prepended to the command list automatically.
**kwargs: Additional keyword arguments for expanded eAPI
functionality. Only supported eAPI params are used in building
the request

Returns:
This method will return the raw response from the connection
which is a Python dictionary object.


def parse(self, filepath, content):

        try:
            parsed = yaml.load(content)
        except yaml.YAMLError as exc:
            msg = "No YAML object could be decoded from file: {}\n{}"
            raise SettingsBackendError(msg.format(filepath, exc))
        return parsed

Parse opened settings content using YAML parser.

Args:
filepath (str): Settings object, depends from backend
content (str): Settings content from opened file, depends from
backend.

Raises:
boussole.exceptions.SettingsBackendError: If parser can not decode
a valid YAML object.

Returns:
dict: Dictionnary containing parsed setting elements.


def __get_state_by_id(cls, job_id):

    state = model.MapreduceState.get_by_job_id(job_id)
    if state is None:
      raise ValueError("Job state for job %s is missing." % job_id)
    return state

Get job state by id.

Args:
job_id: job id.

Returns:
model.MapreduceState for the job.

Raises:
ValueError: if the job state is missing.


def _print_test_names(test_classes):
    for test_class in test_classes:
        cls = test_class(config_parser.TestRunConfig())
        test_names = []
        try:
            cls._pre_run()
            if cls.tests:
                test_names = list(cls.tests)
            else:
                test_names = cls.get_existing_test_names()
        except Exception:
            logging.exception('Failed to retrieve generated tests.')
        finally:
            cls._clean_up()
        print('==========> %s <==========' % cls.TAG)
        for name in test_names:
            print(f'{cls.TAG}.{name}')

Prints the names of all the tests in all test classes.
Args:
test_classes: classes, the test classes to print names from.


def _get_prop_from_modelclass(modelclass, name):

  if name == '__key__':
    return modelclass._key

  parts = name.split('.')
  part, more = parts[0], parts[1:]
  prop = modelclass._properties.get(part)
  if prop is None:
    if issubclass(modelclass, model.Expando):
      prop = model.GenericProperty(part)
    else:
      raise TypeError('Model %s has no property named %r' %
                      (modelclass._get_kind(), part))

  while more:
    part = more.pop(0)
    if not isinstance(prop, model.StructuredProperty):
      raise TypeError('Model %s has no property named %r' %
                      (modelclass._get_kind(), part))
    maybe = getattr(prop, part, None)
    if isinstance(maybe, model.Property) and maybe._name == part:
      prop = maybe
    else:
      maybe = prop._modelclass._properties.get(part)
      if maybe is not None:

        prop = getattr(prop, maybe._code_name)
      else:
        if issubclass(prop._modelclass, model.Expando) and not more:
          prop = model.GenericProperty()
          prop._name = name
        else:
          raise KeyError('Model %s has no property named %r' %
                         (prop._modelclass._get_kind(), part))

  return prop

Helper for FQL parsing to turn a property name into a property object.

Args:
modelclass: The model class specified in the query.
name: The property name.  This may contain dots which indicate
sub-properties of structured properties.

Returns:
A Property object.

Raises:
KeyError if the property doesn't exist and the model clas doesn't
derive from Expando.


def run_idle(self):
    if ((not self.idlers) or (self.inactive >= len(self.idlers))):
        return False
    idler = self.idlers.popleft()
    (callback, args, kwds) = idler
    _logging_debug('idler: %s', callback.__name__)
    res = callback(*args, **kwds)
    if (res is not None):
        if res:
            self.inactive = 0
        else:
            self.inactive += 1
        self.idlers.append(idler)
    else:
        _logging_debug('idler %s removed', callback.__name__)
    return True

Run one of the idle callbacks.

Returns:
True if one was called, False if no idle callback was called.


def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False):
    if message_name:
        full_name = '.'.join((message_name, field_proto.name))
    else:
        full_name = field_proto.name
    return descriptor.FieldDescriptor(name=field_proto.name, full_name=full_name, index=index, number=field_proto.number, type=field_proto.type, cpp_type=None, message_type=None, enum_type=None, containing_type=None, label=field_proto.label, has_default_value=False, default_value=None, is_extension=is_extension, extension_scope=None, options=field_proto.options)

Creates a field descriptor from a FieldDescriptorProto.

For message and enum type fields, this method will do a look up
in the pool for the appropriate descriptor for that type. If it
is unavailable, it will fall back to the _source function to
create it. If this type is still unavailable, construction will
fail.

Args:
field_proto: The proto describing the field.
message_name: The name of the containing message.
index: Index of the field
is_extension: Indication that this field is for an extension.

Returns:
An initialized FieldDescriptor object


def __init__(self, qobj_model, **run_config):

        self._qobj_model = qobj_model
        self._run_config = run_config

Create new converter.

Args:
qobj_model (QobjInstruction): marshmallow model to serialize to object.
run_config (dict): experimental configuration.


def __init__(self, column_names=None, title=None):

    super(CLITableView, self).__init__(column_names=column_names, title=title)
    if self._columns:
      self._column_width = len(self._columns[0])
    else:
      self._column_width = 0

Initializes a command line table view.

Args:
column_names (Optional[list[str]]): column names.
title (Optional[str]): title.


def xldate_as_datetime(xldate, datemode=0, option="to_datetime"):

    if option == "to_float":
        d = (xldate - 25589) * 86400.0
    else:
        try:
            d = datetime.datetime(1899, 12, 30) + \
                datetime.timedelta(days=xldate + 1462 * datemode)

            if option == "to_string":
                date_format = "%Y-%m-%d %H:%M:%S"
                d = d.strftime(date_format)
        except TypeError:
            logging.info(f'The date is not of correct type [{xldate}]')
            d = xldate
    return d

Converts a xls date stamp to a more sensible format.

Args:
xldate (str): date stamp in Excel format.
datemode (int): 0 for 1900-based, 1 for 1904-based.
option (str): option in ("to_datetime", "to_float", "to_string"),
return value

Returns:
datetime (datetime object, float, or string).


def table_chains(self, table='filter'):
    return dict(((c['name'], self.get_chain(c['name'], table)) for c in self.get_table(table)))

Get a dict where the keys are all the chains for the given table
and each value is the set of rules defined for the given chain.

Args:
table (str): table name, defaults to ``filter``

Returns:
dict: chains with set of defined rules


def cutting_indices(self, independent_decision_points: List[pg.geno.DecisionPoint], global_state: pg.geno.AttributeDict, step: int) -> List[int]:

Implementation of getting the indices of the cutting points.

Args:
independent_decision_points: A list of independent decision points.
global_state: An optional keyword argument as the global state. Subclass
can omit.
step: An optional keyword argument as the curent step. Subclass can omit.

Returns:
A list of integers as the cutting points.


def scroll(clicks, x=None, y=None, pause=None, _pause=True):
    _failSafeCheck()
    if (type(x) in (tuple, list)):
        (x, y) = (x[0], x[1])
    (x, y) = position(x, y)
    platformModule._scroll(clicks, x, y)
    _autoPause(pause, _pause)

Performs a scroll of the mouse scroll wheel.

Whether this is a vertical or horizontal scroll depends on the underlying
operating system.

The x and y parameters detail where the mouse event happens. If None, the
current mouse position is used. If a float value, it is rounded down. If
outside the boundaries of the screen, the event happens at edge of the
screen.

Args:
clicks (int, float): The amount of scrolling to perform.
x (int, float, None, tuple, optional): The x position on the screen where the
click happens. None by default. If tuple, this is used for x and y.
y (int, float, None, optional): The y position on the screen where the
click happens. None by default.

Returns:
None


def sample(self, bqm, num_reads=10):

        values = tuple(bqm.vartype.value)

        def _itersample():
            for __ in range(num_reads):
                sample = {v: choice(values) for v in bqm.linear}
                energy = bqm.energy(sample)

                yield sample, energy

        samples, energies = zip(*_itersample())

        return SampleSet.from_samples(samples, bqm.vartype, energies)

Give random samples for a binary quadratic model.

Variable assignments are chosen by coin flip.

Args:
bqm (:obj:`.BinaryQuadraticModel`):
Binary quadratic model to be sampled from.

num_reads (int, optional, default=10):
Number of reads.

Returns:
:obj:`.SampleSet`


def get_property_dict(entity_proto):
    return dict(((p.key, p.value) for p in entity_proto.property))

Convert datastore.Entity to a dict of property name -> datastore.Value.

Args:
entity_proto: datastore.Entity proto message.

Usage:
>>> get_property_dict(entity_proto)
{'foo': {string_value='a'}, 'bar': {integer_value=2}}

Returns:
dict of entity properties.


def _read_mptcp_join(self, bits, size, kind):
    if (self._syn and self._ack):
        return self._read_join_synack(bits, size, kind)
    elif self._syn:
        return self._read_join_syn(bits, size, kind)
    elif self._ack:
        return self._read_join_ack(bits, size, kind)
    else:
        temp = self._read_fileng(size)
        data = dict(kind=kind, length=(size + 1), subtype='MP_JOIN-Unknown', data=(bytes(chr(int(bits[:4], base=2)), encoding='utf-8') + temp))
        return data

Read Join Connection option.

Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)

Returns:
* dict -- extracted Join Connection (MP_JOIN) option

Structure of MP_JOIN [RFC 6824]:
Octets      Bits        Name                        Description
0           0     tcp.mp.kind                 Kind (30)
1           8     tcp.mp.length               Length
2          16     tcp.mp.subtype              Subtype (1)
2          20     tcp.mp.data                 Handshake-specific Data


def op_nodes(self, op=None):

        nodes = []
        for node in self._multi_graph.nodes():
            if node.type == "op":
                if op is None or isinstance(node.op, op):
                    nodes.append(node)
        return nodes

Get the list of "op" nodes in the dag.

Args:
op (Type): Instruction subclass op nodes to return. if op=None, return
all op nodes.
Returns:
list[DAGNode]: the list of node ids containing the given op.


def get_plugin_asset(plugin_asset_cls, graph=None):
    if graph is None:
        graph = ops.get_default_graph()
    if not plugin_asset_cls.plugin_name:
        raise ValueError('Class %s has no plugin_name' % plugin_asset_cls.__name__)
    name = _PLUGIN_ASSET_PREFIX + plugin_asset_cls.plugin_name
    container = graph.get_collection(name)
    if container:
        if len(container) != 1:
            raise ValueError('Collection for %s had %d items, expected 1' % (name, len(container)))
        instance = container[0]
        if not isinstance(instance, plugin_asset_cls):
            raise ValueError('Plugin name collision between classes %s and %s' % (plugin_asset_cls.__name__, instance.__class__.__name__))
    else:
        instance = plugin_asset_cls()
        graph.add_to_collection(name, instance)
        graph.add_to_collection(_PLUGIN_ASSET_PREFIX, plugin_asset_cls.plugin_name)
    return instance

Acquire singleton PluginAsset instance from a graph.

PluginAssets are always singletons, and are stored in tf Graph collections.
This way, they can be defined anywhere the graph is being constructed, and
if the same plugin is configured at many different points, the user can always
modify the same instance.

Args:
plugin_asset_cls: The PluginAsset class
graph: (optional) The graph to retrieve the instance from. If not specified,
the default graph is used.

Returns:
An instance of the plugin_asset_class

Raises:
ValueError: If we have a plugin name collision, or if we unexpectedly find
the wrong number of items in a collection.


def __init__(self, loss_scale_value):
    super(FixedLossScale, self).__init__()
    if not isinstance(loss_scale_value, (int, float)):
        raise ValueError('loss_scale_value must be a Python int or float.')
    if loss_scale_value < 1:
        raise ValueError('loss_scale_value must be at least 1.')
    self._loss_scale_value = float(loss_scale_value)

Creates the fixed loss scale.

Args:
loss_scale_value: A Python float. Its ideal value varies depending on
models to run. Choosing a too small loss_scale might affect model
quality; a too big loss_scale might cause inf or nan. There is no single
right loss_scale to apply. There is no harm choosing a relatively big
number as long as no nan or inf is encountered in training.

Raises:
ValueError: If loss_scale_value is less than 1.


def _print_download_progress_msg(self, msg, flush=False):
    if self._interactive_mode():
        self._max_prog_str = max(self._max_prog_str, len(msg))
        sys.stdout.write(('\r%-{}s'.format(self._max_prog_str) % msg))
        sys.stdout.flush()
        if flush:
            print('\n')
    else:
        logging.info(msg)

Prints a message about download progress either to the console or TF log.

Args:
msg: Message to print.
flush: Indicates whether to flush the output (only used in interactive
mode).


def _address_content(self, x):

    mem_keys = tf.layers.dense(self.mem_vals, self.key_depth,
                               bias_initializer=tf.constant_initializer(1.0),
                               name="mem_key")
    mem_query = tf.layers.dense(x, self.key_depth,
                                bias_initializer=tf.constant_initializer(1.0),
                                name="mem_query")
    norm = tf.matmul(self._norm(mem_query), self._norm(mem_keys),
                     transpose_b=True)
    dot_product = tf.matmul(mem_query, mem_keys, transpose_b=True)
    cos_dist = tf.div(dot_product, norm + 1e-7, name="cos_dist")
    access_logits = self.sharpen_factor * cos_dist
    return access_logits

Address the memory based on content similarity.

Args:
x: a tensor in the shape of [batch_size, length, depth].
Returns:
the logits for each memory entry [batch_size, length, memory_size].


def register_user(self, user):

        self.users[user.index] = {'known_items': set()}
        self.n_user += 1

For new users, append their information into the dictionaries.

Args:
user (User): User.


def write_fasta_file_from_dict(indict, outname, outdir=None, outext='.faa', force_rerun=False):
    if (not outdir):
        outdir = ''
    outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext)
    if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile):
        seqs = []
        for (i, s) in indict.items():
            seq = ssbio.protein.sequence.utils.cast_to_seq_record(s, id=i)
            seqs.append(seq)
        SeqIO.write(seqs, outfile, 'fasta')
    return outfile

Write a FASTA file for a dictionary of IDs and their sequence strings.

Args:
indict: Input dictionary with keys as IDs and values as sequence strings
outname: Name of the output file which will have outext appended to it
outdir: Path to directory to output sequences to
outext: Extension of FASTA file, default ".faa"
force_rerun: If file should be overwritten if it exists

Returns:
str: Path to output FASTA file.


def Push(cls, connection, datafile, filename,
             st_mode=DEFAULT_PUSH_MODE, mtime=0, progress_callback=None):

        fileinfo = ('{},{}'.format(filename, int(st_mode))).encode('utf-8')

        cnxn = FileSyncConnection(connection, b'<2I')
        cnxn.Send(b'SEND', fileinfo)

        if progress_callback:
            total_bytes = os.fstat(datafile.fileno()).st_size if isinstance(datafile, file) else -1
            progress = cls._HandleProgress(lambda current: progress_callback(filename, current, total_bytes))
            next(progress)

        while True:
            data = datafile.read(MAX_PUSH_DATA)
            if data:
                cnxn.Send(b'DATA', data)

                if progress_callback:
                    progress.send(len(data))
            else:
                break

        if mtime == 0:
            mtime = int(time.time())

        cnxn.Send(b'DONE', size=mtime)
        for cmd_id, _, data in cnxn.ReadUntil((), b'OKAY', b'FAIL'):
            if cmd_id == b'OKAY':
                return
            raise PushFailedError(data)

Push a file-like object to the device.

Args:
connection: ADB connection
datafile: File-like object for reading from
filename: Filename to push to
st_mode: stat mode for filename
mtime: modification time
progress_callback: callback method that accepts filename, bytes_written and total_bytes

Raises:
PushFailedError: Raised on push failure.


def _tuple_of_big_endian_int(bit_groups: Tuple[(np.ndarray, ...)]) -> Tuple[(int, ...)]:
    return tuple((_big_endian_int(bits) for bits in bit_groups))

Returns the big-endian integers specified by groups of bits.

Args:
bit_groups: Groups of descending bits, each specifying a big endian
integer with the 1s bit at the end.

Returns:
A tuple containing the integer for each group.


def register_for_auto_class(cls, auto_class='AutoProcessor'):
    if not isinstance(auto_class, str):
        auto_class = auto_class.__name__
    import transformers.models.auto as auto_module
    if not hasattr(auto_module, auto_class):
        raise ValueError(f'{auto_class} is not a valid auto class.')
    cls._auto_class = auto_class

Register this class with a given auto class. This should only be used for custom feature extractors as the ones
in the library are already mapped with `AutoProcessor`.

Args:
auto_class (`str` or `type`, *optional*, defaults to `"AutoProcessor"`):
The auto class to register this new feature extractor with.


def exe_cmd(*cmds, timeout=DEFAULT_TIMEOUT_SEC):
    cmd = ' '.join(cmds)
    ret, out, err = utils.run_command(cmd=cmd, stdout=PIPE, stderr=PIPE, shell=True, timeout=timeout)
    logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', utils.cli_cmd_to_string(cmds), out, err, ret)
    if not err:
        return out
    return err

Executes commands in a new shell. Directing stderr to PIPE, with timeout.

This is fastboot's own exe_cmd because of its peculiar way of writing
non-error info to stderr.

Args:
cmds: A sequence of commands and arguments.
timeout: The number of seconds to wait before timing out.

Returns:
The output of the command run, in bytes.

Raises:
Exception: An error occurred during the command execution or
the command timed out.


def is_distributing_by_cloning(model):
    if backend.is_tpu_strategy(model._distribution_strategy) and context.executing_eagerly:
        return False
    elif ops.executing_eagerly_outside_functions():
        return bool(model._compile_distribution)
    return True

Decide whether this model is going to be distributed via cloning.

We are going to distribute the model by cloning in graph mode.

Args:
model: Keras model to distribute.

Returns:
True if the `model` is going to be distributed using cloning and False
otherwise.


def has_chosen(state, correct, msgs):
    ctxt = {}
    exec(state.student_code, globals(), ctxt)
    sel_indx = ctxt['selected_option']
    if (sel_indx != correct):
        state.report(Feedback(msgs[(sel_indx - 1)]))
    else:
        state.reporter.success_msg = msgs[(correct - 1)]
    return state

Verify exercises of the type MultipleChoiceExercise

Args:
state:    State instance describing student and solution code. Can be omitted if used with Ex().
correct:  index of correct option, where 1 is the first option.
msgs  :    list of feedback messages corresponding to each option.

:Example:
The following SCT is for a multiple choice exercise with 2 options, the first
of which is correct.::

Ex().has_chosen(1, ['Correct!', 'Incorrect. Try again!'])