def get_environment_details(zone, environment):
    default_context = google.datalab.Context.default()
    url = (Api._ENDPOINT + (Api._ENVIRONMENTS_PATH_FORMAT % (default_context.project_id, zone, environment)))
    return google.datalab.utils.Http.request(url, credentials=default_context.credentials)

Issues a request to Composer to get the environment details.

Args:
zone: GCP zone of the composer environment
environment: name of the Composer environment
Returns:
A parsed result object.
Raises:
Exception if there is an error performing the operation.


def __matches(s1, s2, ngrams_fn, n=3):

    ngrams1, ngrams2 = set(ngrams_fn(s1, n=n)), set(ngrams_fn(s2, n=n))
    return ngrams1.intersection(ngrams2)

Returns the n-grams that match between two sequences

See also: SequenceMatcher.get_matching_blocks

Args:
s1: a string
s2: another string
n: an int for the n in n-gram

Returns:
set:


def roll_to_business_day(self, date_tensor, roll_convention):
    if roll_convention == constants.BusinessDayConvention.NONE:
        return date_tensor
    rolled_ordinals_table = self._compute_rolled_dates_table(roll_convention)
    ordinals_with_offset = date_tensor.ordinal() - self._ordinal_offset + 1
    rolled_ordinals = self._gather(rolled_ordinals_table, ordinals_with_offset)
    with tf.control_dependencies(self._assert_ordinals_in_bounds(rolled_ordinals)):
        return dt.from_ordinals(rolled_ordinals, validate=False)

Rolls the given dates to business dates according to given convention.

Args:
date_tensor: DateTensor of dates to roll from.
roll_convention: BusinessDayConvention. Determines how to roll a date that
falls on a holiday.

Returns:
The resulting DateTensor.


def __init__(self, flow_obj, parent_runner=None, runner_args=None,
               token=None):

    self.token = token or flow_obj.token
    self.parent_runner = parent_runner

    if parent_runner is not None:
      self.queue_manager = parent_runner.queue_manager
    else:

      self.queue_manager = queue_manager.QueueManager(token=self.token)
      self.queue_manager.FreezeTimestamp()

    self.queued_replies = []

    self.outbound_lock = threading.Lock()
    self.flow_obj = flow_obj

    if runner_args is not None:
      self.runner_args = runner_args
      self.session_id = self.GetNewSessionID()
      self.flow_obj.urn = self.session_id

      self.context = self.InitializeContext(runner_args)
      self.flow_obj.context = self.context
      self.context.session_id = self.session_id

    else:

      self.context = self.flow_obj.context

      self.runner_args = self.flow_obj.runner_args

    self.flow_obj.urn = self.session_id = self.context.session_id

    self.sent_replies = []

Constructor for the Flow Runner.

Args:
flow_obj: The flow object this runner will run states for.
parent_runner: The parent runner of this runner.
runner_args: A FlowRunnerArgs() instance containing initial values. If not
specified, we use the runner_args from the flow_obj.
token: An instance of access_control.ACLToken security token.


def _PrintCheckDependencyStatus(
      self, dependency, result, status_message, verbose_output=True):

    if not result or dependency.is_optional:
      if dependency.is_optional:
        status_indicator = '[OPTIONAL]'
      else:
        status_indicator = '[FAILURE]'

      print('{0:s}\t{1:s}'.format(status_indicator, status_message))

    elif verbose_output:
      print('[OK]\t\t{0:s}'.format(status_message))

Prints the check dependency status.

Args:
dependency (DependencyDefinition): dependency definition.
result (bool): True if the Python module is available and conforms to
the minimum required version, False otherwise.
status_message (str): status message.
verbose_output (Optional[bool]): True if output should be verbose.


def switch_to_line_in(self, source=None):

        if source:
            uid = source.uid
        else:
            uid = self.uid

        self.avTransport.SetAVTransportURI([
            ('InstanceID', 0),
            ('CurrentURI', 'x-rincon-stream:{0}'.format(uid)),
            ('CurrentURIMetaData', '')
        ])

Switch the speaker's input to line-in.

Args:
source (SoCo): The speaker whose line-in should be played.
Default is line-in from the speaker itself.


def set(self, key, samples, sampling_rate):
    if (not np.issubdtype(samples.dtype, np.floating)):
        raise ValueError('Samples are required as np.float32!')
    if (len(samples.shape) > 1):
        raise ValueError('Only single channel supported!')
    self.raise_error_if_not_open()
    if (key in self._file):
        del self._file[key]
    samples = (samples * MAX_INT16_VALUE).astype(np.int16)
    dset = self._file.create_dataset(key, data=samples)
    dset.attrs[SAMPLING_RATE_ATTR] = sampling_rate

Set the samples and sampling-rate for the given key.
Existing data will be overwritten.
The samples have to have ``np.float32`` datatype and values in
the range of -1.0 and 1.0.

Args:
key (str): A key to store the data for.
samples (numpy.ndarray): 1-D array of audio samples (np.float32).
sampling_rate (int): The sampling-rate of the audio samples.

Note:
The container has to be opened in advance.


def setValues(self, values):

        if isinstance(values, dict):
            indices, values = list(zip(*values.items()))
            indices = Utils.toTupleArray(indices)
            if any(isinstance(value, basestring) for value in values):
                values = list(map(str, values))
                self._impl.setValuesTaStr(indices, values, len(values))
            elif all(isinstance(value, Real) for value in values):
                values = list(map(float, values))
                self._impl.setValuesTaDbl(indices, values, len(values))
            else:
                raise TypeError
        elif isinstance(values, (list, tuple)):
            if any(isinstance(value, basestring) for value in values):
                values = list(map(str, values))
                self._impl.setValuesStr(values, len(values))
            elif all(isinstance(value, Real) for value in values):
                values = list(map(float, values))
                self._impl.setValuesDbl(values, len(values))
            else:
                raise TypeError
        else:
            if np is not None and isinstance(values, np.ndarray):
                self.setValues(DataFrame.fromNumpy(values).toList())
                return
            Entity.setValues(self, values)

Assign the values (string or float) to the parameter instances with the
specified indices, equivalent to the AMPL code:

.. code-block:: ampl

let {i in indices} par[i] := values[i];

Args:
values: list, dictionary or :class:`~amplpy.DataFrame` with the
indices and the values to be set.

Raises:
TypeError: If called on a scalar parameter.


def Print(x, data, message, **kwargs):

  return PrintOperation(x, data, message, **kwargs).outputs[0]

Call tf.Print.

Args:
x: a Tensor.
data: a list of Tensor
message: a string
**kwargs: keyword arguments to tf.Print
Returns:
a Tensor which is identical in value to x


def imrotate(img, angle, center=None, scale=1.0, border_value=0, auto_bound=False):
    if ((center is not None) and auto_bound):
        raise ValueError('`auto_bound` conflicts with `center`')
    (h, w) = img.shape[:2]
    if (center is None):
        center = (((w - 1) * 0.5), ((h - 1) * 0.5))
    assert isinstance(center, tuple)
    matrix = cv2.getRotationMatrix2D(center, (- angle), scale)
    if auto_bound:
        cos = np.abs(matrix[(0, 0)])
        sin = np.abs(matrix[(0, 1)])
        new_w = ((h * sin) + (w * cos))
        new_h = ((h * cos) + (w * sin))
        matrix[(0, 2)] += ((new_w - w) * 0.5)
        matrix[(1, 2)] += ((new_h - h) * 0.5)
        w = int(np.round(new_w))
        h = int(np.round(new_h))
    rotated = cv2.warpAffine(img, matrix, (w, h), borderValue=border_value)
    return rotated

Rotate an image.

Args:
img (ndarray): Image to be rotated.
angle (float): Rotation angle in degrees, positive values mean
clockwise rotation.
center (tuple): Center of the rotation in the source image, by default
it is the center of the image.
scale (float): Isotropic scale factor.
border_value (int): Border value.
auto_bound (bool): Whether to adjust the image size to cover the whole
rotated image.

Returns:
ndarray: The rotated image.


def memcache_get(self, key, for_cas=False, namespace=None, use_cache=False,
                   deadline=None):

    if not isinstance(key, basestring):
      raise TypeError('key must be a string; received %r' % key)
    if not isinstance(for_cas, bool):
      raise TypeError('for_cas must be a bool; received %r' % for_cas)
    if namespace is None:
      namespace = namespace_manager.get_namespace()
    options = (for_cas, namespace, deadline)
    batcher = self.memcache_get_batcher
    if use_cache:
      return batcher.add_once(key, options)
    else:
      return batcher.add(key, options)

An auto-batching wrapper for memcache.get() or .get_multi().

Args:
key: Key to set.  This must be a string; no prefix is applied.
for_cas: If True, request and store CAS ids on the Context.
namespace: Optional namespace.
deadline: Optional deadline for the RPC.

Returns:
A Future (!) whose return value is the value retrieved from
memcache, or None.


def from_func_graph(name: Union[str, bytes], graph: func_graph_module.FuncGraph, attrs: Dict[str, attr_value_pb2.AttrValue], function_type: Optional[function_type_lib.FunctionType]=None, overwrite: bool=False) -> AtomicFunction:
    if attrs and attributes_lib.IMPLEMENTS in attrs:
        has_resource_vars = any((inp.dtype == dtypes.resource for inp in graph.inputs))
        captured_inputs = graph.external_captures + graph.deferred_external_captures
        assert not any((has_resource_vars, captured_inputs)), 'Function {name} has "{attr}={value}" attribute and thus can not depend on any tensors outside of its signature or modify variables. \n\nNote: variables are always captured and cause function re-tracing for every variable called.\n  inputs: {inputs}\n  captures: {captured}\n\nTo pass a variable to such function use  use variable.read_value().'.format(name=graph.name, attr=attributes_lib.IMPLEMENTS, value=attrs[attributes_lib.IMPLEMENTS], inputs=graph.inputs, captured=captured_inputs)
    input_ops = set((arg.op for arg in graph.inputs))
    operations = [op for op in graph.get_operations() if op not in input_ops]
    graph_output_names = graph._output_names
    if graph_output_names is not None and all((ops.tensor_id(t) in graph_output_names for t in graph.outputs)):
        output_names = [compat.as_bytes(graph_output_names[ops.tensor_id(t)]) for t in graph.outputs]
        if len(set(output_names)) != len(output_names):
            output_names = []
    else:
        output_names = []
    with graph._c_graph.get() as c_graph:
        fn = pywrap_tf_session.TF_GraphToFunction_wrapper(c_graph, compat.as_str(name), False, [o._c_op for o in operations], [t._as_tf_output() for t in graph.inputs], [t._as_tf_output() for t in graph.outputs], output_names, [o._c_op for o in graph.control_outputs], [], None, compat.as_str(''))
    attrs = attributes_lib.parse_func_attrs(attrs or {})
    for attr_name, attr_value in attrs.items():
        serialized = attr_value.SerializeToString()
        pywrap_tf_session.TF_FunctionSetAttrValueProto(fn, compat.as_str(attr_name), serialized)
    name = compat.as_bytes(name)
    bound_context = context.context()
    if overwrite and bound_context.has_function(name):
        bound_context.remove_function(name)
    bound_context.add_c_function(fn)
    pywrap_tf_session.TF_DeleteFunction(fn)
    call_options = CallOptions(collective_manager_ids_used=getattr(graph, 'collective_manager_ids_used', []), control_captures=graph.function_captures.control, is_stateful=any((op._is_stateful for op in operations)))
    if not function_type:
        function_type = function_type_utils.derive_from_graph(graph)
    return AtomicFunction(name, bound_context, function_type, list(graph._functions.values()), call_options, cached_graph=graph)

Initializes an AtomicFunction from FuncGraph.

Args:
name: str, the name for the created function.
graph: Graph, the graph containing the operations in the function
attrs: dict mapping names of attributes to their AttrValue values
function_type: known FunctionType to use, otherwise one is derived.
overwrite: overwrites function definition in the current context if needed

Returns:
An AtomicFunction instance.


def _create_produce_requests(self, collated):
    requests = {}
    for (node_id, batches) in six.iteritems(collated):
        requests[node_id] = self._produce_request(node_id, self.config['acks'], self.config['request_timeout_ms'], batches)
    return requests

Transfer the record batches into a list of produce requests on a
per-node basis.

Arguments:
collated: {node_id: [RecordBatch]}

Returns:
dict: {node_id: ProduceRequest} (version depends on api_version)


def restore_site_properties(self, site_property='ff_map', filename=None):
    if (not (self.control_params['filetype'] == 'pdb')):
        raise ValueError()
    filename = (filename or self.control_params['output'])
    bma = BabelMolAdaptor.from_file(filename, 'pdb')
    pbm = pb.Molecule(bma._obmol)
    assert (len(pbm.residues) == sum([x['number'] for x in self.param_list]))
    packed_mol = self.convert_obatoms_to_molecule(pbm.residues[0].atoms, residue_name=pbm.residues[0].name, site_property=site_property)
    for resid in pbm.residues[1:]:
        mol = self.convert_obatoms_to_molecule(resid.atoms, residue_name=resid.name, site_property=site_property)
        for site in mol:
            packed_mol.append(site.species, site.coords, properties=site.properties)
    return packed_mol

Restore the site properties for the final packed molecule.

Args:
site_property (str):
filename (str): path to the final packed molecule.

Returns:
Molecule


def framebuffer(self, color_attachments=(), depth_attachment=None) -> 'Framebuffer':

        if type(color_attachments) is Texture or type(color_attachments) is Renderbuffer:
            color_attachments = (color_attachments,)

        ca_mglo = tuple(x.mglo for x in color_attachments)
        da_mglo = None if depth_attachment is None else depth_attachment.mglo

        res = Framebuffer.__new__(Framebuffer)
        res.mglo, res._size, res._samples, res._glo = self.mglo.framebuffer(ca_mglo, da_mglo)
        res._color_attachments = tuple(color_attachments)
        res._depth_attachment = depth_attachment
        res.ctx = self
        res.extra = None
        return res

A :py:class:`Framebuffer` is a collection of buffers that can be used as the destination for rendering.
The buffers for Framebuffer objects reference images from either Textures or Renderbuffers.

Args:
color_attachments (list): A list of :py:class:`Texture` or :py:class:`Renderbuffer` objects.
depth_attachment (Renderbuffer or Texture): The depth attachment.

Returns:
:py:class:`Framebuffer` object


def extract_paths(self, paths, ignore_nopath):
    try:
        super().extract_paths(paths=paths, ignore_nopath=ignore_nopath)
    except ExtractPathError as err:
        LOGGER.debug('%s: failed extracting files: %s', self.vm.name(), err.message)
        if self._has_guestfs:
            self.extract_paths_dead(paths, ignore_nopath)
        else:
            raise

Extract the given paths from the domain

Attempt to extract all files defined in ``paths`` with the method
defined in :func:`~lago.plugins.vm.VMProviderPlugin.extract_paths`,
if it fails, and `guestfs` is available it will try extracting the
files with guestfs.

Args:
paths(list of tuples): files to extract in
`[(src1, dst1), (src2, dst2)...]` format.
ignore_nopath(boolean): if True will ignore none existing paths.

Returns:
None

Raises:
:exc:`~lago.plugins.vm.ExtractPathNoPathError`: if a none existing
path was found on the VM, and `ignore_nopath` is False.
:exc:`~lago.plugins.vm.ExtractPathError`: on all other failures.


def get(self, key):

        lock.acquire()
        try:
            if key not in self:
                return None

            current_time = time.time()
            if self[key].expire > current_time:
                return self[key].value

            deletes = []
            for k, val in self.items():
                if val.expire <= current_time:
                    deletes.append(k)
            for k in deletes:
                del self[k]

            return None
        finally:
            lock.release()

Get an object from the cache

Arguments:
key (str): Cache key

Returns:
Cached object


def is_valid_isbn(isbn):

    length = len(isbn)

    if length == 10:
        return is_isbn10_valid(isbn)
    elif length == 13:
        return is_isbn13_valid(isbn)

    return False

Validate given `isbn`. Wrapper for :func:`is_isbn10_valid`/
:func:`is_isbn13_valid`.

Args:
isbn (str/list): ISBN number as string or list of digits.

Note:
Function doesn't require `isbn` type to be specified (it can be both
10/13 isbn's versions).

Returns:
bool: ``True`` if ISBN is valid.


def __init__(self, submission_id, submissions, storage_bucket):

    self.submission_id = submission_id
    self.storage_bucket = storage_bucket
    self.type = None
    self.submission = None
    if submission_id in submissions.attacks:
      self.type = TYPE_NONTARGETED
      self.submission = submissions.attacks[submission_id]
    elif submission_id in submissions.targeted_attacks:
      self.type = TYPE_TARGETED
      self.submission = submissions.targeted_attacks[submission_id]
    elif submission_id in submissions.defenses:
      self.type = TYPE_DEFENSE
      self.submission = submissions.defenses[submission_id]
    else:
      raise WorkerError(
          'Submission with ID "{0}" not found'.format(submission_id))
    self.submission_dir = None
    self.extracted_submission_dir = None

Initializes ExecutableSubmission.

Args:
submission_id: ID of the submissions
submissions: instance of CompetitionSubmissions with all submissions
storage_bucket: storage bucket where all submissions are stored

Raises:
WorkerError: if submission was not found


def prune_unused_nodes(meta_graph, signature_def):
    graph = tf_v1.Graph()
    with graph.as_default():
        tf_v1.train.import_meta_graph(meta_graph, input_map={}, import_scope='')
        used_node_names = set()
        for (_, tensor_def) in signature_def.outputs.items():
            output_tensor = graph.get_tensor_by_name(tensor_def.name)
            mark_backward(output_tensor, used_node_names)
        node_filter_in_list = []
        for node in meta_graph.graph_def.node:
            if ((node.name in used_node_names) or (node.op == 'VarHandleOp')):
                node_filter_in_list.append(node)
        del meta_graph.graph_def.node[:]
        meta_graph.graph_def.node.extend(node_filter_in_list)
    del graph

Function to prune unused ops given a signature def.

This function does a graph traversal through from all outputs as
defined in the signature_def to collect all used nodes. Then, any
nodes which are unused can be discarded. This is useful for graph which are
executing eagerly or on TPUs.

Args:
meta_graph: The input/output MetaGraphDef for which we wish to prune.
signature_def: A SignatureDef which specifies the outputs from which we wish
to start graph traversal.


def albedo(self, value=999.0):
    if (value is not None):
        try:
            value = float(value)
        except ValueError:
            raise ValueError('value {} need to be of type float for field `albedo`'.format(value))
    self._albedo = value

Corresponds to IDD Field `albedo`

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

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


def write_auth(msg_type, profile_name, auth, cfg):
    key_fmt = ((profile_name + '_') + msg_type)
    pwd = []
    for (k, v) in CONFIG[msg_type]['auth'].items():
        pwd.append(auth[k])
    if (len(pwd) > 1):
        cfg.pwd[key_fmt] = ' :: '.join(pwd)
    else:
        cfg.pwd[key_fmt] = pwd[0]

Write the settings into the auth portion of the cfg.

Args:
:msg_type: (str) message type to create config entry.
:profile_name: (str) name of the profile entry
:auth: (dict) auth parameters
:cfg: (jsonconfig.Config) config instance.


def set_global_step(self, new_global_step, name=None):
    return gen_data_flow_ops.accumulator_set_global_step(self._accumulator_ref, math_ops.cast(ops.convert_to_tensor(new_global_step), _dtypes.int64), name=name)

Sets the global time step of the accumulator.

The operation logs a warning if we attempt to set to a time step that is
lower than the accumulator's own time step.

Args:
new_global_step: Value of new time step. Can be a variable or a constant
name: Optional name for the operation.

Returns:
Operation that sets the accumulator's time step.


def _trigger(self):

        self._completed.set()
        for callback in self._callbacks:
            callback(self)

Trigger all callbacks registered to this Future.

This method is called internally by the batch once the batch
completes.

Args:
message_id (str): The message ID, as a string.


def get_corner(self, time):
    if (self.start_time <= time <= self.end_time):
        diff = (time - self.start_time)
        return (self.i[diff][(0, 0)], self.j[diff][(0, 0)])
    else:
        return ((- 1), (- 1))

Gets the corner array indices of the STObject at a given time that corresponds
to the upper left corner of the bounding box for the STObject.

Args:
time: time at which the corner is being extracted.

Returns:
corner index.


def decorate(self, name_or_func):

    if os.environ.get("SC2_NO_STOPWATCH"):
      return name_or_func if callable(name_or_func) else lambda func: func

    def decorator(name, func):
      @functools.wraps(func)
      def _stopwatch(*args, **kwargs):
        with self(name):
          return func(*args, **kwargs)
      return _stopwatch
    if callable(name_or_func):
      return decorator(name_or_func.__name__, name_or_func)
    else:
      return lambda func: decorator(name_or_func, func)

Decorate a function/method to check its timings.

To use the function's name:
@sw.decorate
def func():
pass

To name it explicitly:
@sw.decorate("name")
def random_func_name():
pass

Args:
name_or_func: the name or the function to decorate.

Returns:
If a name is passed, returns this as a decorator, otherwise returns the
decorated function.


def _PrintTSKPartitionIdentifiersOverview(
      self, volume_system, volume_identifiers):

    header = 'The following partitions were found:\n'
    self._output_writer.Write(header)

    column_names = ['Identifier', 'Offset (in bytes)', 'Size (in bytes)']
    table_view = views.CLITabularTableView(column_names=column_names)

    for volume_identifier in sorted(volume_identifiers):
      volume = volume_system.GetVolumeByIdentifier(volume_identifier)
      if not volume:
        raise errors.SourceScannerError(
            'Partition missing for identifier: {0:s}.'.format(
                volume_identifier))

      volume_extent = volume.extents[0]
      volume_offset = '{0:d} (0x{0:08x})'.format(volume_extent.offset)
      volume_size = self._FormatHumanReadableSize(volume_extent.size)

      table_view.AddRow([volume.identifier, volume_offset, volume_size])

    self._output_writer.Write('\n')
    table_view.Write(self._output_writer)
    self._output_writer.Write('\n')

Prints an overview of TSK partition identifiers.

Args:
volume_system (dfvfs.TSKVolumeSystem): volume system.
volume_identifiers (list[str]): allowed volume identifiers.

Raises:
SourceScannerError: if a volume cannot be resolved from the volume
identifier.


def crop(img, i, j, h, w):
    if (not _is_pil_image(img)):
        raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
    return img.crop((j, i, (j + w), (i + h)))

Crop the given PIL Image.

Args:
img (PIL Image): Image to be cropped.
i (int): i in (i,j) i.e coordinates of the upper left corner.
j (int): j in (i,j) i.e coordinates of the upper left corner.
h (int): Height of the cropped image.
w (int): Width of the cropped image.

Returns:
PIL Image: Cropped image.


def is_fit_to_structure(self, structure, tol=0.01):
    return ((self - self.fit_to_structure(structure)) < tol).all()

Tests whether a tensor is invariant with respect to the
symmetry operations of a particular structure by testing
whether the residual of the symmetric portion is below a
tolerance

Args:
structure (Structure): structure to be fit to
tol (float): tolerance for symmetry testing


def toco_convert(input_data, input_tensors, output_tensors, *args, **kwargs):
    return convert_graphdef(input_data, input_tensors, output_tensors, *args, **kwargs)

Convert a TensorFlow GraphDef to TFLite.

This function is deprecated. Please use `tf.lite.TFLiteConverter` API instead.
Conversion can be customized by providing arguments that are forwarded to
`build_model_flags` and `build_conversion_flags` (see documentation for
details).
Args:
input_data: Input data (i.e. often `sess.graph_def`).
input_tensors: List of input tensors. Type and shape are computed using
`foo.shape` and `foo.dtype`.
output_tensors: List of output tensors (only .name is used from this).
*args: See `build_model_flags` and `build_conversion_flags`.
**kwargs: See `build_model_flags` and `build_conversion_flags`.

Returns:
The converted TensorFlow Lite model in a bytes array.

Raises:
Defined in `convert`.


def proc_val(key, val):

        float_keys = ('etot_conv_thr','forc_conv_thr','conv_thr','Hubbard_U','Hubbard_J0','defauss',
                      'starting_magnetization',)

        int_keys = ('nstep','iprint','nberrycyc','gdir','nppstr','ibrav','nat','ntyp','nbnd','nr1',
                    'nr2','nr3','nr1s','nr2s','nr3s','nspin','nqx1','nqx2','nqx3','lda_plus_u_kind',
                    'edir','report','esm_nfit','space_group','origin_choice','electron_maxstep',
                    'mixing_ndim','mixing_fixed_ns','ortho_para','diago_cg_maxiter','diago_david_ndim',
                    'nraise','bfgs_ndim','if_pos','nks','nk1','nk2','nk3','sk1','sk2','sk3','nconstr')

        bool_keys = ('wf_collect','tstress','tprnfor','lkpoint_dir','tefield','dipfield','lelfield',
                     'lorbm','lberry','lfcpopt','monopole','nosym','nosym_evc','noinv','no_t_rev',
                     'force_symmorphic','use_all_frac','one_atom_occupations','starting_spin_angle',
                     'noncolin','x_gamma_extrapolation','lda_plus_u','lspinorb','london',
                     'ts_vdw_isolated','xdm','uniqueb','rhombohedral','realxz','block',
                     'scf_must_converge','adaptive_thr','diago_full_acc','tqr','remove_rigid_rot',
                     'refold_pos')

        def smart_int_or_float(numstr):
            if numstr.find(".") != -1 or numstr.lower().find("e") != -1:
                return float(numstr)
            else:
                return int(numstr)

        try:
            if key in bool_keys:
                if val.lower() == ".true.":
                    return True
                elif val.lower() == ".false.":
                    return False
                else:
                    raise ValueError(key + " should be a boolean type!")

            if key in float_keys:
                return float(re.search(r"^-?\d*\.?\d*d?-?\d*", val.lower()).group(0).replace("d", "e"))

            if key in int_keys:
                return int(re.match(r"^-?[0-9]+", val).group(0))

        except ValueError:
            pass

        try:
            val = val.replace("d","e")
            return smart_int_or_float(val)
        except ValueError:
            pass

        if "true" in val.lower():
            return True
        if "false" in val.lower():
            return False

        m = re.match(r"^[\"|'](.+)[\"|']$", val)
        if m:
            return m.group(1)

Static helper method to convert PWINPUT parameters to proper type, e.g.,
integers, floats, etc.

Args:
key: PWINPUT parameter key
val: Actual value of PWINPUT parameter.


def add_sources_argument(cls, group, allow_filters=True, prefix=None, add_root_paths=False):
    prefix = (prefix or cls.argument_prefix)
    group.add_argument(('--%s-sources' % prefix), action='store', nargs='+', dest=('%s_sources' % prefix.replace('-', '_')), help=('%s source files to parse' % prefix))
    if allow_filters:
        group.add_argument(('--%s-source-filters' % prefix), action='store', nargs='+', dest=('%s_source_filters' % prefix.replace('-', '_')), help=('%s source files to ignore' % prefix))
    if add_root_paths:
        group.add_argument(('--%s-source-roots' % prefix), action='store', nargs='+', dest=('%s_source_roots' % prefix.replace('-', '_')), help=('%s source root directories allowing files to be referenced relatively to those' % prefix))

Subclasses may call this to add sources and source_filters arguments.

Args:
group: arparse.ArgumentGroup, the extension argument group
allow_filters: bool,  Whether the extension wishes to expose a
source_filters argument.
prefix: str, arguments have to be namespaced.


def _save_and_log_checkpoint(self, actor):

        actor_id = self._worker.actor_id
        checkpoint_info = self._worker.actor_checkpoint_info[actor_id]
        checkpoint_info.num_tasks_since_last_checkpoint += 1
        now = int(1000 * time.time())
        checkpoint_context = ray.actor.CheckpointContext(
            actor_id, checkpoint_info.num_tasks_since_last_checkpoint,
            now - checkpoint_info.last_checkpoint_timestamp)

        if actor.should_checkpoint(checkpoint_context):
            try:
                now = int(1000 * time.time())
                checkpoint_id = (self._worker.raylet_client.
                                 prepare_actor_checkpoint(actor_id))
                checkpoint_info.checkpoint_ids.append(checkpoint_id)
                actor.save_checkpoint(actor_id, checkpoint_id)
                if (len(checkpoint_info.checkpoint_ids) >
                        ray._config.num_actor_checkpoints_to_keep()):
                    actor.checkpoint_expired(
                        actor_id,
                        checkpoint_info.checkpoint_ids.pop(0),
                    )
                checkpoint_info.num_tasks_since_last_checkpoint = 0
                checkpoint_info.last_checkpoint_timestamp = now
            except Exception:

                traceback_str = ray.utils.format_error_message(
                    traceback.format_exc())
                ray.utils.push_error_to_driver(
                    self._worker,
                    ray_constants.CHECKPOINT_PUSH_ERROR,
                    traceback_str,
                    driver_id=self._worker.task_driver_id)

Save an actor checkpoint if necessary and log any errors.

Args:
actor: The actor to checkpoint.

Returns:
The result of the actor's user-defined `save_checkpoint` method.


def assign(self, value, use_locking=False, name=None, read_value=True):
    assign = state_ops.assign(self._variable, value, use_locking=use_locking, name=name)
    if read_value:
        return assign
    return assign.op

Assigns a new value to the variable.

This is essentially a shortcut for `assign(self, value)`.

Args:
value: A `Tensor`. The new value for this variable.
use_locking: If `True`, use locking during the assignment.
name: The name of the operation to be created
read_value: if True, will return something which evaluates to the new
value of the variable; if False will return the assign op.

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


def convert_persistent_value(self, shift, instruction):
    command_dict = {'name': 'pv', 't0': (shift + instruction.start_time), 'ch': instruction.channels[0].name, 'val': instruction.command.value}
    return self._qobj_model(**command_dict)

Return converted `PersistentValueInstruction`.

Args:
shift(int): Offset time.
instruction (PersistentValueInstruction): persistent value instruction.
Returns:
dict: Dictionary of required parameters.


def create_chunker(self, chunk_size):

        rolling_hash = _rabinkarprh.RabinKarpHash(self.window_size, self._seed)
        rolling_hash.set_threshold(1.0 / chunk_size)
        return RabinKarpCDC._Chunker(rolling_hash)

Create a chunker performing content-defined chunking (CDC) using Rabin Karp's rolling hash scheme with a
specific, expected chunk size.

Args:
chunk_size (int): (Expected) target chunk size.

Returns:
BaseChunker: A chunker object.


def open_model(self, model_path, audit=False):

        if audit:
            self._add_entry(templates.FILE_OPEN_AUDIT
                                     .format(model_path=model_path))
        else:
            self._add_entry(templates.FILE_OPEN
                                     .format(model_path=model_path))

Append a open non-workshared model entry to the journal.

This instructs Revit to open a non-workshared model.

Args:
model_path (str): full path to non-workshared model
audit (bool): if True audits the model when opening


def _field_to_json(field, row_value):
    if (row_value is None):
        return None
    if (field.mode == 'REPEATED'):
        return _repeated_field_to_json(field, row_value)
    if (field.field_type == 'RECORD'):
        return _record_field_to_json(field.fields, row_value)
    return _scalar_field_to_json(field, row_value)

Convert a field into JSON-serializable values.

Args:
field ( \
:class:`~google.cloud.bigquery.schema.SchemaField`, \
):
The SchemaField to use for type conversion and field name.

row_value (Union[ \
Sequence[list], \
any, \
]):
Row data to be inserted. If the SchemaField's mode is
REPEATED, assume this is a list. If not, the type
is inferred from the SchemaField's field_type.

Returns:
any:
A JSON-serializable object.


def _evaluateTFLiteModelUsingSignatureDef(self, tflite_model, signature_key, inputs):
    interpreter = Interpreter(model_content=tflite_model)
    signature_runner = interpreter.get_signature_runner(signature_key)
    return signature_runner(**inputs)

Evaluates the model on the `inputs`.

Args:
tflite_model: TensorFlow Lite model.
signature_key: Signature key.
inputs: Map from input tensor names in the SignatureDef to tensor value.

Returns:
Dictionary of outputs.
Key is the output name in the SignatureDef 'signature_key'
Value is the output value


def generate_typegraph(program: cfg.Program, var_table: dict[int, str], loader: jinja2.BaseLoader) -> str:
    encoder = typegraph_serializer.TypegraphEncoder()
    enc_prog = encoder.default(program)
    return _generate_visualization(template_file=_TYPEGRAPH_TEMPLATE_NAME, loader=loader, program=json.dumps(enc_prog), query_table=enc_prog['queries'], var_table=var_table)

Generate the visualization webpage.

Args:
program: cfg.Program. The instance of the program to visualize.
var_table: dict[int, str]. A mapping of cfg.Variable IDs to names.
loader: A jinja2 loader

Returns:
str. The rendered visualization page.


def get_by(self, field, value):
    if (not field):
        logger.exception(RESOURCE_CLIENT_INVALID_FIELD)
        raise ValueError(RESOURCE_CLIENT_INVALID_FIELD)
    filter = '"{0}=\'{1}\'"'.format(field, value)
    results = self.get_all(filter=filter)
    if ('.' not in field):
        results = [item for item in results if (str(item.get(field, '')).lower() == value.lower())]
    return results

Get the resource by passing a field and its value.

Note:
This function uses get_all passing a filter.The search is case-insensitive.

Args:
field: Field name to filter.
value: Value to filter.

Returns:
dict


def Serialize(self, writer):

        super(AccountState, self).Serialize(writer)
        writer.WriteUInt160(self.ScriptHash)
        writer.WriteBool(self.IsFrozen)
        writer.WriteVarInt(len(self.Votes))
        for vote in self.Votes:
            writer.WriteBytes(vote)

        blen = len(self.Balances)
        writer.WriteVarInt(blen)

        for key, fixed8 in self.Balances.items():
            writer.WriteUInt256(key)
            writer.WriteFixed8(fixed8)

Serialize full object.

Args:
writer (neo.IO.BinaryWriter):


def default(self, value):
    if isinstance(value, messages.Enum):
        return str(value)
    if (six.PY3 and isinstance(value, bytes)):
        return value.decode('utf8')
    if isinstance(value, messages.Message):
        result = {}
        for field in value.all_fields():
            item = value.get_assigned_value(field.name)
            if (item not in (None, [], ())):
                result[field.name] = self.__protojson_protocol.encode_field(field, item)
        for unknown_key in value.all_unrecognized_fields():
            (unrecognized_field, _) = value.get_unrecognized_field_info(unknown_key)
            result[unknown_key] = unrecognized_field
        return result
    return super(MessageJSONEncoder, self).default(value)

Return dictionary instance from a message object.

Args:
value: Value to get dictionary for.  If not encodable, will
call superclasses default method.


def FindNode(self, component_path):
    node = self.state.component_tree
    for component in component_path:
        node = node[component]
    return node

Find the node in the component_tree from component_path.

Args:
component_path: A list of components which reference a node in the
component tree. This allows us to resume processing in the tree.

Returns:
A node in the component_tree.


def GetTermSize(self):
    return self._term_size

Returns the terminal (x, y) dimensions in characters.

Returns:
(x, y): A tuple of the terminal x and y dimensions.


def __init__(self, **kwargs):

    if kwargs:
      raise ValueError('Unused keyword arguments: {0:s}.'.format(
          ', '.join(kwargs)))

    super(Decrypter, self).__init__()

Initializes a decrypter.

Args:
kwargs (dict): keyword arguments depending on the decrypter.

Raises:
ValueError: when there are unused keyword arguments.


def __init__(self, xid=None, experimenter=None, exp_type=None, data=b''):

        super().__init__(xid)
        self.experimenter = experimenter
        self.exp_type = exp_type
        self.data = data

Create a ExperimenterHeader with the optional parameters below.

Args:
xid (int): xid to be used on the message header.
experimenter (int): Vendor ID:
MSB 0: low-order bytes are IEEE OUI.
MSB != 0: defined by ONF.
exp_type (int): Experimenter defined.


def to_geojson(self, filename, proj, metadata=None):
    if (metadata is None):
        metadata = {}
    json_obj = {'type': 'FeatureCollection', 'features': [], 'properties': {}}
    json_obj['properties']['times'] = self.times.tolist()
    json_obj['properties']['dx'] = self.dx
    json_obj['properties']['step'] = self.step
    json_obj['properties']['u'] = self.u.tolist()
    json_obj['properties']['v'] = self.v.tolist()
    for (k, v) in metadata.items():
        json_obj['properties'][k] = v
    for (t, time) in enumerate(self.times):
        feature = {'type': 'Feature', 'geometry': {'type': 'Polygon'}, 'properties': {}}
        boundary_coords = self.boundary_polygon(time)
        lonlat = np.vstack(proj(boundary_coords[0], boundary_coords[1], inverse=True))
        lonlat_list = lonlat.T.tolist()
        if (len(lonlat_list) > 0):
            lonlat_list.append(lonlat_list[0])
        feature['geometry']['coordinates'] = [lonlat_list]
        for attr in ['timesteps', 'masks', 'x', 'y', 'i', 'j']:
            feature['properties'][attr] = getattr(self, attr)[t].tolist()
        feature['properties']['attributes'] = {}
        for (attr_name, steps) in self.attributes.items():
            feature['properties']['attributes'][attr_name] = steps[t].tolist()
        json_obj['features'].append(feature)
    file_obj = open(filename, 'w')
    json.dump(json_obj, file_obj, indent=1, sort_keys=True)
    file_obj.close()
    return

Output the data in the STObject to a geoJSON file.

Args:
filename: Name of the file
proj: PyProj object for converting the x and y coordinates back to latitude and longitue values.
metadata: Metadata describing the object to be included in the top-level properties.


def convert_datetime_type(obj):
    if (pd and (obj is pd.NaT)):
        return np.nan
    if (pd and isinstance(obj, pd.Period)):
        return (obj.to_timestamp().value / (10 ** 6.0))
    if (pd and isinstance(obj, _pd_timestamp)):
        return (obj.value / (10 ** 6.0))
    elif (pd and isinstance(obj, pd.Timedelta)):
        return (obj.value / (10 ** 6.0))
    elif isinstance(obj, dt.datetime):
        diff = (obj.replace(tzinfo=None) - DT_EPOCH)
        return (diff.total_seconds() * 1000.0)
    elif isinstance(obj, dt.date):
        return ((dt.datetime(*obj.timetuple()[:6]) - DT_EPOCH).total_seconds() * 1000)
    elif isinstance(obj, np.datetime64):
        epoch_delta = (obj - NP_EPOCH)
        return (epoch_delta / NP_MS_DELTA)
    elif isinstance(obj, dt.time):
        return (((((obj.hour * 3600) + (obj.minute * 60)) + obj.second) * 1000) + (obj.microsecond / 1000.0))

Convert any recognized date, time, or datetime value to floating point
milliseconds since epoch.

Arg:
obj (object) : the object to convert

Returns:
float : milliseconds


def delete_vmss_vms(access_token, subscription_id, resource_group, vmss_name, vm_ids):

    endpoint = ''.join([get_rm_endpoint(),
                        '/subscriptions/', subscription_id,
                        '/resourceGroups/', resource_group,
                        '/providers/Microsoft.Compute/virtualMachineScaleSets/', vmss_name,
                        '/delete?api-version=', COMP_API])
    body = '{"instanceIds" : ' + vm_ids + '}'
    return do_post(endpoint, body, access_token)

Delete a VM in a VM Scale Set.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
vmss_name (str): Name of the virtual machine scale set.
vm_ids (str): String representation of a JSON list of VM IDs. E.g. '[1,2]'.

Returns:
HTTP response.


def _CopyDateTimeFromStringISO8601(self, time_string):
    if (not time_string):
        raise ValueError('Invalid time string.')
    time_string_length = len(time_string)
    (year, month, day_of_month) = self._CopyDateFromString(time_string)
    if (time_string_length <= 10):
        return {'year': year, 'month': month, 'day_of_month': day_of_month}
    if (time_string[10] != 'T'):
        raise ValueError('Invalid time string - missing as date and time separator.')
    (hours, minutes, seconds, microseconds, time_zone_offset) = self._CopyTimeFromStringISO8601(time_string[11:])
    if time_zone_offset:
        (year, month, day_of_month, hours, minutes) = self._AdjustForTimeZoneOffset(year, month, day_of_month, hours, minutes, time_zone_offset)
    date_time_values = {'year': year, 'month': month, 'day_of_month': day_of_month, 'hours': hours, 'minutes': minutes, 'seconds': seconds}
    if (microseconds is not None):
        date_time_values['microseconds'] = microseconds
    return date_time_values

Copies a date and time from an ISO 8601 date and time string.

Args:
time_string (str): time value formatted as:
hh:mm:ss.######[+-]##:##

Where # are numeric digits ranging from 0 to 9 and the seconds
fraction can be either 3 or 6 digits. The fraction of second and
time zone offset are optional.

Returns:
tuple[int, int, int, int, int]: hours, minutes, seconds, microseconds,
time zone offset in minutes.

Raises:
ValueError: if the time string is invalid or not supported.


def set_record(self, name, record_id, record):
    if (name not in self._cache):
        self._cache[name] = {}
    self._cache[name][record_id] = record

Save a record into the cache.

Args:
name (string): The name to save the model under.
record_id (int): The record id.
record (:class:`cinder_data.model.CinderModel`): The model


def sg_prod(tensor, opt):
    r
    return tf.reduce_prod(tensor, axis=opt.axis, keep_dims=opt.keep_dims, name=opt.name)

r"""Computes the product of elements across axis of a tensor.

See `tf.reduce_prod()` in tensorflow.

Args:
tensor: A `Tensor` (automatically given by chain).
opt:
axis : A tuple/list of integers or an integer. The axis to reduce.
keep_dims: If true, retains reduced dimensions with length 1.
name: If provided, replace current tensor's name.

Returns:
A `Tensor`.


def AddArg(self, argument):
    self.args.append(argument)
    if (len(self.args) > self.number_of_args):
        raise errors.ParseError('Too many arguments for this expression.')
    elif (len(self.args) == self.number_of_args):
        return True
    return False

Adds a new argument to this expression.

Args:
argument (str): argument to add.

Returns:
True if the argument is the last argument, False otherwise.

Raises:
ParseError: If there are too many arguments.


def __checkDecisionParameters(self, result, **values):

		error = []

		if not result:
			error.append('Function parameter (result array) should contain one or more header string!')

		if not values:
			error.append('Function parameter (values variables) should contain one or more variable')

		for header in result:
			if not header in self.header:
				error.append('String (' + header + ') in result is not in header!')

		for header in values:
			if not header in self.header:
				error.append('Variable (' + header + ') in values is not in header!')
			elif not values[header].split():
				error.append('Variable (' + header + ') in values is empty string')

		if error:
			return error

Checker of decision parameters, it will raise ValueError if finds something wrong.

Args:
result (array of str): See public decision methods
**values (array of str): See public decision methods

Raise:
ValueError: Result array none.
ValueError: Values dict none.
ValueError: Not find result key in header.
ValueError: Result value is empty.

Returns:
Error array values


def send_msg(self, address, args=[]):

        if not address.startswith('/'):
            address = '/{}'.format(address)

        msg = osc_message_builder.OscMessageBuilder(address=address)

        for arg in args:
            msg.add_arg(arg)
        self.conn.send(msg.build())
        return

Send multiple args into a single message to a given address.

Args:
address (str): OSC Address.
args (list): Arguments to be parsed in VVVV.


def __init__(self, channel):

    self.Exchange = channel.unary_unary(
        '/communicator_objects.UnityToExternal/Exchange',
        request_serializer=mlagents_dot_envs_dot_communicator__objects_dot_unity__message__pb2.UnityMessage.SerializeToString,
        response_deserializer=mlagents_dot_envs_dot_communicator__objects_dot_unity__message__pb2.UnityMessage.FromString,
        )

Constructor.

Args:
channel: A grpc.Channel.


def create_pipeline_field(self, pipeline_key, name, field_type, **kwargs):

		uri = '/'.join([self.api_uri,
						self.pipelines_suffix,
						pipeline_key,
						self.fields_suffix
						])

		code, data = self._create_field(uri, name, field_type, **kwargs)

		return code, data

Creates a pipeline field with the provided attributes.
Args:
pipeline_key	specifying the pipeline to add the field to
name			required name string
field_type		required type string [TEXT_INPUT, DATE or PERSON]
kwargs			{}
return			(status code, field dict)


def write(self, data):

    block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE

    if block_remaining < _HEADER_LENGTH:

      self.__writer.write('\x00' * block_remaining)
      self.__position += block_remaining
      block_remaining = _BLOCK_SIZE

    if block_remaining < len(data) + _HEADER_LENGTH:
      first_chunk = data[:block_remaining - _HEADER_LENGTH]
      self.__write_record(_RECORD_TYPE_FIRST, first_chunk)
      data = data[len(first_chunk):]

      while True:
        block_remaining = _BLOCK_SIZE - self.__position % _BLOCK_SIZE
        if block_remaining >= len(data) + _HEADER_LENGTH:
          self.__write_record(_RECORD_TYPE_LAST, data)
          break
        else:
          chunk = data[:block_remaining - _HEADER_LENGTH]
          self.__write_record(_RECORD_TYPE_MIDDLE, chunk)
          data = data[len(chunk):]
    else:
      self.__write_record(_RECORD_TYPE_FULL, data)

Write single record.

Args:
data: record data to write as string, byte array or byte sequence.


def inv_attractor(dx, alpha: float=300, gamma: int=2):
    return dx.div(1 + alpha * dx.pow(gamma))

Inverse attractor: dc = dx / (1 + alpha*dx^gamma), where dx = a - c, a = attractor point, c = bin center, dc = shift in bin center
This is the default one according to the accompanying paper.

Args:
dx (`torch.Tensor`):
The difference tensor dx = Ai - Cj, where Ai is the attractor point and Cj is the bin center.
alpha (`float`, *optional*, defaults to 300):
Proportional Attractor strength. Determines the absolute strength. Lower alpha = greater attraction.
gamma (`int`, *optional*, defaults to 2):
Exponential Attractor strength. Determines the "region of influence" and indirectly number of bin centers affected.
Lower gamma = farther reach.

Returns:
torch.Tensor: Delta shifts - dc; New bin centers = Old bin centers + dc


def convert_bboxes_from_albumentations(bboxes, target_format, rows, cols, check_validity=False):

    return [convert_bbox_from_albumentations(bbox, target_format, rows, cols, check_validity) for bbox in bboxes]

Convert a list of bounding boxes from the format used by albumentations to a format, specified
in `target_format`.

Args:
bboxes (list): List of bounding box with coordinates in the format used by albumentations
target_format (str): required format of the output bounding box. Should be 'coco' or 'pascal_voc'.
rows (int): image height
cols (int): image width
check_validity (bool): check if all boxes are valid boxes


def filter_by_analysis_period(self, analysis_period):

        _filtered_data = self.filter_by_months(analysis_period.months_int)
        _filtered_data.header._analysis_period = analysis_period
        return _filtered_data

Filter the Data Collection based on an analysis period.

Args:
analysis period: A Ladybug analysis period

Return:
A new Data Collection with filtered data


def is_datafile_valid(datafile):

  try:
    datafile_json = json.loads(datafile)
  except:
    return False

  try:
    jsonschema.Draft4Validator(constants.JSON_SCHEMA).validate(datafile_json)
  except:
    return False

  return True

Given a datafile determine if it is valid or not.

Args:
datafile: JSON string representing the project.

Returns:
Boolean depending upon whether datafile is valid or not.


def Open(self, file_object):
    file_object.seek(0, os.SEEK_SET)
    signature_data = file_object.read(6)
    self.file_format = None
    if (len(signature_data) > 2):
        if (signature_data[:2] == self._CPIO_SIGNATURE_BINARY_BIG_ENDIAN):
            self.file_format = 'bin-big-endian'
        elif (signature_data[:2] == self._CPIO_SIGNATURE_BINARY_LITTLE_ENDIAN):
            self.file_format = 'bin-little-endian'
        elif (signature_data == self._CPIO_SIGNATURE_PORTABLE_ASCII):
            self.file_format = 'odc'
        elif (signature_data == self._CPIO_SIGNATURE_NEW_ASCII):
            self.file_format = 'newc'
        elif (signature_data == self._CPIO_SIGNATURE_NEW_ASCII_WITH_CHECKSUM):
            self.file_format = 'crc'
    if (self.file_format is None):
        raise IOError('Unsupported CPIO format.')
    self._file_object = file_object
    self._file_size = file_object.get_size()
    self._ReadFileEntries(self._file_object)

Opens the CPIO archive file.

Args:
file_object (FileIO): a file-like object.

Raises:
IOError: if the file format signature is not supported.
OSError: if the file format signature is not supported.


async def _call_rpc(self, header):

        length, _, cmd, feature, address = struct.unpack("<BBBBB", bytes(header))
        rpc_id = (feature << 8) | cmd

        payload = self.rpc_payload[:length]

        self._logger.debug("Calling RPC %d:%04X with %s", address, rpc_id, binascii.hexlify(payload))

        exception = None
        response = None

        try:
            response = await self.send_rpc(self.CLIENT_ID, str(self.device.iotile_id), address, rpc_id, bytes(payload), timeout=30.0)
        except VALID_RPC_EXCEPTIONS as err:
            exception = err
        except Exception as err:
            self._logger.exception("Error calling RPC %d:%04X", address, rpc_id)
            exception = err

        status, response = pack_rpc_response(response, exception)
        resp_header = struct.pack("<BBBB", status, 0, 0, len(response))

        await self._send_notification(self.ReceiveHeaderHandle, resp_header)

        if len(response) > 0:
            await self._send_notification(self.ReceivePayloadHandle, response)

Call an RPC given a header and possibly a previously sent payload

Args:
header (bytearray): The RPC header we should call


def del_method(self, m):

        if isinstance(m, types.FunctionType) and not iscoroutinefunction(m):
            wrkey = ('function', id(m))
        else:
            f, obj = get_method_vars(m)
            wrkey = (f, id(obj))
        if wrkey in self:
            del self[wrkey]

Remove an instance method or function if it exists

Args:
m: The instance method or function to remove


def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    super(GetResponsePayload, self).read(input_stream, kmip_version=kmip_version)
    local_stream = utils.BytearrayStream(input_stream.read(self.length))
    if self.is_tag_next(enums.Tags.OBJECT_TYPE, local_stream):
        self._object_type = primitives.Enumeration(enum=enums.ObjectType, tag=enums.Tags.OBJECT_TYPE)
        self._object_type.read(local_stream, kmip_version=kmip_version)
    else:
        raise ValueError('Parsed payload encoding is missing the object type field.')
    if self.is_tag_next(enums.Tags.UNIQUE_IDENTIFIER, local_stream):
        self._unique_identifier = primitives.TextString(tag=enums.Tags.UNIQUE_IDENTIFIER)
        self._unique_identifier.read(local_stream, kmip_version=kmip_version)
    else:
        raise ValueError('Parsed payload encoding is missing the unique identifier field.')
    self.secret = self.secret_factory.create(self.object_type)
    if self.is_tag_next(self._secret.tag, local_stream):
        self._secret.read(local_stream, kmip_version=kmip_version)
    else:
        raise ValueError('Parsed payload encoding is missing the secret field.')
    self.is_oversized(local_stream)

Read the data encoding the Get response payload and decode it
into its constituent parts.

Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read method; usually a BytearrayStream
object.
kmip_version (KMIPVersion): An enumeration defining the KMIP
version with which the object will be decoded. Optional,
defaults to KMIP 1.0.

Raises:
ValueError: Raised if the object type, unique identifier, or
secret attributes are missing from the encoded payload.


def CacheFileObject(self, path_spec, file_object):

    self._file_object_cache.CacheObject(path_spec.comparable, file_object)

Caches a file-like object based on a path specification.

Args:
path_spec (PathSpec): path specification.
file_object (FileIO): file-like object.


def _collect_tokens(self, node: dict) -> list:
    tokens = [self._termination_char] if self._termination_char in node else []
    for token, subtrie_head in node.items():
        if token != self._termination_char:
            subtokens = self._collect_tokens(subtrie_head)
            tokens.extend([token + subtoken for subtoken in subtokens])
    return tokens

Generates all tokens in the Trie starting from a given node.

Args:
node (dict): The node in the Trie from which tokens need to be generated.

Returns:
list: List of tokens generated from the given node.


def _get_query_results(self, job_id, retry, project=None, timeout_ms=None, location=None):
    extra_params = {'maxResults': 0}
    if (project is None):
        project = self.project
    if (timeout_ms is not None):
        extra_params['timeoutMs'] = timeout_ms
    if (location is None):
        location = self.location
    if (location is not None):
        extra_params['location'] = location
    path = '/projects/{}/queries/{}'.format(project, job_id)
    resource = self._call_api(retry, method='GET', path=path, query_params=extra_params)
    return _QueryResults.from_api_repr(resource)

Get the query results object for a query job.

Arguments:
job_id (str): Name of the query job.
retry (google.api_core.retry.Retry):
(Optional) How to retry the RPC.
project (str):
(Optional) project ID for the query job (defaults to the
project of the client).
timeout_ms (int):
(Optional) number of milliseconds the the API call should
wait for the query to complete before the request times out.
location (str): Location of the query job.

Returns:
google.cloud.bigquery.query._QueryResults:
A new ``_QueryResults`` instance.


def prune_intermediate_layers(node):
    if not node.get('children'):
        return
    layer_blocks = [(i, child) for i, child in enumerate(node['children']) if is_layer_block(child)]
    if len(layer_blocks) > 2:
        to_remove = [i for i, _ in layer_blocks[1:-1]]
        node['children'] = [child for i, child in enumerate(node['children']) if i not in to_remove]
    for child in node['children']:
        prune_intermediate_layers(child)

Recursively removes intermediate layers from the tree to improve readability.
Keeps at least the first and last layers if many consecutive layers are present.

Args:
node (`dict`): The root or subnode to prune recursively.


def __init__(self, all_reduce_alg='nccl', num_packs=1):
    self._all_reduce_alg = all_reduce_alg
    self._num_packs = num_packs
    self._simple_cross_replica_ops = ReductionToOneDevice()
    super(AllReduceCrossDeviceOps, self).__init__()

Initializes the object.

Args:
all_reduce_alg: the all-reduce algorithm to use, currently only "nccl" or
"hierarchical_copy" are supported.
num_packs: a non-negative integer. The number of packs to split values
into. If zero, no packing will be done.


def read_named_csv(name, data_path=DATA_PATH, nrows=None, verbose=True):

    if os.path.isfile(name):
        try:
            return read_json(name)
        except (IOError, UnicodeDecodeError, json.JSONDecodeError):
            pass
        try:
            return read_csv(name, nrows=nrows)
        except (IOError, pd.errors.ParserError):
            pass
        try:
            return read_txt(name, nrows=nrows)
        except (IOError, UnicodeDecodeError):
            pass
    data_path = expand_filepath(data_path)
    if os.path.isfile(os.path.join(data_path, name)):
        return read_csv(os.path.join(data_path, name), nrows=nrows)
    if name in DATASET_NAME2FILENAME:
        name = DATASET_NAME2FILENAME[name]
        if name.lower().endswith('.txt') or name.lower().endswith('.txt.gz'):
            return read_text(os.path.join(data_path, name), nrows=nrows)
        else:
            return read_csv(os.path.join(data_path, name), nrows=nrows)
    try:
        return read_csv(os.path.join(data_path, name + '.csv.gz'), nrows=nrows)
    except IOError:
        pass
    try:
        return read_csv(os.path.join(data_path, name + '.csv'), nrows=nrows)
    except IOError:
        pass
    try:
        return read_json(os.path.join(data_path, name + '.json'))
    except IOError:
        pass
    try:
        return read_txt(os.path.join(data_path, name + '.txt'), verbose=verbose)
    except IOError:
        pass

    try:
        return KeyedVectors.load_word2vec_format(os.path.join(BIGDATA_PATH, name + '.bin.gz'), binary=True)
    except IOError:
        pass
    except ValueError:
        pass
    try:
        return read_txt(os.path.join(BIGDATA_PATH, name + '.txt'), verbose=verbose)
    except IOError:
        pass

Convert a dataset in a local file (usually a CSV) into a Pandas DataFrame

TODO: should be called read_named_dataset

Args:
`name` is assumed not to have an extension (like ".csv"), alternative extensions are tried automatically.file


def get_new_address(self, id=None, endpoint=None):

        return self._call_endpoint(GET_NEW_ADDRESS, id=id, endpoint=endpoint)

Create new address
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the error encountered in the RPC call


def ListPlugins(logdir):
    plugins_dir = os.path.join(logdir, _PLUGINS_DIR)
    try:
        entries = tf.io.gfile.listdir(plugins_dir)
    except tf.errors.NotFoundError:
        return []
    return [x.rstrip('/') for x in entries if (x.endswith('/') or _IsDirectory(plugins_dir, x))]

List all the plugins that have registered assets in logdir.

If the plugins_dir does not exist, it returns an empty list. This maintains
compatibility with old directories that have no plugins written.

Args:
logdir: A directory that was created by a TensorFlow events writer.

Returns:
a list of plugin names, as strings


def resource_import(filename: str, *, module: Optional[epath.PathLike]=None) -> str:
    path = epath.resource_path(module) if module else _static_path()
    path = path.joinpath(filename)
    content = path.read_text()
    if path.suffix == '.css':
        return f'<style>{content}</style>'
    elif path.suffix == '.js':
        return f'<script>{content}</script>'
    else:
        raise ValueError('')

Returns the `HTML` associated with the resource.

Args:
filename: Path to the `.css`, `.js` resource
module: Python module name from which the filename is relative too.


def bytes_to_long(bytesdata: bytes) -> int:

    assert len(bytesdata) == 8
    return sum((b << (k * 8) for k, b in enumerate(bytesdata)))

Converts an 8-byte sequence to a long integer.

Args:
bytesdata: 8 consecutive bytes, as a ``bytes`` object, in
little-endian format (least significant byte [LSB] first)

Returns:
integer


def open_required(func):

    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        'Wrapper function to check that the given ``JLink`` has been\n            opened.\n\n            Args:\n              self (JLink): the ``JLink`` instance\n              args: list of arguments to pass to the wrapped function\n              kwargs: key-word arguments dict to pass to the wrapped function\n\n            Returns:\n              The return value of the wrapped function.\n\n            Raises:\n              JLinkException: if the J-Link DLL is not open or the J-Link is\n                  disconnected.\n            '
        if (not self.opened()):
            raise errors.JLinkException('J-Link DLL is not open.')
        elif (not self.connected()):
            raise errors.JLinkException('J-Link connection has been lost.')
        return func(self, *args, **kwargs)
    return wrapper

Decorator to specify that the J-Link DLL must be opened, and a
J-Link connection must be established.

Args:
func (function): function being decorated

Returns:
The wrapper function.


def _config_session():
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    config.gpu_options.visible_device_list = '0'
    return tf.Session(config=config)

Configure session for particular device

Returns:
tensorflow.Session


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

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

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

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

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


def char_decode(self, sequences):
    decode_strs = [seq.replace(' ', '') for seq in self.char_tokenizer.batch_decode(sequences)]
    return decode_strs

Convert a list of lists of char token ids into a list of strings by calling char tokenizer.

Args:
sequences (`torch.Tensor`):
List of tokenized input ids.
Returns:
`List[str]`: The list of char decoded sentences.


def detect_content_type(self, path=None, payload=None, objectInput=None):
    if objectInput:
        message = 'Detection content type with file object is not stable.'
        log.exception(message)
        raise TikaAppError(message)
    f = file_path(path, payload, objectInput)
    switches = ['-d', f]
    result = self._command_template(switches).lower()
    return (result, path, f)

Return the content type of passed file or payload.

Args:
path (string): Path of file to analyze
payload (string): Payload base64 to analyze
objectInput (object): file object/standard input to analyze

Returns:
content type of file (string)


def update(self, data):
    for (key, value) in data.items():
        setattr(self, key, value)

Update the current memory record with the given data dict.

Args:
data (dict): Data dictionary to update the record attributes with.


def __init__(self, content=None, min=0, max=HUGE, name=None):
    assert 0 <= min <= max <= HUGE, (min, max)
    if content is not None:
        content = tuple(map(tuple, content))
        assert len(content), repr(content)
        for alt in content:
            assert len(alt), repr(alt)
    self.content = content
    self.min = min
    self.max = max
    self.name = name

Initializer.

Args:
content: optional sequence of subsequences of patterns; if absent,
matches one node; if present, each subsequence is an alternative [*]
min: optional minimum number of times to match, default 0
max: optional maximum number of times to match, default HUGE
name: optional name assigned to this match

[*] Thus, if content is [[a, b, c], [d, e], [f, g, h]] this is
equivalent to (a b c | d e | f g h); if content is None,
this is equivalent to '.' in regular expression terms.
The min and max parameters work as follows:
min=0, max=maxint: .*
min=1, max=maxint: .+
min=0, max=1: .?
min=1, max=1: .
If content is not None, replace the dot with the parenthesized
list of alternatives, e.g. (a b c | d e | f g h)*


def __init__(self, config=None, start=True):
    config = config or DispatcherConfig()
    if config.fault_tolerant_mode and (not config.work_dir):
        raise ValueError('Cannot enable fault tolerant mode without configuring a work dir. Make sure to set `work_dir` in the `config` object passed to `DispatcherServer`.')
    self._config = config
    if isinstance(config, service_config_pb2.DispatcherConfig):
        config_proto = config
    else:
        config_proto = service_config_pb2.DispatcherConfig(port=config.port, protocol=config.protocol, work_dir=config.work_dir, fault_tolerant_mode=config.fault_tolerant_mode, worker_addresses=config.worker_addresses, job_gc_check_interval_ms=config.job_gc_check_interval_ms, job_gc_timeout_ms=config.job_gc_timeout_ms, worker_timeout_ms=config.worker_timeout_ms, worker_max_concurrent_snapshots=config.worker_max_concurrent_snapshots)
    self._server = _pywrap_server_lib.TF_DATA_NewDispatchServer(config_proto.SerializeToString())
    if start:
        self._server.start()

Creates a new dispatch server.

Args:
config: (Optional.) A `tf.data.experimental.service.DispatcherConfig`
configuration. If `None`, the dispatcher will use default configuration
values.
start: (Optional.) Boolean, indicating whether to start the server after
creating it. Defaults to True.


def _add_bound_method(self, bound_method, identify_observed):

        inst = bound_method.__self__
        method_name = bound_method.__name__
        key = self.make_key(bound_method)
        if key not in self.observers:
            self.observers[key] = ObserverBoundMethod(
                inst, method_name, identify_observed, (key, self.observers))
            return True
        else:
            return False

Add an bound method as an observer.

Args:
bound_method: The bound method to add as an observer.
identify_observed: See the docstring for add_observer.

Returns:
True if the bound method is added, otherwise False.


def sget_steptime(self, cycle, step, dataset_number=None):
    dataset_number = self._validate_dataset_number(dataset_number)
    if (dataset_number is None):
        self._report_empty_dataset()
        return
    cycle_index_header = self.headers_normal.cycle_index_txt
    step_time_header = self.headers_normal.step_time_txt
    step_index_header = self.headers_normal.step_index_txt
    test = self.datasets[dataset_number].dfdata
    if isinstance(step, (list, tuple)):
        warnings.warn(f'The varialbe step is a list.Should be an integer.{step}')
        step = step[0]
    c = test.loc[(((test[cycle_index_header] == cycle) & (test[step_index_header] == step)), :)]
    if (not self.is_empty(c)):
        t = c[step_time_header]
        return t
    else:
        return None

Returns step time for cycle, step.

Convinience function; same as issuing
dfdata[(dfdata[cycle_index_header] == cycle) &
(dfdata[step_index_header] == step)][step_time_header]

Args:
cycle: cycle number
step: step number
dataset_number: the dataset number (automatic selection if None)

Returns:
pandas.Series or None if empty


def execute_command(self, command: str, read: bool=False) -> None:
    if self.debug:
        print(command)
        return 'SIMULATING VALUE' if read else True
    else:
        print('\nCOMMAND\n', command, '\n' + '-' * 40)
        try:
            cmd = subprocess.run(command, shell=True, capture_output=read, text=True, check=True)
            if read:
                return cmd.stdout.strip()
            return True
        except subprocess.CalledProcessError as e:
            return False

Helper function that either executes or prints each command.

Args:
command - a command line command, typically a gcloud command.
read - if True, the commands output is passed back to the caller.

Returns:
Bool - if command value is not required, simply indicate successor failure.
String - if read is specified, the command output or error is returned.


def _parse_vars(self, tokens):
    key_values = {}
    for token in tokens:
        if token.startswith('
            break
        else:
            (k, v) = token.split('=', 1)
            key = k.strip()
            key_values[key] = v.strip()
    return key_values

Given an iterable of tokens, returns variables and their values as a
dictionary.

For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'}


def pot_string_from_file(filename='feff.inp'):

        with zopen(filename, "rt") as f_object:
            f = f_object.readlines()
            ln = -1
            pot_str = ["POTENTIALS\n"]
            pot_tag = -1
            pot_data = 0
            pot_data_over = 1

            sep_line_pattern = [re.compile('ipot.*Z.*tag.*lmax1.*lmax2.*spinph'),
                                re.compile('^[*]+.*[*]+$')]

            for line in f:
                if pot_data_over == 1:
                    ln += 1
                    if pot_tag == -1:
                        pot_tag = line.find("POTENTIALS")
                        ln = 0
                    if pot_tag >= 0 and ln > 0 and pot_data_over > 0:
                        try:
                            if len(sep_line_pattern[0].findall(line)) > 0 or \
                                            len(sep_line_pattern[1].findall(line)) > 0:
                                pot_str.append(line)
                            elif int(line.split()[0]) == pot_data:
                                pot_data += 1
                                pot_str.append(line.replace("\r", ""))
                        except (ValueError, IndexError):
                            if pot_data > 0:
                                pot_data_over = 0

        return ''.join(pot_str).rstrip('\n')

Reads Potential parameters from a feff.inp or FEFFPOT file.
The lines are arranged as follows:

ipot   Z   element   lmax1   lmax2   stoichometry   spinph

Args:
filename: file name containing potential data.

Returns:
FEFFPOT string.


def patch_toText(self, patches):
    text = []
    for patch in patches:
        text.append(str(patch))
    return ''.join(text)

Take a list of patches and return a textual representation.

Args:
patches: Array of Patch objects.

Returns:
Text representation of patches.


def list_attributes(self, name):

        result = self.client.service.getListAttributes(name, self.proxy_id)
        if isinstance(result, list) and len(result) == 1:
            return result[0]
        return result

Look up the attributes of a list.

Args:
name (str): The name of the list

Returns:
dict: attributes of the list


def create_token(self,
                     token_name,
                     project_name,
                     dataset_name,
                     is_public):

        url = self.url() + '/nd/resource/dataset/{}'.format(
            dataset_name) + '/project/{}'.format(project_name) + \
            '/token/{}/'.format(token_name)

        json = {
            "token_name": token_name,
            "public": is_public
        }

        req = self.remote_utils.post_url(url, json=json)

        if req.status_code is not 201:
            raise RemoteDataUploadError('Cout not upload {}:'.format(req.text))
        if req.content == "" or req.content == b'':
            return True
        else:
            return False

Creates a token with the given parameters.
Arguments:
project_name (str): Project name
dataset_name (str): Dataset name project is based on
token_name (str): Token name
is_public (int): 1 is public. 0 is not public
Returns:
bool: True if project created, false if not created.


def Scan(self, scan_context, auto_recurse=True, scan_path_spec=None):

    if not scan_context:
      raise ValueError('Invalid scan context.')

    scan_context.updated = False

    if scan_path_spec:
      scan_node = scan_context.GetScanNode(scan_path_spec)

    else:
      scan_node = scan_context.GetUnscannedScanNode()

    if scan_node:
      self._ScanNode(scan_context, scan_node, auto_recurse=auto_recurse)

Scans for supported formats.

Args:
scan_context (SourceScannerContext): source scanner context.
auto_recurse (Optional[bool]): True if the scan should automatically
recurse as far as possible.
scan_path_spec (Optional[PathSpec]): path specification to indicate
where the source scanner should continue scanning, where None
indicates the scanner will start with the sources.

Raises:
ValueError: if the scan context is invalid.


def update_nanopubstore_start_dt(url: str, start_dt: str):

    hostname = urllib.parse.urlsplit(url)[1]

    start_dates_doc = state_mgmt.get(start_dates_doc_key)
    if not start_dates_doc:
        start_dates_doc = {
            "_key": start_dates_doc_key,
            "start_dates": [{"nanopubstore": hostname, "start_dt": start_dt}],
        }
        state_mgmt.insert(start_dates_doc)
    else:
        for idx, start_date in enumerate(start_dates_doc["start_dates"]):
            if start_date["nanopubstore"] == hostname:
                start_dates_doc["start_dates"][idx]["start_dt"] = start_dt
                break
        else:
            start_dates_doc["start_dates"].append(
                {"nanopubstore": hostname, "start_dt": start_dt}
            )

        state_mgmt.replace(start_dates_doc)

Add nanopubstore start_dt to belapi.state_mgmt collection

Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's


def __init__(self, seed_fn, desc=None):

        if desc is None:
            desc = u'Query({})'.format(getattr(seed_fn, '__name__', ''))

        self.seed_fn = seed_fn
        self.transforms = []
        self.desc_stack = []
        self.desc = desc

Configure the `Query`.

Args:
seed_fn (callable): Callable with no arguments that produces a list of values.

Keyword Args:
desc (str): A description of the query, used in log messages.
If not provided, defaults to the name of the seed function.

Returns:
Query


def add_triple(self, p, o, auto_refresh=True):

		self.rdf.graph.add((self.uri, p, self._handle_object(o)))

		self._handle_triple_refresh(auto_refresh)

add triple by providing p,o, assumes s = subject

Args:
p (rdflib.term.URIRef): predicate
o (): object
auto_refresh (bool): whether or not to update object-like self.rdf.triples

Returns:
None: adds triple to self.rdf.graph


def get_associated_resource(self, task):
    if (not task):
        raise HPOneViewUnknownType(MSG_INVALID_TASK)
    if ((task['category'] != 'tasks') and (task['category'] != 'backups')):
        raise HPOneViewUnknownType(MSG_UNKNOWN_OBJECT_TYPE)
    if (task['type'] == 'TaskResourceV2'):
        resource_uri = task['associatedResource']['resourceUri']
        if (resource_uri and resource_uri.startswith('/rest/appliance/support-dumps/')):
            return (task, resource_uri)
    elif (task['type'] == 'BACKUP'):
        task = self._connection.get(task['taskUri'])
        resource_uri = task['uri']
    else:
        raise HPOneViewInvalidResource((MSG_TASK_TYPE_UNRECONIZED % task['type']))
    entity = {}
    if resource_uri:
        entity = self._connection.get(resource_uri)
    return (task, entity)

Retrieve a resource associated with a task.

Args:
task: task dict

Returns:
tuple: task (updated), the entity found (dict)


def plot_vec(axis, step, var):

    xmesh, ymesh, vec1, vec2 = get_meshes_vec(step, var)
    dipz = step.geom.nztot
    if conf.field.shift:
        vec1 = np.roll(vec1, conf.field.shift, axis=0)
        vec2 = np.roll(vec2, conf.field.shift, axis=0)
    if step.geom.spherical or conf.plot.ratio is None:
        dipx = dipz
    else:
        dipx = step.geom.nytot if step.geom.twod_yz else step.geom.nxtot
        dipx = int(dipx
    axis.quiver(xmesh[::dipx, ::dipz], ymesh[::dipx, ::dipz],
                vec1[::dipx, ::dipz], vec2[::dipx, ::dipz],
                linewidths=1)

Plot vector field.

Args:
axis (:class:`matplotlib.axes.Axes`): the axis handler of an
existing matplotlib figure where the vector field should
be plotted.
step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData
instance.
var (str): the vector field name.


def set_session(self, headers=None):
    if (headers is None):
        headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'}
    elif (not isinstance(headers, dict)):
        raise TypeError('"headers" must be a dict object')
    self.session = Session(self.proxy_pool)
    self.session.headers.update(headers)

Init session with default or custom headers

Args:
headers: A dict of headers (default None, thus using the default
header to init the session)


def StringEscape(self, string, match, **_):

    precondition.AssertType(string, Text)
    if match.group(1) in "'\"rnbt":
      self.string += compatibility.UnescapeString(string)
    else:
      self.string += string

Escape backslashes found inside a string quote.

Backslashes followed by anything other than ['"rnbt] will just be included
in the string.

Args:
string: The string that matched.
match: The match object (m.group(1) is the escaped code)


def _get_bundles_by_type(self, type):

        bundles = {}
        bundle_definitions = self.config.get(type)
        if bundle_definitions is None:
            return bundles

        for bundle_name, paths in bundle_definitions.items():
            bundle_files = []

            for path in paths:

                pattern = abspath = os.path.join(self.basedir, path)

                assetdir = os.path.dirname(abspath)

                fnames = [os.path.join(assetdir, fname)
                          for fname in os.listdir(assetdir)]
                expanded_fnames = fnmatch.filter(fnames, pattern)
                bundle_files.extend(sorted(expanded_fnames))
            bundles[bundle_name] = bundle_files

        return bundles

Get a dictionary of bundles for requested type.

Args:
type: 'javascript' or 'css'


def __init__(self, streaming_buffer, writer_spec=None):

    self._streaming_buffer = streaming_buffer
    self._no_dup = False
    if writer_spec:
      self._no_dup = writer_spec.get(self._NO_DUPLICATE, False)
    if self._no_dup:

      self._seg_index = int(streaming_buffer.name.rsplit("-", 1)[1])

      self._seg_valid_length = 0

Initialize a GoogleCloudStorageOutputWriter instance.

Args:
streaming_buffer: an instance of writable buffer from cloudstorage_api.

writer_spec: the specification for the writer.


def __init__(self, specification_store, signature_identifiers):

    super(SignaturesFileEntryFilter, self).__init__()
    self._file_scanner = None
    self._signature_identifiers = []

    self._file_scanner = self._GetScanner(
        specification_store, signature_identifiers)

Initializes a signature-based file entry filter.

Args:
specification_store (FormatSpecificationStore): a specification store.
signature_identifiers (list[str]): signature identifiers.


def calculate_sun_from_hoy(self, hoy, is_solar_time=False):

        datetime = DateTime.from_hoy(hoy, self.is_leap_year)
        return self.calculate_sun_from_date_time(datetime, is_solar_time)

Get Sun data for an hour of the year.

Args:
datetime: Ladybug datetime
is_solar_time: A boolean to indicate if the input hour is solar time
(Default: False).

Returns:
A sun object for this particular time


def preemphasis(signal, shift=1, cof=0.98):

    rolled_signal = np.roll(signal, shift)
    return signal - cof * rolled_signal

preemphasising on the signal.

Args:
signal (array): The input signal.
shift (int): The shift step.
cof (float): The preemphasising coefficient. 0 equals to no filtering.

Returns:
array: The pre-emphasized signal.


def __init__(self, operator, left, right):

        super(BinaryComposition, self).__init__(operator, left, right)
        self.operator = operator
        self.left = left
        self.right = right
        self.validate()

Construct an expression that connects two expressions with an operator.

Args:
operator: unicode, specifying where the field was declared
left: Expression on the left side of the binary operator
right: Expression on the right side of the binary operator

Returns:
new BinaryComposition object


async def update(self, service_id: str, version: str, *, image: str=None, rollback: bool=False) -> bool:
    if ((image is None) and (rollback is False)):
        raise ValueError('You need to specify an image.')
    inspect_service = (await self.inspect(service_id))
    spec = inspect_service['Spec']
    if (image is not None):
        spec['TaskTemplate']['ContainerSpec']['Image'] = image
    params = {'version': version}
    if (rollback is True):
        params['rollback'] = 'previous'
    data = json.dumps(clean_map(spec))
    (await self.docker._query_json('services/{service_id}/update'.format(service_id=service_id), method='POST', data=data, params=params))
    return True

Update a service.
If rollback is True image will be ignored.

Args:
service_id: ID or name of the service.
version: Version of the service that you want to update.
rollback: Rollback the service to the previous service spec.

Returns:
True if successful.


def _generate_G_points(self, kpoint):

        gpoints = []
        for i in range(2 * self._nbmax[2] + 1):
            i3 = i - 2 * self._nbmax[2] - 1 if i > self._nbmax[2] else i
            for j in range(2 * self._nbmax[1] + 1):
                j2 = j - 2 * self._nbmax[1] - 1 if j > self._nbmax[1] else j
                for k in range(2 * self._nbmax[0] + 1):
                    k1 = k - 2 * self._nbmax[0] - 1 if k > self._nbmax[0] else k
                    G = np.array([k1, j2, i3])
                    v = kpoint + G
                    g = np.linalg.norm(np.dot(v, self.b))
                    E = g ** 2 / self._C
                    if E < self.encut:
                        gpoints.append(G)
        return np.array(gpoints, dtype=np.float64)

Helper function to generate G-points based on nbmax.

This function iterates over possible G-point values and determines
if the energy is less than G_{cut}. Valid values are appended to
the output array. This function should not be called outside of
initialization.

Args:
kpoint (np.array): the array containing the current k-point value

Returns:
a list containing valid G-points


def Normalize(self, fraction=1.0):

        if self.log:
            raise ValueError("Pmf is under a log transform")

        total = self.Total()
        if total == 0.0:
            raise ValueError('total probability is zero.')
            logging.warning('Normalize: total probability is zero.')
            return total

        factor = float(fraction) / total
        for x in self.d:
            self.d[x] *= factor

        return total

Normalizes this PMF so the sum of all probs is fraction.

Args:
fraction: what the total should be after normalization

Returns: the total probability before normalizing


def make_pixel_mask(image: 'torch.Tensor', output_size: Tuple[int, int]) -> 'torch.Tensor':
    input_height, input_width = image.shape[-2:]
    batch_size = image.size(0)
    mask = torch.zeros((batch_size, *output_size), dtype=torch.long)
    mask[:input_height, :input_width] = 1
    return mask

Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.

Args:
image (`np.ndarray`):
Image to make the pixel mask for.
output_size (`Tuple[int, int]`):
Output size of the mask.


def get_audience(self, audience_id):

    audience = self.audience_id_map.get(audience_id)
    if audience:
      return audience

    self.logger.error('Audience ID "%s" is not in datafile.' % audience_id)
    self.error_handler.handle_error(exceptions.InvalidAudienceException((enums.Errors.INVALID_AUDIENCE_ERROR)))

Get audience object for the provided audience ID.

Args:
audience_id: ID of the audience.

Returns:
Dict representing the audience.


def get(self, branch='master', filename=''):

        file_contents = ''

        if self.runway_dir:
            file_contents = self.local_file(filename=filename)
        else:
            file_contents = self.remote_file(branch=branch, filename=filename)

        return file_contents

Retrieve _filename_ from GitLab.

Args:
branch (str): Git Branch to find file.
filename (str): Name of file to retrieve relative to root of Git
repository, or _runway_dir_ if specified.

Returns:
str: Contents of file.


def load_strain(self, strain_id, strain_genome_file):
    strain_gp = GEMPRO(gem_name=strain_id, genome_path=strain_genome_file, write_protein_fasta_files=False)
    self.strains.append(strain_gp)
    return self.strains.get_by_id(strain_id)

Load a strain as a new GEM-PRO by its ID and associated genome file. Stored in the ``strains`` attribute.

Args:
strain_id (str): Strain ID
strain_genome_file (str): Path to strain genome file


def SignFile(self, in_filename, out_filename=None):

    if out_filename is None:
      out_filename = "%s.signed" % in_filename

    args = [
        "-certs", self.cert, "-key", self.key, "-n", self.application, "-t",
        "http:
        "-in", in_filename, "-out", out_filename
    ]

    try:
      output_log = io.StringIO()
      ossl = pexpect.spawn("osslsigncode", args)

      ossl.logfile_read = output_log
      ossl.expect("Enter PEM pass phrase")
      ossl.sendline(self.password)
      ossl.wait()
    except pexpect.ExceptionPexpect:
      output_log.seek(0)
      logging.exception(output_log.read())
      raise

    if not os.path.exists(out_filename):
      raise SigningError("Expected output %s not created" % out_filename)

    try:
      subprocess.check_call(["osslsigncode", "verify", "-in", out_filename])
    except subprocess.CalledProcessError:
      logging.exception("Bad signature verification on %s", out_filename)
      raise SigningError("Bad signature verification on %s" % out_filename)

    return out_filename

Sign a file using osslsigncode.

Args:
in_filename: file to read from
out_filename: file to output to, if none we output to the same filename as
the input with a .signed suffix.

Returns:
output filename string
Raises:
pexpect.ExceptionPexpect: if the expect invocation of osslsigncode fails.
SigningError: for signing failures.


def save_checkpoint(model, filename, optimizer=None, meta=None):
    if (meta is None):
        meta = {}
    elif (not isinstance(meta, dict)):
        raise TypeError('meta must be a dict or None, but got {}'.format(type(meta)))
    meta.update(mmcv_version=mmcv.__version__, time=time.asctime())
    mmcv.mkdir_or_exist(osp.dirname(filename))
    if hasattr(model, 'module'):
        model = model.module
    checkpoint = {'meta': meta, 'state_dict': weights_to_cpu(model.state_dict())}
    if (optimizer is not None):
        checkpoint['optimizer'] = optimizer.state_dict()
    torch.save(checkpoint, filename)

Save checkpoint to file.

The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
``optimizer``. By default ``meta`` will contain version and time info.

Args:
model (Module): Module whose params are to be saved.
filename (str): Checkpoint filename.
optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
meta (dict, optional): Metadata to be saved in checkpoint.


def _check_sensor_platform_consistency(self, sensor):
    ref_sensor = SENSORS.get(self.platform, None)
    if (ref_sensor and (not (sensor == ref_sensor))):
        logger.error('Sensor-Platform mismatch: {} is not a payload of {}. Did you choose the correct reader?'.format(sensor, self.platform))

Make sure sensor and platform are consistent

Args:
sensor (str) : Sensor name from YAML dataset definition

Raises:
ValueError if they don't match


def read_config(config_filepath, logger=logging.getLogger('ProsperCommon')):
    config_parser = configparser.ConfigParser(interpolation=ExtendedInterpolation(), allow_no_value=True, delimiters='=', inline_comment_prefixes='
    logger.debug('config_filepath=%s', config_filepath)
    with open(config_filepath, 'r') as filehandle:
        config_parser.read_file(filehandle)
    return config_parser

fetch and parse config file

Args:
config_filepath (str): path to config file.  abspath > relpath
logger (:obj:`logging.Logger`): logger to catch error msgs


def Check(self, error, filename, linenum):
    if Match('T(EST|est)', self.current_function):
        base_trigger = self._TEST_TRIGGER
    else:
        base_trigger = self._NORMAL_TRIGGER
    trigger = (base_trigger * (2 ** _VerboseLevel()))
    if (self.lines_in_function > trigger):
        error_level = int(math.log((self.lines_in_function / base_trigger), 2))
        if (error_level > 5):
            error_level = 5
        error(filename, linenum, 'readability/fn_size', error_level, ('Small and focused functions are preferred: %s has %d non-comment lines (error triggered by exceeding %d lines).' % (self.current_function, self.lines_in_function, trigger)))

Report if too many lines in function body.

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


def instance_default(self, obj):

        return self.property.themed_default(obj.__class__, self.name, obj.themed_values())

Get the default value that will be used for a specific instance.

Args:
obj (HasProps) : The instance to get the default value for.

Returns:
object


def exists(self, path: str) -> bool:
    raise NotImplementedError

Check if the provided path exists on the FileSystem.

Args:
path: string path that needs to be checked.

Returns: boolean flag indicating if path exists


def _eligible_features_from_example_handler(self, request):
    features_list = inference_utils.get_eligible_features(self.examples[0:NUM_EXAMPLES_TO_SCAN], NUM_MUTANTS)
    return http_util.Respond(request, features_list, 'application/json')

Returns a list of JSON objects for each feature in the example.

Args:
request: A request for features.

Returns:
A list with a JSON object for each feature.
Numeric features are represented as {name: observedMin: observedMax:}.
Categorical features are repesented as {name: samples:[]}.


def plot_stacked_hist(self, key="wall_time", nmax=5, ax=None, **kwargs):

        ax, fig, plt = get_ax_fig_plt(ax=ax)

        mpi_rank = "0"
        timers = self.timers(mpi_rank=mpi_rank)
        n = len(timers)

        names, values = [], []
        rest = np.zeros(n)

        for idx, sname in enumerate(self.section_names(ordkey=key)):
            sections = self.get_sections(sname)
            svals = np.asarray([s.__dict__[key] for s in sections])
            if idx < nmax:
                names.append(sname)
                values.append(svals)
            else:
                rest += svals

        names.append("others (nmax=%d)" % nmax)
        values.append(rest)

        ind = np.arange(n)
        width = 0.35
        colors = nmax * ['r', 'g', 'b', 'c', 'k', 'y', 'm']

        bars = []
        bottom = np.zeros(n)
        for idx, vals in enumerate(values):
            color = colors[idx]
            bar = ax.bar(ind, vals, width, color=color, bottom=bottom)
            bars.append(bar)
            bottom += vals

        ax.set_ylabel(key)
        ax.set_title("Stacked histogram with the %d most important sections" % nmax)

        ticks = ind + width / 2.0
        labels = ["MPI=%d, OMP=%d" % (t.mpi_nprocs, t.omp_nthreads) for t in timers]
        ax.set_xticks(ticks)
        ax.set_xticklabels(labels, rotation=15)

        ax.legend([bar[0] for bar in bars], names, loc="best")

        return fig

Plot stacked histogram of the different timers.

Args:
key: Keyword used to extract data from the timers. Only the first `nmax`
sections with largest value are show.
mmax: Maximum nuber of sections to show. Other entries are grouped together
in the `others` section.
ax: matplotlib :class:`Axes` or None if a new figure should be created.

Returns:
`matplotlib` figure


def array(self):
    url = '{}/{}'.format(__endpoint__, self.type.RESOURCE)
    return RestClient.get(url, self.params)[self.type.RESOURCE]

Get all resources and return the result as an array

Returns:
array of str: Array of resources


def createCategoryFilter(self, retina_name, filter_name, body, ):

        resourcePath = '/classify/create_category_filter'
        method = 'POST'

        queryParams = {}
        headerParams = {'Accept': 'Application/json', 'Content-Type': 'application/json'}
        postData = None

        queryParams['retina_name'] = retina_name
        queryParams['filter_name'] = filter_name
        postData = body
        response = self.apiClient._callAPI(resourcePath, method, queryParams, postData, headerParams)

        return category_filter.CategoryFilter(**response.json())

get filter for classifier
Args:
filter_name, str: A unique name for the filter. (required)
body, FilterTrainingObject: The list of positive and negative (optional) example items. (required)
retina_name, str: The retina name (required)
Returns: CategoryFilter


class AlignVisionBlock(nn.Module):

    def __init__(self, config: AlignVisionConfig, in_dim: int, out_dim: int, stride: int, expand_ratio: int, kernel_size: int, drop_rate: float, id_skip: bool, adjust_padding: bool):
        super().__init__()
        self.expand_ratio = expand_ratio
        self.expand = True if self.expand_ratio != 1 else False
        expand_in_dim = in_dim * expand_ratio
        if self.expand:
            self.expansion = AlignVisionExpansionLayer(config=config, in_dim=in_dim, out_dim=expand_in_dim, stride=stride)
        self.depthwise_conv = AlignVisionDepthwiseLayer(config=config, in_dim=expand_in_dim if self.expand else in_dim, stride=stride, kernel_size=kernel_size, adjust_padding=adjust_padding)
        self.squeeze_excite = AlignVisionSqueezeExciteLayer(config=config, in_dim=in_dim, expand_dim=expand_in_dim, expand=self.expand)
        self.projection = AlignVisionFinalBlockLayer(config=config, in_dim=expand_in_dim if self.expand else in_dim, out_dim=out_dim, stride=stride, drop_rate=drop_rate, id_skip=id_skip)

    def forward(self, hidden_states: torch.FloatTensor) -> torch.Tensor:
        embeddings = hidden_states
        if self.expand_ratio != 1:
            hidden_states = self.expansion(hidden_states)
        hidden_states = self.depthwise_conv(hidden_states)
        hidden_states = self.squeeze_excite(hidden_states)
        hidden_states = self.projection(embeddings, hidden_states)
        return hidden_states

This corresponds to the block module of original the EfficientNet vision encoder implementation.

Args:
config ([`AlignVisionConfig`]):
Model configuration class.
in_dim (`int`):
Number of input channels.
out_dim (`int`):
Number of output channels.
stride (`int`):
Stride size to be used in convolution layers.
expand_ratio (`int`):
Expand ratio to set the output dimensions for the expansion and squeeze-excite layers.
kernel_size (`int`):
Kernel size for the depthwise convolution layer.
drop_rate (`float`):
Dropout rate to be used in the final phase of each block.
id_skip (`bool`):
Whether to apply dropout and sum the final hidden states with the input embeddings during the final phase
of each block. Set to `True` for the first block of each stage.
adjust_padding (`bool`):
Whether to apply padding to only right and bottom side of the input kernel before the depthwise convolution
operation, set to `True` for inputs with odd input sizes.


def trace_buffer_capacity(self):
    cmd = enums.JLinkTraceCommand.GET_CONF_CAPACITY
    data = ctypes.c_uint32(0)
    res = self._dll.JLINKARM_TRACE_Control(cmd, ctypes.byref(data))
    if (res == 1):
        raise errors.JLinkException('Failed to get trace buffer size.')
    return data.value

Retrieves the trace buffer's current capacity.

Args:
self (JLink): the ``JLink`` instance.

Returns:
The current capacity of the trace buffer.  This is not necessarily
the maximum possible size the buffer could be configured with.