def get_template_list(self, page=1, page_size=None, account_id=None, query=None):
    request = self._get_request()
    parameters = {'page': page, 'page_size': page_size, 'account_id': account_id, 'query': query}
    return request.get(self.TEMPLATE_GET_LIST_URL, parameters=parameters)

Lists your Templates

Args:

page (int, optional):           Page number of the template List to return. Defaults to 1.
page_size (int, optional):      Number of objects to be returned per page, must be between 1 and 100, default is 20.
account_id (str, optional):     Which account to return Templates for. Must be a team member. Use "all" to indicate all team members. Defaults to your account.
query (str, optional):          String that includes search terms and/or fields to be used to filter the Template objects.

Returns:
A ResourceList object


def save(self, file_prefix: str, options: Optional[checkpoint_options.CheckpointOptions]=None) -> Optional[ops.Operation]:
    if options is not None and options.experimental_io_device is not None:
        raise ValueError('Specified experimental_io_device in DTensor checkpoint is not supported.')
    del options
    tensor_names = []
    tensors = []
    tensor_slices = []
    for saveable in self._saveable_objects:
        for spec in saveable.specs:
            tensor = spec.tensor
            if tensor is not None:
                if api.device_name() != spec.device:
                    tensor = api.pack([tensor] * self._mesh.host_mesh().num_local_devices(), layout.Layout.replicated(self._mesh.host_mesh(), rank=tensor.shape.rank))
                tensor_names.append(spec.name)
                tensors.append(tensor)
                tensor_slices.append(spec.slice_spec)
    return save_restore.sharded_save(self._mesh, file_prefix, tensor_names, tensor_slices, tensors)

Saves the saveable objects to a checkpoint with `file_prefix`.

Also query the generated shards from the distributed DTensor SaveV2 ops and
do a MergeV2 on those. Each op here is backed by a global_barrier to avoid
racing from multiple clients.

Args:
file_prefix: A string or scalar string Tensor containing the prefix to
save under.
options: Optional `CheckpointOptions` object. This is unused in DTensor.

Returns:
An `Operation`, or None when executing eagerly.


def flowwrite(flow, filename, quantize=False, concat_axis=0, *args, **kwargs):
    if (not quantize):
        with open(filename, 'wb') as f:
            f.write('PIEH'.encode('utf-8'))
            np.array([flow.shape[1], flow.shape[0]], dtype=np.int32).tofile(f)
            flow = flow.astype(np.float32)
            flow.tofile(f)
            f.flush()
    else:
        assert (concat_axis in [0, 1])
        (dx, dy) = quantize_flow(flow, *args, **kwargs)
        dxdy = np.concatenate((dx, dy), axis=concat_axis)
        imwrite(dxdy, filename)

Write optical flow to file.

If the flow is not quantized, it will be saved as a .flo file losslessly,
otherwise a jpeg image which is lossy but of much smaller size. (dx and dy
will be concatenated horizontally into a single image if quantize is True.)

Args:
flow (ndarray): (h, w, 2) array of optical flow.
filename (str): Output filepath.
quantize (bool): Whether to quantize the flow and save it to 2 jpeg
images. If set to True, remaining args will be passed to
:func:`quantize_flow`.
concat_axis (int): The axis that dx and dy are concatenated,
can be either 0 or 1. Ignored if quantize is False.


def apply_mutation(module_path, operator, occurrence):
    module_ast = get_ast(module_path, python_version=operator.python_version)
    original_code = module_ast.get_code()
    visitor = MutationVisitor(occurrence, operator)
    mutated_ast = visitor.walk(module_ast)
    mutated_code = None
    if visitor.mutation_applied:
        mutated_code = mutated_ast.get_code()
        with module_path.open(mode='wt', encoding='utf-8') as handle:
            handle.write(mutated_code)
            handle.flush()
    return (original_code, mutated_code)

Apply a specific mutation to a file on disk.

Args:
module_path: The path to the module to mutate.
operator: The `operator` instance to use.
occurrence: The occurrence of the operator to apply.

Returns: A `(unmutated-code, mutated-code)` tuple to the with-block. If there was
no mutation performed, the `mutated-code` is `None`.


def get_estimator(output_dir, train_config, args):

  target_name = train_config['target_column']
  if is_classification_model(args.model_type) and target_name not in \
          train_config['categorical_columns']:
    raise ValueError('When using a classification model, the target must be a '
                     'categorical variable.')
  if is_regression_model(args.model_type) and target_name not in \
          train_config['numerical_columns']:
    raise ValueError('When using a regression model, the target must be a '
                     'numerical variable.')

  if is_dnn_model(args.model_type) and not args.layer_sizes:
    raise ValueError('--layer-size* must be used with DNN models')
  if is_linear_model(args.model_type) and args.layer_sizes:
    raise ValueError('--layer-size* cannot be used with linear models')

  feature_columns = _tflearn_features(train_config, args)

  config = tf.contrib.learn.RunConfig(
      save_checkpoints_secs=args.save_checkpoints_secs)

  train_dir = os.path.join(output_dir, 'train')
  if args.model_type == 'dnn_regression':
    estimator = tf.contrib.learn.DNNRegressor(
        feature_columns=feature_columns,
        hidden_units=args.layer_sizes,
        config=config,
        model_dir=train_dir,
        optimizer=tf.train.AdamOptimizer(
            args.learning_rate, epsilon=args.epsilon))
  elif args.model_type == 'linear_regression':
    estimator = tf.contrib.learn.LinearRegressor(
        feature_columns=feature_columns,
        config=config,
        model_dir=train_dir,
        optimizer=tf.train.AdamOptimizer(
            args.learning_rate, epsilon=args.epsilon))
  elif args.model_type == 'dnn_classification':
    estimator = tf.contrib.learn.DNNClassifier(
        feature_columns=feature_columns,
        hidden_units=args.layer_sizes,
        n_classes=train_config['vocab_stats'][target_name]['n_classes'],
        config=config,
        model_dir=train_dir,
        optimizer=tf.train.AdamOptimizer(
            args.learning_rate, epsilon=args.epsilon))
  elif args.model_type == 'linear_classification':
    estimator = tf.contrib.learn.LinearClassifier(
        feature_columns=feature_columns,
        n_classes=train_config['vocab_stats'][target_name]['n_classes'],
        config=config,
        model_dir=train_dir,
        optimizer=tf.train.AdamOptimizer(
            args.learning_rate, epsilon=args.epsilon))
  else:
    raise ValueError('bad --model-type value')

  return estimator

Returns a tf learn estimator.

We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is
controlled by the values of model_type in the args.

Args:
output_dir: Modes are saved into outputdir/train
train_config: our training config
args: command line parameters

Returns:
TF lean estimator

Raises:
ValueError: if config is wrong.


def _ragged_tensor_to_string(string_tensor, summarize):
    if string_tensor.shape.rank == 1:
        pieces = string_tensor
    else:
        pieces = map_fn_lib.map_fn(lambda s: _ragged_tensor_to_string(s, summarize), string_tensor, fn_output_signature=tensor_lib.TensorSpec(None, dtypes.string))
    if summarize not in (-1, None):
        pieces = cond.cond(_nrows(string_tensor) <= 2 * summarize, lambda: pieces, lambda: array_ops.concat([pieces[:summarize], ['...'], pieces[-summarize:]], axis=0))
    return '[' + string_ops.reduce_join(pieces, separator=', ') + ']'

Returns a scalar string tensor with the contents of `string_tensor`.

Args:
string_tensor: A potentially ragged tensor with dtype=string.
summarize: Include only the first and last `summarize` elements of each
dimension.  If `-1` or `None`, then include all elements.

Returns:
A scalar string Tensor.


def dump(ofp, *pb_objs, **kwargs):

    mode = 'wb'
    if isinstance(ofp, str):
        ostream = open(ofp, mode=mode, **kwargs)
    else:
        ostream = open(fileobj=ofp, mode=mode, **kwargs)
    with ostream:
        ostream.write(*pb_objs)

Write to a stream.

Args:
ofp (string or file-like object): output stream.
pb_objs (*protobuf.message.Message): list of protobuf message objects
to be written.


def collective_diffusion_coefficient( self ):

        if self.has_run:
            return self.atoms.collective_dr_squared() / ( 6.0 * self.lattice.time )
        else:
            return None

Returns the collective or "jump" diffusion coefficient, D_J.

Args:
None

Returns:
(Float): The collective diffusion coefficient, D_J.


def aggregate(self, batch_outs, batch_start=None, batch_end=None):
    raise NotImplementedError('Must be implemented in subclasses.')

Aggregates batch-level results into total results.

Args:
batch_outs: A list of batch-level outputs.
batch_start: The start index of this batch. Always `None` if `use_steps`
is `True`.
batch_end: The end index of this batch. Always `None` if `use_steps` is
`True`.


def __init__(self, dimensions, hidden_size):

    super(LearnableMultivariateNormalDiagCell, self).__init__()
    self.dimensions = dimensions
    self.hidden_size = hidden_size
    self.lstm_cell = tf.keras.layers.LSTMCell(hidden_size)
    self.output_layer = tf.keras.layers.Dense(2*dimensions)

Constructs a learnable multivariate diagonal normal cell.

Args:
dimensions: An integer corresponding to the dimensionality of the
distribution.
hidden_size: Dimensionality of the LSTM function parameters.


def convert_transpose(params, w_name, scope_name, inputs, layers, weights, names):

    print('Converting transpose ...')
    if params['perm'][0] != 0:
        if inputs[0] in layers:
            print('!!! Cannot permute batch dimension. Result may be wrong !!!')
            layers[scope_name] = layers[inputs[0]]
        else:
            print('Skip weight matrix transpose, result may be wrong.')
    else:
        if names:
            tf_name = 'PERM' + random_string(4)
        else:
            tf_name = w_name + str(random.random())
        permute = keras.layers.Permute(params['perm'][1:], name=tf_name)
        layers[scope_name] = permute(layers[inputs[0]])

Convert transpose layer.

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


def pp_hex(raw, reverse=True):

    if not reverse:
        return ''.join(['{:02x}'.format(v) for v in bytearray(raw)])
    return ''.join(reversed(['{:02x}'.format(v) for v in bytearray(raw)]))

Return a pretty-printed (hex style) version of a binary string.

Args:
raw (bytes): any sequence of bytes
reverse (bool): True if output should be in reverse order.

Returns:
Hex string corresponding to input byte sequence.


def _FormatReturnOrExitToken(self, token_data):
    error_string = bsmtoken.BSM_ERRORS.get(token_data.status, 'UNKNOWN')
    return {'error': error_string, 'token_status': token_data.status, 'call_status': token_data.return_value}

Formats a return or exit token as a dictionary of values.

Args:
token_data (bsm_token_data_exit|bsm_token_data_return32|
bsm_token_data_return64): AUT_EXIT, AUT_RETURN32 or
AUT_RETURN64 token data.

Returns:
dict[str, str]: token values.


def _extract_params(self, kwargs, hyperparameters):
    init_params = dict()
    fit_params = dict()
    produce_params = dict()
    for (name, param) in hyperparameters.get('fixed', dict()).items():
        if (name in kwargs):
            value = kwargs.pop(name)
        elif ('default' in param):
            value = param['default']
        else:
            raise TypeError("{} required argument '{}' not found".format(self.name, name))
        init_params[name] = value
    for (name, param) in hyperparameters.get('tunable', dict()).items():
        if (name in kwargs):
            init_params[name] = kwargs.pop(name)
    fit_args = [arg['name'] for arg in self.fit_args]
    produce_args = [arg['name'] for arg in self.produce_args]
    for name in list(kwargs.keys()):
        if (name in fit_args):
            fit_params[name] = kwargs.pop(name)
        elif (name in produce_args):
            produce_params[name] = kwargs.pop(name)
    if kwargs:
        error = "Unexpected hyperparameters '{}'".format(', '.join(kwargs.keys()))
        raise TypeError(error)
    return (init_params, fit_params, produce_params)

Extract init, fit and produce params from kwargs.

The `init_params`, `fit_params` and `produce_params` are extracted
from the passed `kwargs` taking the metadata hyperparameters as a
reference.

During this extraction, make sure that all the required hyperparameters
have been given and that nothing unexpected exists in the input.

Args:
kwargs (dict): dict containing the Keyword arguments that have
been passed to the `__init__` method upon
initialization.
hyperparameters (dict): hyperparameters dictionary, as found in
the JSON annotation.

Raises:
TypeError: A `TypeError` is raised if a required argument is not
found in the `kwargs` dict, or if an unexpected
argument has been given.


def tagscleanupdicts(configuration=None, url=None, keycolumn=5, failchained=True):
    if (not Tags._tags_dict):
        if (configuration is None):
            configuration = Configuration.read()
        with Download(full_agent=configuration.get_user_agent()) as downloader:
            if (url is None):
                url = configuration['tags_cleanup_url']
            Tags._tags_dict = downloader.download_tabular_rows_as_dicts(url, keycolumn=keycolumn)
            keys = Tags._tags_dict.keys()
            chainerror = False
            for (i, tag) in enumerate(keys):
                whattodo = Tags._tags_dict[tag]
                action = whattodo[u'action']
                final_tags = whattodo[u'final tags (semicolon separated)']
                for final_tag in final_tags.split(';'):
                    if (final_tag in keys):
                        index = list(keys).index(final_tag)
                        if (index != i):
                            whattodo2 = Tags._tags_dict[final_tag]
                            action2 = whattodo2[u'action']
                            if ((action2 != 'OK') and (action2 != 'Other')):
                                final_tags2 = whattodo2[u'final tags (semicolon separated)']
                                if (final_tag not in final_tags2.split(';')):
                                    chainerror = True
                                    if failchained:
                                        logger.error(('Chained rules: %s (%s -> %s) | %s (%s -> %s)' % (action, tag, final_tags, action2, final_tag, final_tags2)))
            if (failchained and chainerror):
                raise ChainRuleError('Chained rules for tags detected!')
            Tags._wildcard_tags = list()
            for tag in Tags._tags_dict:
                if ('*' in tag):
                    Tags._wildcard_tags.append(tag)
    return (Tags._tags_dict, Tags._wildcard_tags)

Get tags cleanup dictionaries

Args:
configuration (Optional[Configuration]): HDX configuration. Defaults to global configuration.
url (Optional[str]): Url of tags cleanup spreadsheet. Defaults to None (internal configuration parameter).
keycolumn (int): Column number of tag column in spreadsheet. Defaults to 5.
failchained (bool): Fail if chained rules found. Defaults to True.

Returns:
Tuple[Dict,List]: Returns (Tags dictionary, Wildcard tags list)


def forward(self, hidden_states: torch.Tensor, attention_mask: torch.Tensor, position_embeddings: Optional[torch.Tensor]=None, output_attentions: bool=False, **kwargs):
    residual = hidden_states
    if self.normalize_before:
        hidden_states = self.self_attn_layer_norm(hidden_states)
    hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask, position_embeddings=position_embeddings, output_attentions=output_attentions)
    hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
    hidden_states = residual + hidden_states
    if not self.normalize_before:
        hidden_states = self.self_attn_layer_norm(hidden_states)
    if self.normalize_before:
        hidden_states = self.final_layer_norm(hidden_states)
    residual = hidden_states
    hidden_states = self.activation_fn(self.fc1(hidden_states))
    hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
    hidden_states = self.fc2(hidden_states)
    hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
    hidden_states = residual + hidden_states
    if not self.normalize_before:
        hidden_states = self.final_layer_norm(hidden_states)
    if self.training:
        if torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any():
            clamp_value = torch.finfo(hidden_states.dtype).max - 1000
            hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
    outputs = (hidden_states,)
    if output_attentions:
        outputs += (attn_weights,)
    return outputs

Args:
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
attention_mask (`torch.FloatTensor`): attention mask of size
`(batch, 1, target_len, source_len)` where padding elements are indicated by very large negative
values.
position_embeddings (`torch.FloatTensor`, *optional*):
Object queries (also called content embeddings), to be added to the hidden states.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
returned tensors for more detail.


def download_software_version(version=None, synch=False):

    if not version:
        raise CommandExecutionError("Version option must not be none.")

    if not isinstance(synch, bool):
        raise CommandExecutionError("Synch option must be boolean..")

    if synch is True:
        query = {'type': 'op',
                 'cmd': '<request><system><software><download>'
                        '<version>{0}</version></download></software></system></request>'.format(version)}
    else:
        query = {'type': 'op',
                 'cmd': '<request><system><software><download><sync-to-peer>yes</sync-to-peer>'
                        '<version>{0}</version></download></software></system></request>'.format(version)}

    return _get_job_results(query)

Download software packages by version number.

Args:
version(str): The version of the PANOS file to download.

synch (bool): If true then the file will synch to the peer unit.

CLI Example:

.. code-block:: bash

salt '*' panos.download_software_version 8.0.0
salt '*' panos.download_software_version 8.0.0 True


def __init__(self, n_clusters: int, batch_size: int, is_batched: bool=False):
    super().__init__()
    self.n_clusters = n_clusters
    self.batch_size = batch_size
    self.is_batched = is_batched

Preprocessing for Clustering Transformation
The clustering transform expects batches for performance reasons,
therefore this batches the data and converts it to numpy arrays,
which are accepted by sklearn. This transform also adds the same key
to all batches, such that only 1 state is created and updated during
clustering updates.

Example Usage::

pcoll | ClusteringPreprocessing(
n_clusters=8,
batch_size=1024,
is_batched=False)

Args:
n_clusters: number of clusters used by the algorithm
batch_size: size of the data batches
is_batched: boolean value that marks if the collection is already
batched and thus doesn't need to be batched by this transform


def read_stream(self, file: IO, data_stream: DataStream) -> Reply:
    (yield from data_stream.read_file(file=file))
    reply = (yield from self._control_stream.read_reply())
    self.raise_if_not_match('End stream', ReplyCodes.closing_data_connection, reply)
    data_stream.close()
    return reply

Read from the data stream.

Args:
file: A destination file object or a stream writer.
data_stream: The stream of which to read from.

Coroutine.

Returns:
Reply: The final reply.


def _build_zmat(self, construction_table):

        c_table = construction_table
        default_cols = ['atom', 'b', 'bond', 'a', 'angle', 'd', 'dihedral']
        optional_cols = list(set(self.columns) - {'atom', 'x', 'y', 'z'})

        zmat_frame = pd.DataFrame(columns=default_cols + optional_cols,
                                  dtype='float', index=c_table.index)

        zmat_frame.loc[:, optional_cols] = self.loc[c_table.index,
                                                    optional_cols]

        zmat_frame.loc[:, 'atom'] = self.loc[c_table.index, 'atom']
        zmat_frame.loc[:, ['b', 'a', 'd']] = c_table

        zmat_values = self._calculate_zmat_values(c_table)
        zmat_frame.loc[:, ['bond', 'angle', 'dihedral']] = zmat_values

        zmatrix = Zmat(zmat_frame, metadata=self.metadata,
                       _metadata={'last_valid_cartesian': self.copy()})
        return zmatrix

Create the Zmatrix from a construction table.

Args:
Construction table (pd.DataFrame):

Returns:
Zmat: A new instance of :class:`Zmat`.


def write(self, data):

        self._process.poll()
        if self._process.returncode is not None:
            raise EOFError('Process ended')
        self._process.stdin.write(data)

Write *n* bytes to the subprocess' input channel.

Args:
data(bytes): The data to write.

Raises:
EOFError: If the process exited.


def extract_possible_actions(self, state_arr):

        agent_x, agent_y = np.where(state_arr[-1] == 1)
        agent_x, agent_y = agent_x[0], agent_y[0]

        possible_action_arr = None
        for x, y in [
            (-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)
        ]:
            next_x = agent_x + x
            if next_x < 0 or next_x >= state_arr[-1].shape[1]:
                continue
            next_y = agent_y + y
            if next_y < 0 or next_y >= state_arr[-1].shape[0]:
                continue

            wall_flag = False
            if x > 0:
                for add_x in range(1, x):
                    if self.__map_arr[agent_x + add_x, next_y] == self.WALL:
                        wall_flag = True
            elif x < 0:
                for add_x in range(x, 0):
                    if self.__map_arr[agent_x + add_x, next_y] == self.WALL:
                        wall_flag = True

            if wall_flag is True:
                continue

            if y > 0:
                for add_y in range(1, y):
                    if self.__map_arr[next_x, agent_y + add_y] == self.WALL:
                        wall_flag = True
            elif y < 0:
                for add_y in range(y, 0):
                    if self.__map_arr[next_x, agent_y + add_y] == self.WALL:
                        wall_flag = True

            if wall_flag is True:
                continue

            if self.__map_arr[next_x, next_y] == self.WALL:
                continue

            if (next_x, next_y) in self.__route_memory_list:
                continue

            next_action_arr = np.zeros((
                 3 + self.__enemy_num,
                 state_arr[-1].shape[0],
                 state_arr[-1].shape[1]
            ))
            next_action_arr[0][agent_x, agent_y] = 1
            next_action_arr[1] = self.__map_arr
            next_action_arr[-1][next_x, next_y] = 1

            for e in range(self.__enemy_num):
                enemy_state_arr = np.zeros(state_arr[0].shape)
                enemy_state_arr[self.__enemy_pos_list[e][0], self.__enemy_pos_list[e][1]] = 1
                next_action_arr[2 + e] = enemy_state_arr

            next_action_arr = np.expand_dims(next_action_arr, axis=0)
            if possible_action_arr is None:
                possible_action_arr = next_action_arr
            else:
                possible_action_arr = np.r_[possible_action_arr, next_action_arr]

        if possible_action_arr is not None:
            while possible_action_arr.shape[0] < self.__batch_size:
                key = np.random.randint(low=0, high=possible_action_arr.shape[0])
                possible_action_arr = np.r_[
                    possible_action_arr,
                    np.expand_dims(possible_action_arr[key], axis=0)
                ]
        else:

            self.__route_memory_list = self.__route_memory_list[1:]
            possible_action_arr = self.extract_possible_actions(state_arr)

        return possible_action_arr

Extract possible actions.

Args:
state_arr:  `np.ndarray` of state.

Returns:
`np.ndarray` of actions.
The shape is:(
`batch size corresponded to each action key`,
`channel that is 1`,
`feature points1`,
`feature points2`
)


def by_geopoint(self, lat, long):

        header, content = self._http_request(self.BASE_URL, lat=lat, long=long)
        return json.loads(content)

Perform a Yelp Neighborhood API Search based on a geopoint.

Args:
lat      - geopoint latitude
long     - geopoint longitude


def unhide_tool(self, context_name, tool_name):

        data = self._context(context_name)
        hidden_tools = data["hidden_tools"]
        if tool_name in hidden_tools:
            hidden_tools.remove(tool_name)
            self._flush_tools()

Unhide a tool so that it may be exposed in a suite.

Note that unhiding a tool doesn't guarantee it can be seen - a tool of
the same name from a different context may be overriding it.

Args:
context_name (str): Context containing the tool.
tool_name (str): Name of tool to unhide.


def attach_socket(self, **kwargs):

        return self.client.api.attach_socket(self.id, **kwargs)

Like :py:meth:`attach`, but returns the underlying socket-like object
for the HTTP request.

Args:
params (dict): Dictionary of request parameters (e.g. ``stdout``,
``stderr``, ``stream``).
ws (bool): Use websockets instead of raw HTTP.

Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.


def _show_all(saved_model_dir):
    saved_model = saved_model_utils.read_saved_model(saved_model_dir)
    for meta_graph_def in sorted(saved_model.meta_graphs, key=lambda meta_graph_def: list(meta_graph_def.meta_info_def.tags)):
        tag_set = meta_graph_def.meta_info_def.tags
        print("\nMetaGraphDef with tag-set: '%s' contains the following SignatureDefs:" % ', '.join(tag_set))
        tag_set = ','.join(tag_set)
        signature_def_map = meta_graph_def.signature_def
        for signature_def_key in sorted(signature_def_map.keys()):
            print("\nsignature_def['" + signature_def_key + "']:")
            _show_inputs_outputs_mgd(meta_graph_def, signature_def_key, indent=1)
        _show_ops_in_metagraph_mgd(meta_graph_def)
    _show_defined_functions(saved_model_dir, saved_model.meta_graphs)

Prints tag-set, ops, SignatureDef, and Inputs/Outputs of SavedModel.

Prints all tag-set, ops, SignatureDef and Inputs/Outputs information stored in
SavedModel directory.

Args:
saved_model_dir: Directory containing the SavedModel to inspect.


def remove_child(self, c: 'AbstractSyntaxTree') -> None:
    if self._children is None:
        raise ValueError(f'No children belonging to {self!r}.')
    self._children.remove(c)
    c.parent = None

Removes a child from the reciever and sets its parent to `None`.

Args:
c: The child to remove. By default, compared using pointer equality.

Raises:
ValueError in the event that the child does not being to the underlying
list of children.


def PublishEvent(cls, event_name, msg, token=None):

    cls.PublishMultipleEvents({event_name: [msg]}, token=token)

Publish the message into all listeners of the event.

We send the message to all event handlers which contain this
string in their EVENT static member. This allows the event to be
sent to multiple interested listeners.

Args:
event_name: An event name.
msg: The message to send to the event handler.
token: ACL token.

Raises:
ValueError: If the message is invalid. The message must be a Semantic
Value (instance of RDFValue) or a full GrrMessage.


def alwaysThrew(self, error_type=None):

        if self.callCount == 0:
            return False
        if not error_type:
            return True if len(self.exceptions) == self.callCount else False
        else:
            return uch.obj_in_list_always(self.exceptions, error_type)

Determining whether the specified exception is the ONLY thrown exception
Args:
error_type:
None: checking without specified exception
Specified Exception
Return: Boolean


def load_hat(self, path):

        hat = cv2.imread(path, cv2.IMREAD_UNCHANGED)
        if hat is None:
            raise ValueError('No hat image found at `{}`'.format(path))
        b, g, r, a = cv2.split(hat)
        return cv2.merge((r, g, b, a))

Loads the hat from a picture at path.

Args:
path: The path to load from

Returns:
The hat data.


def cifar_generator(cifar_version, tmp_dir, training, how_many, start_from=0):
    if (cifar_version == 'cifar10'):
        url = _CIFAR10_URL
        train_files = _CIFAR10_TRAIN_FILES
        test_files = _CIFAR10_TEST_FILES
        prefix = _CIFAR10_PREFIX
        image_size = _CIFAR10_IMAGE_SIZE
        label_key = 'labels'
    elif ((cifar_version == 'cifar100') or (cifar_version == 'cifar20')):
        url = _CIFAR100_URL
        train_files = _CIFAR100_TRAIN_FILES
        test_files = _CIFAR100_TEST_FILES
        prefix = _CIFAR100_PREFIX
        image_size = _CIFAR100_IMAGE_SIZE
        if (cifar_version == 'cifar100'):
            label_key = 'fine_labels'
        else:
            label_key = 'coarse_labels'
    _get_cifar(tmp_dir, url)
    data_files = (train_files if training else test_files)
    (all_images, all_labels) = ([], [])
    for filename in data_files:
        path = os.path.join(tmp_dir, prefix, filename)
        with tf.gfile.Open(path, 'rb') as f:
            if six.PY2:
                data = cPickle.load(f)
            else:
                data = cPickle.load(f, encoding='latin1')
        images = data['data']
        num_images = images.shape[0]
        images = images.reshape((num_images, 3, image_size, image_size))
        all_images.extend([np.squeeze(images[j]).transpose((1, 2, 0)) for j in range(num_images)])
        labels = data[label_key]
        all_labels.extend([labels[j] for j in range(num_images)])
    return image_utils.image_generator(all_images[start_from:(start_from + how_many)], all_labels[start_from:(start_from + how_many)])

Image generator for CIFAR-10 and 100.

Args:
cifar_version: string; one of "cifar10" or "cifar100"
tmp_dir: path to temporary storage directory.
training: a Boolean; if true, we use the train set, otherwise the test set.
how_many: how many images and labels to generate.
start_from: from which image to start.

Returns:
An instance of image_generator that produces CIFAR-10 images and labels.


def __init__(self, max_iterations, unroll_loop=False):

        assert max_iterations >= 0
        self.max_iterations = max_iterations

        assert isinstance(unroll_loop, bool)
        self.unroll_loop = unroll_loop

        super(Iterative, self).__init__()

        self.initialize = tf.make_template(name_='initialize', func_=self.tf_initialize)
        self.step = tf.make_template(name_='step', func_=self.tf_step)
        self.next_step = tf.make_template(name_='next-step', func_=self.tf_next_step)

Creates a new iterative solver instance.

Args:
max_iterations: Maximum number of iterations before termination.
unroll_loop: Unrolls the TensorFlow while loop if true.


def email_address(self, address, owner=None, **kwargs):
    return EmailAddress(self.tcex, address, owner=owner, **kwargs)

Create the Email Address TI object.

Args:
owner:
address:
**kwargs:

Return:


def html_for_modules_method(method_name, *args, **kwargs):

    method = getattr(modules, method_name)
    value = method(*args, **kwargs)
    return KEY_VALUE_TEMPLATE.format(method_name, value)

Returns an HTML snippet for a Modules API method.

Args:
method_name: A string containing a Modules API method.
args: Positional arguments to be passed to the method.
kwargs: Keyword arguments to be passed to the method.

Returns:
String HTML representing the Modules API method and value.


def _begin_operation_action(self, action):

        conn_key = action.data['id']
        callback = action.data['callback']

        if self._get_connection_state(conn_key) != self.Idle:
            callback(conn_key, self.id, False, 'Cannot start operation, connection is not idle')
            return

        data = self._get_connection(conn_key)
        data['state'] = self.InProgress
        data['microstate'] = action.data['operation_name']
        data['action'] = action

Begin an attempted operation.

Args:
action (ConnectionAction): the action object describing what we are
operating on


def _add_arg_java(self, key, value, mask=False):
    if isinstance(value, bool):
        value = int(value)
    self._data[key] = value
    self._args.append('{}{}={}'.format('-D', key, value))
    self._args_quoted.append(self.quote('{}{}={}'.format('-D', key, value)))
    if mask:
        value = ('x' * len(str(value)))
    self._args_masked.append('{}{}={}'.format('-D', key, value))

Add CLI Arg formatted specifically for Java.

Args:
key (string): The CLI Args key (e.g., --name).
value (string): The CLI Args value (e.g., bob).
mask (boolean, default:False): Indicates whether no mask value.


def read_label_list(path):

    ll = annotations.LabelList()

    for record in read_label_file(path):
        ll.add(annotations.Label(record[2], start=record[0], end=record[1]))

    return ll

Reads labels from an Audacity label file
and returns them wrapped in a :py:class:`audiomate.annotations.LabelList`.

Args:
path (str): Path to the Audacity label file

Returns:
audiomate.annotations.LabelList: Label list containing the labels


def __init__(self, project_name, instance_name, table_name):

        self.btspec = BigtableSpec(project_name, instance_name, table_name)
        self.bt_table = bigtable.Client(
            self.btspec.project, admin=True).instance(
                self.btspec.instance).table(self.btspec.table)
        self.tf_table = tf.contrib.cloud.BigtableClient(
            self.btspec.project,
            self.btspec.instance).table(self.btspec.table)

Constructor.

Args:
project_name:  string name of GCP project having table.
instance_name:  string name of CBT instance in project.
table_name:  string name of CBT table in instance.


def tell(self):
    self._checkClosed()
    return self._position

Tell the stream's current offset.

Returns:
current offset in reading this stream.

Raises:
``ValueError``: When this stream is closed.


def get_intersection(self, range_):
    result = []
    for entry in self.entries:
        (package, value) = entry
        if (value is None):
            continue
        if (package.version not in range_):
            continue
        if isinstance(value, list):
            variants = value
            entry_ = _PackageEntry(package, variants, self.solver)
            result.append(entry_)
            continue
        if self.solver.package_filter:
            rule = self.solver.package_filter.excludes(package)
            if rule:
                if config.debug_package_exclusions:
                    print_debug(("Package '%s' was excluded by rule '%s'" % (package.qualified_name, str(rule))))
                entry[1] = None
                continue
        if self.solver.package_load_callback:
            self.solver.package_load_callback(package)
        variants_ = []
        for var in package.iter_variants():
            variant = PackageVariant(var, self.solver.building)
            variants_.append(variant)
        entry[1] = variants_
        entry_ = _PackageEntry(package, variants_, self.solver)
        result.append(entry_)
    return (result or None)

Get a list of variants that intersect with the given range.

Args:
range_ (`VersionRange`): Package version range.

Returns:
List of `_PackageEntry` objects.


def register_event(self, name, callback, validator):

    async def _validate_and_call(message):
        payload = message.get('payload')
        try:
            payload = validator.verify(payload)
        except ValidationError:
            self._logger.warning('Dropping invalid payload for event %s, payload=%s', name, payload)
            return
        try:
            result = callback(payload)
            if inspect.isawaitable(result):
                (await result)
        except:
            self._logger.error('Error calling callback for event %s, payload=%s', name, payload, exc_info=True)
    self._manager.every_match(_validate_and_call, type='event', name=name)

Register a callback to receive events.

Every event with the matching name will have its payload validated
using validator and then will be passed to callback if validation
succeeds.

Callback must be a normal callback function, coroutines are not
allowed.  If you need to run a coroutine you are free to schedule it
from your callback.

Args:
name (str): The name of the event that we are listening
for
callback (callable): The function that should be called
when a message that matches validator is received.
validator (Verifier): A schema verifier that will
validate a received message uniquely


def _peer_get_bfd(self, tx, rx, multiplier):

        tx = self._callback(tx, handler='get_config')
        rx = self._callback(rx, handler='get_config')
        multiplier = self._callback(multiplier, handler='get_config')
        tx = pynos.utilities.return_xml(str(tx))
        rx = pynos.utilities.return_xml(str(rx))
        multiplier = pynos.utilities.return_xml(str(multiplier))
        config = pynos.utilities.merge_xml(tx, rx)
        return pynos.utilities.merge_xml(config, multiplier)

Get and merge the `bfd` config from global BGP.

You should not use this method.
You probably want `BGP.bfd`.

Args:
tx: XML document with the XML to get the transmit interval.
rx: XML document with the XML to get the receive interval.
multiplier: XML document with the XML to get the interval
multiplier.

Returns:
Merged XML document.

Raises:
None


def load_institute(adapter, internal_id, display_name, sanger_recipients=None):
    institute_obj = build_institute(internal_id=internal_id, display_name=display_name, sanger_recipients=sanger_recipients)
    log.info('Loading institute {0} with display name {1} into database'.format(internal_id, display_name))
    adapter.add_institute(institute_obj)

Load a institute into the database

Args:
adapter(MongoAdapter)
internal_id(str)
display_name(str)
sanger_recipients(list(email))


def wait_for_stateful_block_init(context, mri, timeout=DEFAULT_TIMEOUT):
    context.when_matches([mri, 'state', 'value'], StatefulStates.READY, bad_values=[StatefulStates.FAULT, StatefulStates.DISABLED], timeout=timeout)

Wait until a Block backed by a StatefulController has initialized

Args:
context (Context): The context to use to make the child block
mri (str): The mri of the child block
timeout (float): The maximum time to wait


def add_attribute_label(self, attribute_id, label):
    if (not self.can_update()):
        self._tcex.handle_error(910, [self.type])
    return self.tc_requests.add_attribute_label(self.api_type, self.api_sub_type, self.unique_id, attribute_id, label, owner=self.owner)

Adds a security labels to a attribute

Args:
attribute_id:
label:

Returns: A response json


def _map_args(self, node: 'cfg.CFGNode', args: function.Args) -> 'dict[str, cfg.Variable]':
    posargs = [u.AssignToNewVariable(node) for u in args.posargs]
    kws = {k: u.AssignToNewVariable(node) for k, u in args.namedargs.items()}
    sig = self.signature
    callargs = {name: self.ctx.program.NewVariable(default.data, [], node) for name, default in sig.defaults.items()}
    positional = dict(zip(sig.param_names, posargs))
    posonly_names = set(sig.posonly_params)
    for key in set(positional) - posonly_names:
        if key in kws:
            raise error_types.DuplicateKeyword(sig, args, self.ctx, key)
    kwnames = set(kws)
    extra_kws = kwnames.difference(sig.param_names + sig.kwonly_params)
    if extra_kws and (not sig.kwargs_name):
        if function.has_visible_namedarg(node, args, extra_kws):
            raise error_types.WrongKeywordArgs(sig, args, self.ctx, extra_kws)
    posonly_kws = kwnames & posonly_names
    if posonly_kws and (not sig.kwargs_name):
        raise error_types.WrongKeywordArgs(sig, args, self.ctx, posonly_kws)
    callargs.update(positional)
    callargs.update(kws)
    for key, kwonly in itertools.chain(self.get_nondefault_params(), ((key, True) for key in sig.kwonly_params)):
        if key not in callargs:
            if args.starstarargs or (args.starargs and (not kwonly)):
                callargs[key] = self.ctx.new_unsolvable(node)
            else:
                raise error_types.MissingParameter(sig, args, self.ctx, key)
    if sig.varargs_name:
        varargs_name = sig.varargs_name
        extraneous = posargs[self.argcount(node):]
        if args.starargs:
            if extraneous:
                log.warning('Not adding extra params to *%s', varargs_name)
            callargs[varargs_name] = args.starargs.AssignToNewVariable(node)
        else:
            callargs[varargs_name] = self.ctx.convert.build_tuple(node, extraneous)
    elif len(posargs) > self.argcount(node):
        raise error_types.WrongArgCount(sig, args, self.ctx)
    if sig.kwargs_name:
        kwargs_name = sig.kwargs_name
        if args.starstarargs:
            callargs[kwargs_name] = args.starstarargs.AssignToNewVariable(node)
        else:
            omit = sig.param_names + sig.kwonly_params
            k = _instances.Dict(self.ctx)
            k.update(node, args.namedargs, omit=omit)
            callargs[kwargs_name] = k.to_variable(node)
    return callargs

Map call args to function args.

This emulates how Python would map arguments of function calls. It takes
care of keyword parameters, default parameters, and *args and **kwargs.

Args:
node: The current CFG node.
args: The arguments.

Returns:
A dictionary, mapping strings (parameter names) to cfg.Variable.

Raises:
function.FailedFunctionCall: If the caller supplied incorrect arguments.


def urlEncodeAndJoin(self, seq, sepr=','):

        try:
            from urllib.parse import quote_plus as encode
            return sepr.join([encode(x, encoding=CHARSET_UTF8) for x in seq])
        except ImportError:
            from urllib import quote as encode
            return sepr.join([i for i in map(lambda x: encode(x), seq)])

sepr.join(urlencode(seq))
Args:
seq: string list to be urlencoded
sepr: join seq with sepr
Returns:
str


def patchify(self, pixel_values, interpolate_pos_encoding: bool=False):
    patch_size, num_channels = (self.config.patch_size, self.config.num_channels)
    if shape_list(pixel_values)[1] == num_channels:
        pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
    if not interpolate_pos_encoding:
        tf.debugging.assert_equal(shape_list(pixel_values)[1], shape_list(pixel_values)[2], message='Make sure the pixel values have a squared size')
    tf.debugging.assert_equal(shape_list(pixel_values)[1] % patch_size, 0, message='Make sure the pixel values have a size that is divisible by the patch size')
    tf.debugging.assert_equal(shape_list(pixel_values)[3], num_channels, message='Make sure the number of channels of the pixel values is equal to the one set in the configuration')
    batch_size = shape_list(pixel_values)[0]
    num_patches_h = shape_list(pixel_values)[1]
    num_patches_w = shape_list(pixel_values)[2]
    patchified_pixel_values = tf.reshape(pixel_values, (batch_size, num_patches_h, patch_size, num_patches_w, patch_size, num_channels))
    patchified_pixel_values = tf.einsum('nhpwqc->nhwpqc', patchified_pixel_values)
    patchified_pixel_values = tf.reshape(patchified_pixel_values, (batch_size, num_patches_h * num_patches_w, patch_size ** 2 * num_channels))
    return patchified_pixel_values

Args:
pixel_values (`tf.Tensor` of shape `(batch_size, height, width, num_channels)` or `(batch_size, num_channels, height, width)`):
Pixel values.
interpolate_pos_encoding (`bool`, default `False`):
interpolation flag passed during the forward pass.

Returns:
`tf.Tensor` of shape `(batch_size, num_patches, patch_size**2 * num_channels)`:
Patchified pixel values.


def lstat(self, entry_path, dir_fd=None):

        entry_path = self._path_with_dir_fd(entry_path, self.lstat, dir_fd)
        return self.filesystem.stat(entry_path, follow_symlinks=False)

Return the os.stat-like tuple for entry_path, not following symlinks.

Args:
entry_path:  path to filesystem object to retrieve.
dir_fd: If not `None`, the file descriptor of a directory, with
`entry_path` being relative to this directory.
New in Python 3.3.

Returns:
the FakeStatResult object corresponding to `entry_path`.

Raises:
OSError: if the filesystem object doesn't exist.


def __init__(self, prefix):

        self.bed = PyPlink(prefix)
        self.bim = self.bed.get_bim()
        self.fam = self.bed.get_fam()

        self.bim["multiallelic"] = False
        self.bim.loc[
            self.bim.duplicated(["chrom", "pos"], keep=False),
            "multiallelic"
        ] = True

        try:
            self.fam = self.fam.set_index("iid", verify_integrity=True)
        except ValueError:
            logging.info(
                "Setting the index as 'fid_iid' because the individual IDs "
                "are not unique."
            )

            self.fam["fid_iid"] = [
                "{fid}_{iid}".format(fid=fid, iid=iid)
                for fid, iid in zip(self.fam.fid, self.fam.iid)
            ]
            self.fam = self.fam.set_index("fid_iid", verify_integrity=True)

Binary plink file reader.
Args:
prefix (str): the prefix of the Plink binary files.


def assert_global_step(global_step_tensor):
    if not (isinstance(global_step_tensor, variables.Variable) or isinstance(global_step_tensor, tensor.Tensor) or resource_variable_ops.is_resource_variable(global_step_tensor)):
        raise TypeError('Existing "global_step" must be a Variable or Tensor: %s.' % global_step_tensor)
    if not global_step_tensor.dtype.base_dtype.is_integer:
        raise TypeError('Existing "global_step" does not have integer type: %s' % global_step_tensor.dtype)
    if global_step_tensor.get_shape().ndims != 0 and global_step_tensor.get_shape().is_fully_defined():
        raise TypeError('Existing "global_step" is not scalar: %s' % global_step_tensor.get_shape())

Asserts `global_step_tensor` is a scalar int `Variable` or `Tensor`.

Args:
global_step_tensor: `Tensor` to test.


def set_state(self, vid, value=None, default=False, disable=False):
    cmds = self.command_builder('state', value=value, default=default, disable=disable)
    return self.configure_vlan(vid, cmds)

Configures the VLAN state

EosVersion:
4.13.7M

Args:
vid (str): The VLAN ID to configure
value (str): The value to set the vlan state to
default (bool): Configures the vlan state to its default value
disable (bool): Negates the vlan state

Returns:
True if the operation was successful otherwise False


def tar_add_bytes(tf, filename, bytestring):

    if not isinstance(bytestring, bytes):
        bytestring = bytestring.encode('ascii')
    buff = io.BytesIO(bytestring)
    tarinfo = tarfile.TarInfo(filename)
    tarinfo.size = len(bytestring)
    tf.addfile(tarinfo, buff)

Add a file to a tar archive

Args:
tf (tarfile.TarFile): tarfile to add the file to
filename (str): path within the tar file
bytestring (bytes or str): file contents. Must be :class:`bytes` or
ascii-encodable :class:`str`


def timeRange(
        start: datetime.time, end: datetime.time,
        step: float) -> Iterator[datetime.datetime]:

    assert step > 0
    start = _fillDate(start)
    end = _fillDate(end)
    delta = datetime.timedelta(seconds=step)
    t = start
    while t < datetime.datetime.now():
        t += delta
    while t <= end:
        waitUntil(t)
        yield t
        t += delta

Iterator that waits periodically until certain time points are
reached while yielding those time points.

Args:
start: Start time, can be specified as datetime.datetime,
or as datetime.time in which case today is used as the date
end: End time, can be specified as datetime.datetime,
or as datetime.time in which case today is used as the date
step (float): The number of seconds of each period


def __call__(self, *args):

        if len(self.formatters) == 0:
            self.setup(*args)

        row_cells = []

        if self.rownum:
            row_cells.append(0)
        if self.timestamp:
            row_cells.append(datetime.datetime.now())
        if self.time_diff:
            row_cells.append(0)

        row_cells.extend(args)

        if len(row_cells) != len(self.formatters):
            raise ValueError('Expected number of columns is {}. Got {}.'.format(
                len(self.formatters), len(row_cells)))

        line = self.format_row(*row_cells)
        self.print_line(line)

Prints a formatted row

Args:
args: row cells


def create_query(self, fields=None):

        if fields is None:
            return Query(self.fields)

        non_contained_fields = set(fields) - set(self.fields)
        if non_contained_fields:
            raise BaseLunrException(
                "Fields {} are not part of the index", non_contained_fields
            )

        return Query(fields)

Convenience method to create a Query with the Index's fields.

Args:
fields (iterable, optional): The fields to include in the Query,
defaults to the Index's `all_fields`.

Returns:
Query: With the specified fields or all the fields in the Index.


def make_supercells_with_defects(self, scaling_matrix):

        scs = []
        sc = self._structure.copy()
        sc.make_supercell(scaling_matrix)
        scs.append(sc)
        for ids, defect_site in enumerate(self._defect_sites):
            sc_with_inter = sc.copy()
            sc_with_inter.append(
                defect_site.species_string,
                defect_site.frac_coords,
                coords_are_cartesian=False,
                validate_proximity=False,
                properties=None)
            if not sc_with_inter:
                raise RuntimeError(
                    "could not generate supercell with" " interstitial {}".format(
                        ids + 1))
            scs.append(sc_with_inter.copy())
        return scs

Generate a sequence of supercells
in which each supercell contains a single interstitial,
except for the first supercell in the sequence
which is a copy of the defect-free input structure.

Args:
scaling_matrix (3x3 integer array): scaling matrix
to transform the lattice vectors.
Returns:
scs ([Structure]): sequence of supercells.


def CopyToDict(self):
    result_dict = {'labels': self.labels}
    if self.comment:
        result_dict['comment'] = self.comment
    return result_dict

Copies the event tag to a dictionary.

Returns:
dict[str, object]: event tag attributes.


def convert_timedelta(duration):

    days, seconds = duration.days, duration.seconds
    hours = seconds
    minutes = (seconds % 3600)
    seconds = (seconds % 60)
    return days, hours, minutes, seconds

Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)


def _original_path(self, path):

    def components_to_path():
        if (len(path_components) > len(normalized_components)):
            normalized_components.extend(path_components[len(normalized_components):])
        sep = self._path_separator(path)
        normalized_path = sep.join(normalized_components)
        if (path.startswith(sep) and (not normalized_path.startswith(sep))):
            normalized_path = (sep + normalized_path)
        return normalized_path
    if (self.is_case_sensitive or (not path)):
        return path
    path_components = self._path_components(path)
    normalized_components = []
    current_dir = self.root
    for component in path_components:
        if (not isinstance(current_dir, FakeDirectory)):
            return components_to_path()
        (dir_name, current_dir) = self._directory_content(current_dir, component)
        if ((current_dir is None) or (isinstance(current_dir, FakeDirectory) and (current_dir._byte_contents is None) and (current_dir.st_size == 0))):
            return components_to_path()
        normalized_components.append(dir_name)
    return components_to_path()

Return a normalized case version of the given path for
case-insensitive file systems. For case-sensitive file systems,
return path unchanged.

Args:
path: the file path to be transformed

Returns:
A version of path matching the case of existing path elements.


def generate_json_schema(cls, schema, context=DEFAULT_DICT):

        schema = cls._get_schema(schema)

        return cls(context=context).dump(schema).data

Generate a JSON Schema from a Marshmallow schema.

Args:
schema (marshmallow.Schema|str): The Marshmallow schema, or the
Python path to one, to create the JSON schema for.

Keyword Args:
file_pointer (file, optional): The path or pointer to the file
to write this schema to. If not provided, the schema will be
dumped to ``sys.stdout``.

Returns:
dict: The JSON schema in dictionary form.


def plot(self, **plot_kwargs: Any) -> None:

        fig = plt.figure()
        plt.plot(self._rabi_angles, self._excited_state_probs, 'ro-',
                 figure=fig, **plot_kwargs)
        plt.xlabel(r"Rabi Angle (Radian)", figure=fig)
        plt.ylabel('Excited State Probability', figure=fig)
        fig.show()

Plots excited state probability vs the Rabi angle (angle of rotation
around the x-axis).

Args:
**plot_kwargs: Arguments to be passed to matplotlib.pyplot.plot.


def Print(self, output_writer):

    if self._date_time_ranges:
      for date_time_range in self._date_time_ranges:
        if date_time_range.start_date_time is None:
          end_time_string = date_time_range.end_date_time.CopyToDateTimeString()
          output_writer.Write('\t{0:s} after {1:s}\n'.format(
              date_time_range.time_value, end_time_string))

        elif date_time_range.end_date_time is None:
          start_time_string = (
              date_time_range.start_date_time.CopyToDateTimeString())
          output_writer.Write('\t{0:s} before {1:s}\n'.format(
              date_time_range.time_value, start_time_string))

        else:
          start_time_string = (
              date_time_range.start_date_time.CopyToDateTimeString())
          end_time_string = date_time_range.end_date_time.CopyToDateTimeString()
          output_writer.Write('\t{0:s} between {1:s} and {2:s}\n'.format(
              date_time_range.time_value, start_time_string,
              end_time_string))

Prints a human readable version of the filter.

Args:
output_writer (CLIOutputWriter): output writer.


def ones(shape, dtype=None, **kwargs):
    data = np.ones(shape, dtype)
    return dc.array(data, **kwargs)

Create an array of given shape and type, filled with ones.

Args:
shape (sequence of ints): 2D shape of the array.
dtype (data-type, optional): Desired data-type for the array.
kwargs (optional): Other arguments of the array (*coords, attrs, and name).

Returns:
array (decode.array): Decode array filled with ones.


async def gather(self, *cmds: str) -> Tuple[int]:
    subprocs = self.spawn(*cmds)
    subproc_wait_coros = [subproc.wait_done() for subproc in subprocs]
    return (await asyncio.gather(*subproc_wait_coros))

Coroutine to spawn subprocesses and block until completion.

Note:
The same `max_concurrency` restriction that applies to `spawn`
also applies here.

Returns:
The exit codes of the spawned subprocesses, in the order they were
passed.


def compile_protofile(proto_file_path):

    out_file = tempfile.mkstemp()[1]
    try:
        subprocess.check_output(['protoc', '--include_source_info',
                                 '--descriptor_set_out', out_file,
                                 proto_file_path])
    except subprocess.CalledProcessError as e:
        sys.exit('protoc returned status {}'.format(e.returncode))
    return out_file

Compile proto file to descriptor set.

Args:
proto_file_path: Path to proto file to compile.

Returns:
Path to file containing compiled descriptor set.

Raises:
SystemExit if the compilation fails.


def _click(x, y, button):

    if button == 'left':
        try:
            _sendMouseEvent(MOUSEEVENTF_LEFTCLICK, x, y)
        except (PermissionError, OSError):
            pass
    elif button == 'middle':
        try:
            _sendMouseEvent(MOUSEEVENTF_MIDDLECLICK, x, y)
        except (PermissionError, OSError):
            pass
    elif button == 'right':
        try:
            _sendMouseEvent(MOUSEEVENTF_RIGHTCLICK, x, y)
        except (PermissionError, OSError):
            pass
    else:
        assert False, "button argument not in ('left', 'middle', 'right')"

Send the mouse click event to Windows by calling the mouse_event() win32
function.

Args:
button (str): The mouse button, either 'left', 'middle', or 'right'
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.

Returns:
None


def get_package_for_module(module):
    if isinstance(module, six.string_types):
        try:
            module = sys.modules[module]
        except KeyError:
            return None
    try:
        return six.text_type(module.package)
    except AttributeError:
        if (module.__name__ == '__main__'):
            try:
                file_name = module.__file__
            except AttributeError:
                pass
            else:
                base_name = os.path.basename(file_name)
                split_name = os.path.splitext(base_name)
                if (len(split_name) == 1):
                    return six.text_type(base_name)
                return u'.'.join(split_name[:(- 1)])
        return six.text_type(module.__name__)

Get package name for a module.

Helper calculates the package name of a module.

Args:
module: Module to get name for.  If module is a string, try to find
module in sys.modules.

Returns:
If module contains 'package' attribute, uses that as package name.
Else, if module is not the '__main__' module, the module __name__.
Else, the base name of the module file name.  Else None.


def _CheckForOutOfOrderStepAndMaybePurge(self, event):

    if event.step < self.most_recent_step and event.HasField('summary'):
      self._Purge(event, by_tags=True)
    else:
      self.most_recent_step = event.step
      self.most_recent_wall_time = event.wall_time

Check for out-of-order event.step and discard expired events for tags.

Check if the event is out of order relative to the global most recent step.
If it is, purge outdated summaries for tags that the event contains.

Args:
event: The event to use as reference. If the event is out-of-order, all
events with the same tags, but with a greater event.step will be purged.


def _allocate_ips_to_nics(self, conf):
    for (dom_name, dom_spec) in conf.get('domains', {}).items():
        for (idx, nic) in enumerate(dom_spec.get('nics', [])):
            if ('ip' in nic):
                continue
            net = self._get_net(conf, dom_name, nic)
            if (net['type'] != 'nat'):
                continue
            allocated = net['mapping'].values()
            vacant = _create_ip(net['gw'], set(range(2, 255)).difference(set([int(ip.split('.')[(- 1)]) for ip in allocated])).pop())
            nic['ip'] = vacant
            self._add_nic_to_mapping(net, dom_spec, nic)

For all the nics of all the domains in the conf that have dynamic ip,
allocate one and addit to the network mapping

Args:
conf (dict): Configuration spec to extract the domains from

Returns:
None


def coroutine(func):

    def wrapper(*args, **kwargs):
        gen = func(*args, **kwargs)
        val = next(gen)
        if (val != None):
            raise TypeError('Unexpected value from start of coroutine')
        return gen
    wrapper.__name__ = func.__name__
    wrapper.__doc__ = func.__doc__
    return wrapper

Wraps a PEP-342 enhanced generator in a way that avoids boilerplate of the "priming" call to ``next``.

Args:
func (Callable): The function constructing a generator to decorate.

Returns:
Callable: The decorated generator.


def get_tensor_from_node(node):
    with ops.init_scope():
        if getattr(node, 'is_distributed_variable', False):
            return node
        elif getattr(node, 'is_distributed_table', False):
            return node
        elif getattr(node, 'is_sharded_variable', False):
            return node
        elif resource_variable_ops.is_resource_variable(node):
            return node.handle
        elif isinstance(node, asset.Asset):
            return node.asset_path
        elif tensor_util.is_tf_type(node):
            return node
        elif isinstance(node, resource.CapturableResource):
            return node.resource_handle
        raise ValueError(f'Cannot convert node {node} to tensor.')

Resolves a saved model graph node into a tensor to be captured.

Args:
node: a tensor, variable, or resource to be resolved into a capturable
tensor

Returns:
A list of tensors.
Raises:
ValueError: if the node cannot be converted into a tensor.


def dot(poly1, poly2):
    if ((not isinstance(poly1, Poly)) and (not isinstance(poly2, Poly))):
        return numpy.dot(poly1, poly2)
    poly1 = Poly(poly1)
    poly2 = Poly(poly2)
    poly = (poly1 * poly2)
    if ((numpy.prod(poly1.shape) <= 1) or (numpy.prod(poly2.shape) <= 1)):
        return poly
    return chaospy.poly.sum(poly, 0)

Dot product of polynomial vectors.

Args:
poly1 (Poly) : left part of product.
poly2 (Poly) : right part of product.

Returns:
(Poly) : product of poly1 and poly2.

Examples:
>>> poly = cp.prange(3, 1)
>>> print(poly)
[1, q0, q0^2]
>>> print(cp.dot(poly, numpy.arange(3)))
2q0^2+q0
>>> print(cp.dot(poly, poly))
q0^4+q0^2+1


def resorted(values):

    if not values:
        return values

    values = sorted(values)

    first_word = next(
        (cnt for cnt, val in enumerate(values)
             if val and not val[0].isdigit()),
        None
    )

    if first_word is None:
        return values

    words = values[first_word:]
    numbers = values[:first_word]

    return words + numbers

Sort values, but put numbers after alphabetically sorted words.

This function is here to make outputs diff-compatible with Aleph.

Example::
>>> sorted(["b", "1", "a"])
['1', 'a', 'b']
>>> resorted(["b", "1", "a"])
['a', 'b', '1']

Args:
values (iterable): any iterable object/list/tuple/whatever.

Returns:
list of sorted values, but with numbers after words


def _sample_cell(args, cell_body):
    env = datalab.utils.commands.notebook_environment()
    query = None
    table = None
    view = None
    if args['query']:
        query = _get_query_argument(args, cell_body, env)
    elif args['table']:
        table = _get_table(args['table'])
    elif args['view']:
        view = datalab.utils.commands.get_notebook_item(args['view'])
        if (not isinstance(view, datalab.bigquery.View)):
            raise Exception(('%s is not a view' % args['view']))
    else:
        query = datalab.bigquery.Query(cell_body, values=env)
    count = args['count']
    method = args['method']
    if (method == 'random'):
        sampling = datalab.bigquery.Sampling.random(percent=args['percent'], count=count)
    elif (method == 'hashed'):
        sampling = datalab.bigquery.Sampling.hashed(field_name=args['field'], percent=args['percent'], count=count)
    elif (method == 'sorted'):
        ascending = (args['order'] == 'ascending')
        sampling = datalab.bigquery.Sampling.sorted(args['field'], ascending=ascending, count=count)
    elif (method == 'limit'):
        sampling = datalab.bigquery.Sampling.default(count=count)
    else:
        sampling = datalab.bigquery.Sampling.default(count=count)
    if query:
        results = query.sample(sampling=sampling, dialect=args['dialect'], billing_tier=args['billing'])
    elif view:
        results = view.sample(sampling=sampling)
    else:
        results = table.sample(sampling=sampling)
    if args['verbose']:
        print(results.sql)
    if args['profile']:
        return datalab.utils.commands.profile_df(results.to_dataframe())
    else:
        return results

Implements the bigquery sample cell magic for ipython notebooks.

Args:
args: the optional arguments following '%%bigquery sample'.
cell_body: optional contents of the cell interpreted as SQL, YAML or JSON.
Returns:
The results of executing the sampling query, or a profile of the sample data.


def start_naive_bayes(automated_run, session, path):
    module = functions.import_string_code_as_module(automated_run.source)
    random_state = (8 if (not hasattr(module, 'random_state')) else module.random_state)
    assert (module.metric_to_optimize in automated_run.base_learner_origin.metric_generators)
    base_estimator = automated_run.base_learner_origin.return_estimator()
    base_estimator.set_params(**module.default_params)
    default_params = functions.make_serializable(base_estimator.get_params())
    non_searchable_params = dict(((key, val) for (key, val) in iteritems(default_params) if (key not in module.pbounds)))
    existing_base_learners = []
    for base_learner in automated_run.base_learner_origin.base_learners:
        if (not (base_learner.job_status == 'finished')):
            continue
        in_search_space = True
        for (key, val) in iteritems(non_searchable_params):
            if (base_learner.hyperparameters[key] != val):
                in_search_space = False
                break
        if in_search_space:
            existing_base_learners.append(base_learner)
    target = []
    initialization_dict = dict(((key, list()) for key in module.pbounds.keys()))
    for base_learner in existing_base_learners:
        all_numerical = True
        for key in module.pbounds.keys():
            if (not isinstance(base_learner.hyperparameters[key], numbers.Number)):
                all_numerical = False
                break
        if (not all_numerical):
            continue
        for key in module.pbounds.keys():
            initialization_dict[key].append(base_learner.hyperparameters[key])
        target.append(base_learner.individual_score[module.metric_to_optimize])
    initialization_dict['target'] = (target if (not module.invert_metric) else list(map((lambda x: (- x)), target)))
    print('{} existing in initialization dictionary'.format(len(initialization_dict['target'])))
    func_to_optimize = return_func_to_optimize(path, session, automated_run.base_learner_origin, module.default_params, module.metric_to_optimize, module.invert_metric, set(module.integers))
    bo = BayesianOptimization(func_to_optimize, module.pbounds)
    bo.initialize(initialization_dict)
    np.random.seed(random_state)
    bo.maximize(**module.maximize_config)

Starts naive bayes automated run

Args:
automated_run (xcessiv.models.AutomatedRun): Automated run object

session: Valid SQLAlchemy session

path (str, unicode): Path to project folder


def decode(self, fp: TextIO) -> BioCCollection:

        tree = etree.parse(fp)
        collection = self.__parse_collection(tree.getroot())
        collection.encoding = tree.docinfo.encoding
        collection.standalone = tree.docinfo.standalone
        collection.version = tree.docinfo.xml_version
        return collection

Deserialize ``fp`` to a BioC collection object.

Args:
fp: a ``.read()``-supporting file-like object containing a BioC collection

Returns:
an object of BioCollection


def builder(name, **builder_init_kwargs):
    (name, builder_kwargs) = _dataset_name_and_kwargs_from_name_str(name)
    builder_kwargs.update(builder_init_kwargs)
    if (name in _ABSTRACT_DATASET_REGISTRY):
        raise DatasetNotFoundError(name, is_abstract=True)
    if (name in _IN_DEVELOPMENT_REGISTRY):
        raise DatasetNotFoundError(name, in_development=True)
    if (name not in _DATASET_REGISTRY):
        raise DatasetNotFoundError(name)
    try:
        return _DATASET_REGISTRY[name](**builder_kwargs)
    except BaseException:
        logging.error('Failed to construct dataset %s', name)
        raise

Fetches a `tfds.core.DatasetBuilder` by string name.

Args:
name: `str`, the registered name of the `DatasetBuilder` (the snake case
version of the class name). This can be either `"dataset_name"` or
`"dataset_name/config_name"` for datasets with `BuilderConfig`s.
As a convenience, this string may contain comma-separated keyword
arguments for the builder. For example `"foo_bar/a=True,b=3"` would use
the `FooBar` dataset passing the keyword arguments `a=True` and `b=3`
(for builders with configs, it would be `"foo_bar/zoo/a=True,b=3"` to
use the `"zoo"` config and pass to the builder keyword arguments `a=True`
and `b=3`).
**builder_init_kwargs: `dict` of keyword arguments passed to the
`DatasetBuilder`. These will override keyword arguments passed in `name`,
if any.

Returns:
A `tfds.core.DatasetBuilder`.

Raises:
DatasetNotFoundError: if `name` is unrecognized.


def from_table(table, fields=None):
    if (fields is None):
        fields = '*'
    elif isinstance(fields, list):
        fields = ','.join(fields)
    return Query(('SELECT %s FROM %s' % (fields, table._repr_sql_())))

Return a Query for the given Table object

Args:
table: the Table object to construct a Query out of
fields: the fields to return. If None, all fields will be returned. This can be a string
which will be injected into the Query after SELECT, or a list of field names.

Returns:
A Query object that will return the specified fields from the records in the Table.


def WriteEventBody(self, event):

    latitude = getattr(event, 'latitude', None)
    longitude = getattr(event, 'longitude', None)
    if latitude is not None and longitude is not None:
      placemark_xml_element = ElementTree.Element('Placemark')

      name_xml_element = ElementTree.SubElement(placemark_xml_element, 'name')

      name_xml_element.text = 'PLACEHOLDER FOR EVENT IDENTIFIER'

      description_xml_element = ElementTree.SubElement(
          placemark_xml_element, 'description')

      description_xml_element.text = (
          rawpy.NativePythonFormatterHelper.GetFormattedEventObject(event))

      point_xml_element = ElementTree.SubElement(
          placemark_xml_element, 'Point')

      coordinates_xml_element = ElementTree.SubElement(
          point_xml_element, 'coordinates')
      coordinates_xml_element.text = '{0!s},{1!s}'.format(longitude, latitude)

      xml_string = ElementTree.tostring(placemark_xml_element)

      output_text = codecs.decode(xml_string, self._output_mediator.encoding)
      self._output_writer.Write(output_text)

Writes the body of an event to the output.

Args:
event (EventObject): event.


def make_dataset_from_selfplay(data_extracts):

    tf_examples = (make_tf_example(features_lib.extract_features(pos), pi, result)
                   for pos, pi, result in data_extracts)
    return tf_examples

Returns an iterable of tf.Examples.
Args:
data_extracts: An iterable of (position, pi, result) tuples


def add_trial(self, trial):
    trial.set_verbose(self._verbose)
    self._trials.append(trial)
    with warn_if_slow('scheduler.on_trial_add'):
        self._scheduler_alg.on_trial_add(self, trial)
    self.trial_executor.try_checkpoint_metadata(trial)

Adds a new trial to this TrialRunner.

Trials may be added at any time.

Args:
trial (Trial): Trial to queue.


def set_value(self, text):

        if self.single_line:
            text = text.replace('\n', '')
        self.set_text(text)

Sets the text content.

Args:
text (str): The string content that have to be appended as standard child identified by the key 'text'


def CheckPosixThreading(filename, clean_lines, linenum, error):
    line = clean_lines.elided[linenum]
    for (single_thread_func, multithread_safe_func, pattern) in _THREADING_LIST:
        if Search(pattern, line):
            error(filename, linenum, 'runtime/threadsafe_fn', 2, (((('Consider using ' + multithread_safe_func) + '...) instead of ') + single_thread_func) + '...) for improved thread safety.'))

Checks for calls to thread-unsafe functions.

Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).

Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.


def clean_strings(iterable):
    retval = []
    for val in iterable:
        try:
            retval.append(val.strip())
        except AttributeError:
            retval.append(val)
    return retval

Take a list of strings and clear whitespace
on each one. If a value in the list is not a
string pass it through untouched.

Args:
iterable: mixed list

Returns:
mixed list


def ones(shape, dtype=None, name=None):
    with ops.init_scope():
        if dtype is None:
            dtype = floatx()
        tf_dtype = dtypes_module.as_dtype(dtype)
        v = array_ops.ones(shape=shape, dtype=tf_dtype, name=name)
        if py_all(v.shape.as_list()):
            return variable(v, dtype=dtype, name=name)
        return v

Instantiates an all-ones variable and returns it.

Args:
shape: Tuple of integers, shape of returned Keras variable.
dtype: String, data type of returned Keras variable.
name: String, name of returned Keras variable.

Returns:
A Keras variable, filled with `1.0`.
Note that if `shape` was symbolic, we cannot return a variable,
and will return a dynamically-shaped tensor instead.

Example:

>>> kvar = tf.keras.backend.ones((3,4))
>>> tf.keras.backend.eval(kvar)
array([[1.,  1.,  1.,  1.],
[1.,  1.,  1.,  1.],
[1.,  1.,  1.,  1.]], dtype=float32)


def predict_proba(self, X):

        return collections.deque(self.iter_predict_proba(X), maxlen=1).pop()

Returns the predicted probabilities for ``X``.

Arguments:
X (array-like or sparse matrix of shape (n_samples, n_features)): The input samples.
Sparse matrices are accepted only if they are supported by the weak model.

Returns:
array of shape (n_samples, n_classes) containing the predicted probabilities.


def _Consumers(t, func_graphs):
    consumers = t.consumers()
    for func in func_graphs:
        for input_t, placeholder in _Captures(func):
            if input_t is t:
                consumers.extend(_Consumers(placeholder, func_graphs))
    return consumers

Returns the consumers of t, crossing closure boundaries where necessary.

Args:
t: Tensor
func_graphs: a list of FuncGraphs that may have captured t.

Returns:
A list of tensors. The tensors will be from the current graph and/or
func_graphs.


def WriteValuesToJSONFile(self, state, values):
    value_counters = {}
    max_post_size = config.CONFIG['BigQuery.max_file_post_size']
    for value in values:
        class_name = value.__class__.__name__
        (output_tracker, created) = self._GetTempOutputFileHandles(class_name)
        value_counters[class_name] = (value_counters.get(class_name, (- 1)) + 1)
        if (not ((value_counters[class_name] % max_post_size)
            output_tracker.gzip_filehandle.flush()
            if (os.path.getsize(output_tracker.gzip_filehandle.name) > max_post_size):
                self.Flush(state)
                value_counters[class_name] = 0
                (output_tracker, created) = self._GetTempOutputFileHandles(class_name)
        if (not output_tracker.schema):
            output_tracker.schema = self.RDFValueToBigQuerySchema(value)
        if created:
            self._WriteJSONValue(output_tracker.gzip_filehandle, value)
        else:
            self._WriteJSONValue(output_tracker.gzip_filehandle, value, delimiter='\n')
    for output_tracker in itervalues(self.temp_output_trackers):
        output_tracker.gzip_filehandle.flush()

Write newline separated JSON dicts for each value.

We write each dict separately so we don't have to hold all of the output
streams in memory. We open and close the JSON array manually with [].

Args:
state: rdf_protodict.AttributedDict with the plugin's state.
values: RDF values to export.


def load_ipython_extension(ip):

    decor = InteractiveDecorator(ip)
    ip.events.register('post_run_cell', decor.post_run_cell)

    newhist = AcornHistoryManager(ip.history_manager, decor)
    ip.history_manager = newhist

Loads the interacting decorator that ships with `acorn` into the ipython
interactive shell.

Args:
ip (IPython.core.interactiveshell.InteractiveShell): ipython shell instance
for interacting with the shell variables.


def expm1(x):
    if any_symbolic_tensors((x,)):
        return Expm1().symbolic_call(x)
    return backend.numpy.expm1(x)

Calculate `exp(x) - 1` for all elements in the tensor.

Args:
x: Input values.

Returns:
Output tensor, element-wise exponential minus one.


def encode(self, value: Any) -> geno.DNA:

Encode a value into a DNA.

Args:
value: A value that conforms to the hyper value definition.

Returns:
DNA for the value.


def set_dna(self, dna: geno.DNA) -> None:
    self._dna = dna
    self._decoded_value = None

Use this DNA to generate value.

NOTE(daiyip): self._dna is only used in __call__.
Thus 'set_dna' can be called multiple times to generate different values.

Args:
dna: DNA to use to decode the value.


def expand_indicators(indicator):

        if indicator.count(' : ') > 0:

            indicator_list = []

            iregx_pattern = r'^(.*?(?=\s\:\s|$))?'
            iregx_pattern += r'(?:\s\:\s)?'

            iregx_pattern += r'((?<=\s\:\s).*?(?=(?:\s)?\:\s|$))?'
            iregx_pattern += r'(?:(?:\s)?\:\s)?'

            iregx_pattern += r'((?<=\s\:\s).*?(?=$))?$'
            iregx = re.compile(iregx_pattern)

            indicators = iregx.search(indicator)
            if indicators is not None:
                indicator_list = list(indicators.groups())
        else:

            indicator_list = [indicator]

        return indicator_list

Process indicators expanding file hashes/custom indicators into multiple entries.

Args:
indicator (string): " : " delimited string
Returns:
(list): a list of indicators split on " : ".


def get_other_answers_simple(pool, seeded_answers, get_student_item_dict, num_responses):

    ret = []

    pool = {int(k): v for k, v in pool.items()}
    total_in_pool = len(seeded_answers)
    merged_pool = convert_seeded_answers(seeded_answers)
    student_id = get_student_item_dict()['student_id']

    for key in pool:
        total_in_pool += len(pool[key])

        if student_id in pool[key].keys():
            total_in_pool -= 1
        if key in merged_pool:
            merged_pool[key].update(pool[key].items())
        else:
            merged_pool[key] = pool[key]

    selected = []

    while len(ret) < min(num_responses, total_in_pool):
        for option, students in merged_pool.items():
            student = student_id
            i = 0
            while (student == student_id or i > 100) and (str(option) + student) not in selected:

                student = random.choice(students.keys())
                i += 1
            selected.append(str(option)+student)
            if student.startswith('seeded'):

                rationale = students[student]
            else:
                student_item = get_student_item_dict(student)
                submission = sas_api.get_answers_for_student(student_item)
                rationale = submission.get_rationale(0)
            ret.append({'option': option, 'rationale': rationale})

            if len(ret) >= min(num_responses, total_in_pool):
                break

    return {"answers": ret}

Get answers from others with simple algorithm, which picks one answer for each option.

Args:
see `get_other_answers`
num_responses (int): the number of responses to be returned. This value may not be
respected if there is not enough answers to return

Returns:
dict: answers based on the selection algorithm


def __init__(self, dims):
    if isinstance(dims, (tuple, list)):
        self._dims = tuple((as_dimension(d).value for d in dims))
    elif dims is None:
        self._dims = None
    elif isinstance(dims, tensor_shape_pb2.TensorShapeProto):
        if dims.unknown_rank:
            self._dims = None
        else:
            self._dims = tuple((dim.size if dim.size != -1 else None for dim in dims.dim))
    elif isinstance(dims, TensorShape):
        self._dims = dims._dims
    else:
        try:
            dims_iter = iter(dims)
        except TypeError:
            self._dims = (as_dimension(dims).value,)
        else:
            self._dims = []
            for d in dims_iter:
                try:
                    self._dims.append(as_dimension(d).value)
                except TypeError as e:
                    raise TypeError("Failed to convert '{0!r}' to a shape: '{1!r}'could not be converted to a dimension. A shape should either be single dimension (e.g. 10), or an iterable of dimensions (e.g. [1, 10, None]).".format(dims, d)) from e
            self._dims = tuple(self._dims)

Creates a new TensorShape with the given dimensions.

Args:
dims: A list of Dimensions, or None if the shape is unspecified.

Raises:
TypeError: If dims cannot be converted to a list of dimensions.


def parse_matches(patient_id, match_objs):
    LOG.info('Parsing MatchMaker matches for patient {}'.format(patient_id))
    parsed_matches = []
    for match_obj in match_objs:
        milliseconds_date = match_obj['created']['$date']
        mdate = datetime.datetime.fromtimestamp((milliseconds_date / 1000.0))
        match_type = 'external'
        matching_patients = []
        parsed_match = {'match_oid': match_obj['_id']['$oid'], 'match_date': mdate}
        if (match_obj['data']['patient']['id'] == patient_id):
            match_results = match_obj['results']
            for node_result in match_results:
                if (match_obj['match_type'] == 'internal'):
                    match_type = 'internal'
                for patient in node_result['patients']:
                    match_patient = {'patient_id': patient['patient']['id'], 'score': patient['score'], 'patient': patient['patient'], 'node': node_result['node']}
                    matching_patients.append(match_patient)
        else:
            m_patient = match_obj['data']['patient']
            contact_institution = m_patient['contact'].get('institution')
            if (contact_institution and ('Scout software user' in contact_institution)):
                match_type = 'internal'
            score = None
            for res in match_obj['results']:
                for patient in res['patients']:
                    LOG.info('Looping in else, patient:{}'.format(patient['patient']['id']))
                    if (patient['patient']['id'] == patient_id):
                        score = patient['score']
                        match_patient = {'patient_id': m_patient['id'], 'score': score, 'patient': m_patient, 'node': res['node']}
                        matching_patients.append(match_patient)
        parsed_match['match_type'] = match_type
        parsed_match['patients'] = matching_patients
        parsed_matches.append(parsed_match)
    parsed_matches = sorted(parsed_matches, key=(lambda k: k['match_date']), reverse=True)
    return parsed_matches

Parse a list of matchmaker matches objects and returns
a readable list of matches to display in matchmaker matches view.

Args:
patient_id(str): id of a mme patient
match_objs(list): list of match objs returned by MME server for the patient
# match_objs looks like this:
[
{
'node' : { id : node_id , label: node_label},
'patients' : [
{ 'patient': {patient1_data} },
{ 'patient': {patient2_data} },
..
]
},
..
]

Returns:
parsed_matches(list): a list of parsed match objects


def from_authorized_user_info(cls, info, scopes=None):
    keys_needed = set(('refresh_token', 'client_id', 'client_secret'))
    missing = keys_needed.difference(six.iterkeys(info))
    if missing:
        raise ValueError('Authorized user info was not in the expected format, missing fields {}.'.format(', '.join(missing)))
    return Credentials(None, refresh_token=info['refresh_token'], token_uri=_GOOGLE_OAUTH2_TOKEN_ENDPOINT, scopes=scopes, client_id=info['client_id'], client_secret=info['client_secret'])

Creates a Credentials instance from parsed authorized user info.

Args:
info (Mapping[str, str]): The authorized user info in Google
format.
scopes (Sequence[str]): Optional list of scopes to include in the
credentials.

Returns:
google.oauth2.credentials.Credentials: The constructed
credentials.

Raises:
ValueError: If the info is not in the expected format.


def _draw_frame(self, framedata):
    original = self.read_frame()
    if (original is None):
        self.update_info(self.info_string(message='Finished.', frame=framedata))
        return
    if (self.original is not None):
        processed = self.process_frame(original.copy())
        if (self.cmap_original is not None):
            original = to_gray(original)
        elif (not is_color_image(original)):
            self.original.set_cmap('gray')
        self.original.set_data(original)
    else:
        processed = self.process_frame(original)
    if (self.cmap_processed is not None):
        processed = to_gray(processed)
    elif (not is_color_image(processed)):
        self.processed.set_cmap('gray')
    if self.annotations:
        self.annotate(framedata)
    self.processed.set_data(processed)
    self.update_info(self.info_string(frame=framedata))

Reads, processes and draws the frames.

If needed for color maps, conversions to gray scale are performed. In
case the images are no color images and no custom color maps are
defined, the colormap `gray` is applied.

This function is called by TimedAnimation.

Args:
framedata: The frame data.


def watchlist_movies(self, **kwargs):
    path = self._get_id_path('watchlist_movies')
    kwargs.update({'session_id': self.session_id})
    response = self._GET(path, kwargs)
    self._set_attrs_to_values(response)
    return response

Get the list of movies on an account watchlist.

Args:
page: (optional) Minimum 1, maximum 1000.
sort_by: (optional) 'created_at.asc' | 'created_at.desc'
language: (optional) ISO 639-1 code.

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


def dict_of_lists_add(dictionary, key, value):

    list_objs = dictionary.get(key, list())
    list_objs.append(value)
    dictionary[key] = list_objs

Add value to a list in a dictionary by key

Args:
dictionary (DictUpperBound): Dictionary to which to add values
key (Any): Key within dictionary
value (Any): Value to add to list in dictionary

Returns:
None


def add_ldap_group_link(self, cn, group_access, provider, **kwargs):
    path = ('/groups/%s/ldap_group_links' % self.get_id())
    data = {'cn': cn, 'group_access': group_access, 'provider': provider}
    self.manager.gitlab.http_post(path, post_data=data, **kwargs)

Add an LDAP group link.

Args:
cn (str): CN of the LDAP group
group_access (int): Minimum access level for members of the LDAP
group
provider (str): LDAP provider for the LDAP group
**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 is_chief(self):
    return self._is_chief

Return True if this is a chief supervisor.

Returns:
A bool.


def put_pixel(self, x: int, y: int, color: Tuple[int, int, int]) -> None:

        lib.TCOD_image_put_pixel(self.image_c, x, y, color)

Change a pixel on this Image.

Args:
x (int): X pixel of the Image.  Starting from the left at 0.
y (int): Y pixel of the Image.  Starting from the top at 0.
color (Union[Tuple[int, int, int], Sequence[int]]):
An (r, g, b) sequence or Color instance.


def IsAllSpent(self):
    for item in self.Items:
        if (item == CoinState.Confirmed):
            return False
    return True

Flag indicating if all balance is spend.

Returns:
bool:


def _get_block_publisher(self, state_hash):
    state_view = self._state_view_factory.create_view(state_hash)
    try:

        class BatchPublisher():

            def send(self, transactions):
                raise InvalidGenesisConsensusError('Consensus cannot send transactions during genesis.')
        consensus = ConsensusFactory.get_configured_consensus_module(NULL_BLOCK_IDENTIFIER, state_view)
        return consensus.BlockPublisher(BlockCache(self._block_store), state_view_factory=self._state_view_factory, batch_publisher=BatchPublisher(), data_dir=self._data_dir, config_dir=self._config_dir, validator_id=self._identity_signer.get_public_key().as_hex())
    except UnknownConsensusModuleError as e:
        raise InvalidGenesisStateError(e)

Returns the block publisher based on the consensus module set by the
"sawtooth_settings" transaction family.

Args:
state_hash (str): The current state root hash for reading settings.

Raises:
InvalidGenesisStateError: if any errors occur getting the
BlockPublisher.


def mat2euler(rmat, axes="sxyz"):

    try:
        firstaxis, parity, repetition, frame = _AXES2TUPLE[axes.lower()]
    except (AttributeError, KeyError):
        firstaxis, parity, repetition, frame = axes

    i = firstaxis
    j = _NEXT_AXIS[i + parity]
    k = _NEXT_AXIS[i - parity + 1]

    M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3]
    if repetition:
        sy = math.sqrt(M[i, j] * M[i, j] + M[i, k] * M[i, k])
        if sy > EPS:
            ax = math.atan2(M[i, j], M[i, k])
            ay = math.atan2(sy, M[i, i])
            az = math.atan2(M[j, i], -M[k, i])
        else:
            ax = math.atan2(-M[j, k], M[j, j])
            ay = math.atan2(sy, M[i, i])
            az = 0.0
    else:
        cy = math.sqrt(M[i, i] * M[i, i] + M[j, i] * M[j, i])
        if cy > EPS:
            ax = math.atan2(M[k, j], M[k, k])
            ay = math.atan2(-M[k, i], cy)
            az = math.atan2(M[j, i], M[i, i])
        else:
            ax = math.atan2(-M[j, k], M[j, j])
            ay = math.atan2(-M[k, i], cy)
            az = 0.0

    if parity:
        ax, ay, az = -ax, -ay, -az
    if frame:
        ax, az = az, ax
    return vec((ax, ay, az))

Converts given rotation matrix to euler angles in radian.

Args:
rmat: 3x3 rotation matrix
axes: One of 24 axis sequences as string or encoded tuple

Returns:
converted euler angles in radian vec3 float


def import_module(name):
    parts = name.split('.')
    path = None
    module_name = ''
    fhandle = None
    for (index, part) in enumerate(parts):
        module_name = (part if (index == 0) else ('%s.%s' % (module_name, part)))
        path = ([path] if (path is not None) else path)
        try:
            (fhandle, path, descr) = imp.find_module(part, path)
            if (module_name in sys.modules):
                mod = sys.modules[module_name]
            else:
                mod = imp.load_module(module_name, fhandle, path, descr)
        finally:
            if fhandle:
                fhandle.close()
    return mod

Imports a module into the current runtime environment

This function emulates the Python import system that allows for
importing full path modules.  It will break down the module and
import each part (or skip if it is already loaded in cache).

Args:
name (str): The name of the module to import.  This should be
the full path of the module

Returns:
The module that was imported


def _login(self, max_tries=2):

    if not self.current_url.startswith(_KindleCloudReaderBrowser._SIGNIN_URL):
      raise BrowserError(
          'Current url "%s" is not a signin url ("%s")' %
          (self.current_url, _KindleCloudReaderBrowser._SIGNIN_URL))

    email_field_loaded = lambda br: br.find_elements_by_id('ap_email')
    self._wait().until(email_field_loaded)
    tries = 0
    while tries < max_tries:

      email_elem = self.find_element_by_id('ap_email')
      email_elem.clear()
      email_elem.send_keys(self._uname)

      pword_elem = self.find_element_by_id('ap_password')
      pword_elem.clear()
      pword_elem.send_keys(self._pword)

      def creds_entered(_):

        email_ok = email_elem.get_attribute('value') == self._uname
        pword_ok = pword_elem.get_attribute('value') == self._pword
        return email_ok and pword_ok

      kcr_page_loaded = lambda br: br.title == u'Kindle Cloud Reader'
      try:
        self._wait(5).until(creds_entered)
        self.find_element_by_id('signInSubmit-input').click()
        self._wait(5).until(kcr_page_loaded)
      except TimeoutException:
        tries += 1
      else:
        return

    raise LoginError

Logs in to Kindle Cloud Reader.

Args:
max_tries: The maximum number of login attempts that will be made.

Raises:
BrowserError: If method called when browser not at a signin URL.
LoginError: If login unsuccessful after `max_tries` attempts.


def segment_similarity(A, B, T=CLOSE_DISTANCE_THRESHOLD):
    l_a = len(A.points)
    l_b = len(B.points)
    idx = index.Index()
    dex = 0
    for i in range((l_a - 1)):
        idx.insert(dex, bounding_box_from(A.points, i, (i + 1), T), obj=[A.points[i], A.points[(i + 1)]])
        dex = (dex + 1)
    prox_acc = []
    for i in range((l_b - 1)):
        ti = B.points[i].gen2arr()
        ti1 = B.points[(i + 1)].gen2arr()
        bb = bounding_box_from(B.points, i, (i + 1), T)
        intersects = idx.intersection(bb, objects=True)
        n_prox = []
        i_prox = 0
        a = 0
        for x in intersects:
            a = (a + 1)
            pi = x.object[0].gen2arr()
            pi1 = x.object[1].gen2arr()
            prox = line_similarity(ti, ti1, pi, pi1, T)
            i_prox = (i_prox + prox)
            n_prox.append(prox)
        if (a != 0):
            prox_acc.append((i_prox / a))
        else:
            prox_acc.append(0)
    return (np.mean(prox_acc), prox_acc)

Computes the similarity between two segments

Args:
A (:obj:`Segment`)
B (:obj:`Segment`)
Returns:
float: between 0 and 1. Where 1 is very similar and 0 is completely different


def _begin_connection_action(self, action):

        conn_id = action.data['connection_id']
        int_id = action.data['internal_id']
        callback = action.data['callback']

        if self._get_connection_state(conn_id) != self.Disconnected:
            print(self._connections[conn_id])
            callback(conn_id, self.id, False, 'Connection ID is already in use for another connection')
            return

        if self._get_connection_state(int_id) != self.Disconnected:
            callback(conn_id, self.id, False, 'Internal ID is already in use for another connection')
            return

        conn_data = {
            'state': self.Connecting,
            'microstate': None,
            'conn_id': conn_id,
            'int_id': int_id,
            'callback': callback,
            'timeout': action.timeout,
            'context': action.data['context']
        }

        self._connections[conn_id] = conn_data
        self._int_connections[int_id] = conn_data

Begin a connection attempt

Args:
action (ConnectionAction): the action object describing what we are
connecting to


def func_callsig(func, with_name=True):
    import inspect
    argspec = inspect.getargspec(func)
    (args, varargs, varkw, defaults) = argspec
    callsig = inspect.formatargspec(*argspec[0:3])
    if with_name:
        callsig = (get_callable_name(func) + callsig)
    return callsig

String of function call signature

Args:
func (function): live python function

Returns:
str: callsig

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

Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import *  # NOQA
>>> func = func_str
>>> callsig = func_callsig(func)
>>> result = str(callsig)
>>> print(result)
func_str(func, args, kwargs, type_aliases, packed, packkw, truncate)


def update_(self, conf_dict, conf_arg=True):

        for section, secdict in conf_dict.items():
            self[section].update_(secdict, conf_arg)

Update values of configuration options with dict.

Args:
conf_dict (dict): dict of dict indexed with section and option
names.
conf_arg (bool): if True, only options that can be set in a config
file are updated.


def rollapply(data, window, fn):

    res = data.copy()
    res[:] = np.nan
    n = len(data)

    if window > n:
        return res

    for i in range(window - 1, n):
        res.iloc[i] = fn(data.iloc[i - window + 1:i + 1])

    return res

Apply a function fn over a rolling window of size window.

Args:
* data (Series or DataFrame): Series or DataFrame
* window (int): Window size
* fn (function): Function to apply over the rolling window.
For a series, the return value is expected to be a single
number. For a DataFrame, it shuold return a new row.

Returns:
* Object of same dimensions as data


def WriteScanContext(self, scan_context, scan_step=None):
    if (scan_step is not None):
        print('Scan step: {0:d}'.format(scan_step))
    print('Source type\t\t: {0:s}'.format(scan_context.source_type))
    print('')
    scan_node = scan_context.GetRootScanNode()
    self.WriteScanNode(scan_context, scan_node)
    print('')

Writes the source scanner context to stdout.

Args:
scan_context (SourceScannerContext): the source scanner context.
scan_step (Optional[int]): the scan step, where None represents no step.


def get(app: web.Application, feature_type: Type[Any]=None, key: Hashable=None) -> Any:
    key = (key or feature_type)
    if (not key):
        raise AssertionError('No feature identifier provided')
    try:
        found = app[FEATURES_KEY][key]
    except KeyError:
        raise KeyError(f'No feature found for "{key}"')
    if (feature_type and (not isinstance(found, feature_type))):
        raise AssertionError(f'Found {found} did not match type "{feature_type}"')
    return found

Finds declared feature.
Identification is done based on feature type and key.

Args:
app (web.Application):
The current Aiohttp application.

feature_type (Type[Any]):
The Python type of the desired feature.
If specified, it will be checked against the found feature.

key (Hashable):
A specific identifier for the desired feature.
Defaults to `feature_type`

Returns:
Any: The feature found for the combination of `feature_type` and `key`


def write(self, index, value, name=None):
    return self._implementation.write(index, value, name=name)

Write `value` into index `index` of the TensorArray.

Args:
index: 0-D.  int32 scalar with the index to write to.
value: N-D.  Tensor of type `dtype`.  The Tensor to write to this index.
name: A name for the operation (optional).

Returns:
A new TensorArray object with flow that ensures the write occurs.
Use this object for all subsequent operations.

Raises:
ValueError: if there are more writers than specified.