def get_forced_variation(self, experiment_key, user_id):
    if (not self.is_valid):
        self.logger.error(enums.Errors.INVALID_DATAFILE.format('get_forced_variation'))
        return None
    if (not validator.is_non_empty_string(experiment_key)):
        self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('experiment_key'))
        return None
    if (not isinstance(user_id, string_types)):
        self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('user_id'))
        return None
    forced_variation = self.config.get_forced_variation(experiment_key, user_id)
    return (forced_variation.key if forced_variation else None)

Gets the forced variation for a given user and experiment.

Args:
experiment_key: A string key identifying the experiment.
user_id: The user ID.

Returns:
The forced variation key. None if no forced variation key.


def insert_before(self, value: Union[RawValue, Value],
                      raw: bool = False) -> "ArrayEntry":

        return ArrayEntry(self.index, self.before, self.after.cons(self.value),
                          self._cook_value(value, raw), self.parinst,
                          self.schema_node, datetime.now())

Insert a new entry before the receiver.

Args:
value: The value of the new entry.
raw: Flag to be set if `value` is raw.

Returns:
An instance node of the new inserted entry.


def Artifacts(self, os_name=None, cpe=None, label=None):
    hit = (lambda x: ((x[0] == x[1]) or (not x[0])))
    seq = [(self.os_name, os_name), (self.cpe, cpe), (self.label, label)]
    return all(map(hit, seq))

Whether the conditions applies, modulo host data.

Args:
os_name: An OS string.
cpe: A CPE string.
label: A label string.

Returns:
True if os_name, cpe or labels match. Empty values are ignored.


async def game(
            self, short_name, *, id=None,
            text=None, parse_mode=(), link_preview=True,
            geo=None, period=60, contact=None, game=False, buttons=None
    ):

        result = types.InputBotInlineResultGame(
            id=id or '',
            short_name=short_name,
            send_message=await self._message(
                text=text, parse_mode=parse_mode, link_preview=link_preview,
                geo=geo, period=period,
                contact=contact,
                game=game,
                buttons=buttons
            )
        )
        if id is None:
            result.id = hashlib.sha256(bytes(result)).hexdigest()

        return result

Creates a new inline result of game type.

Args:
short_name (`str`):
The short name of the game to use.


def Analyze(self, source_path, output_writer):
    if (not os.path.exists(source_path)):
        raise RuntimeError('No such source: {0:s}.'.format(source_path))
    scan_context = source_scanner.SourceScannerContext()
    scan_path_spec = None
    scan_step = 0
    scan_context.OpenSourcePath(source_path)
    while True:
        self._source_scanner.Scan(scan_context, auto_recurse=self._auto_recurse, scan_path_spec=scan_path_spec)
        if (not scan_context.updated):
            break
        if (not self._auto_recurse):
            output_writer.WriteScanContext(scan_context, scan_step=scan_step)
        scan_step += 1
        if (scan_context.source_type in [definitions.SOURCE_TYPE_DIRECTORY, definitions.SOURCE_TYPE_FILE]):
            break
        for locked_scan_node in scan_context.locked_scan_nodes:
            self._PromptUserForEncryptedVolumeCredential(scan_context, locked_scan_node, output_writer)
        if (not self._auto_recurse):
            scan_node = scan_context.GetUnscannedScanNode()
            if (not scan_node):
                return
            scan_path_spec = scan_node.path_spec
    if self._auto_recurse:
        output_writer.WriteScanContext(scan_context)

Analyzes the source.

Args:
source_path (str): the source path.
output_writer (StdoutWriter): the output writer.

Raises:
RuntimeError: if the source path does not exists, or if the source path
is not a file or directory, or if the format of or within the source
file is not supported.


def get_site_spd_dos(self, site):

        spd_dos = dict()
        for orb, pdos in self.pdos[site].items():
            orbital_type = _get_orb_type(orb)
            if orbital_type in spd_dos:
                spd_dos[orbital_type] = add_densities(spd_dos[orbital_type], pdos)
            else:
                spd_dos[orbital_type] = pdos
        return {orb: Dos(self.efermi, self.energies, densities)
                for orb, densities in spd_dos.items()}

Get orbital projected Dos of a particular site

Args:
site: Site in Structure associated with CompleteDos.

Returns:
dict of {orbital: Dos}, e.g. {"s": Dos object, ...}


def rot90(array, k=1, axes=(0, 1)):
    array = convert_to_tensor(array)
    if array.shape.rank < 2:
        raise ValueError(f'Input array must have at least 2 dimensions. Received: array.ndim={array.shape.rank}')
    if len(axes) != 2 or axes[0] == axes[1]:
        raise ValueError(f'Invalid axes: {axes}. Axes must be a tuple of two different dimensions.')
    k = k % 4
    if k == 0:
        return array
    axes = tuple((axis if axis >= 0 else array.shape.rank + axis for axis in axes))
    perm = [i for i in range(array.shape.rank) if i not in axes]
    perm.extend(axes)
    array = tf.transpose(array, perm)
    shape = tf.shape(array)
    non_rot_shape = shape[:-2]
    h, w = (shape[-2], shape[-1])
    array = tf.reshape(array, tf.concat([[-1], [h, w]], axis=0))
    array = tf.reverse(array, axis=[2])
    array = tf.transpose(array, [0, 2, 1])
    if k % 2 == 1:
        final_h, final_w = (w, h)
    else:
        final_h, final_w = (h, w)
    if k > 1:
        array = tf.reshape(array, tf.concat([[-1], [final_h, final_w]], axis=0))
        for _ in range(k - 1):
            array = tf.reverse(array, axis=[2])
            array = tf.transpose(array, [0, 2, 1])
    final_shape = tf.concat([non_rot_shape, [final_h, final_w]], axis=0)
    array = tf.reshape(array, final_shape)
    inv_perm = [0] * len(perm)
    for i, p in enumerate(perm):
        inv_perm[p] = i
    array = tf.transpose(array, inv_perm)
    return array

Rotate an array by 90 degrees in the specified plane.

Args:
array: Input tensor
k: Number of 90-degree rotations (default=1)
axes: Tuple of two axes that define the plane of rotation.
Defaults to (0, 1).

Returns:
Rotated tensor with correct shape transformation


def update(self, id, newObj):

        newObj = self.validation(newObj)
        for obj in self.model.db:
            if obj["id"] != id:
                continue

            newObj.pop("id", None)
            obj.update(newObj)
            obj = self._cast_model(obj)
            if not self._batch.enable.is_set():
                self.model.save_db()
            return obj

        return None

Update a object
Args:
id (int): Target Object ID
newObj (object): New object will be merged into original object
Returns:
Object: Updated object
None: If specified object id is not found
MultipleInvalid: If input object is invaild


def grappler_optimize(graph, fetches=None, config_proto=None):
    if config_proto is None:
        config_proto = config_pb2.ConfigProto()
        config_proto.graph_options.rewrite_options.min_graph_nodes = -1
    if fetches is not None:
        for fetch in fetches:
            graph.add_to_collection('train_op', fetch)
    metagraph = saver.export_meta_graph(graph_def=graph.as_graph_def())
    return tf_optimizer.OptimizeGraph(config_proto, metagraph)

Tries to optimize the provided graph using grappler.

Args:
graph: A `tf.Graph` instance containing the graph to optimize.
fetches: An optional list of `Tensor`s to fetch (i.e. not optimize away).
Grappler uses the 'train_op' collection to look for fetches, so if not
provided this collection should be non-empty.
config_proto: An optional `tf.compat.v1.ConfigProto` to use when rewriting
the graph.

Returns:
A `tf.compat.v1.GraphDef` containing the rewritten graph.


def apply_inverse(self, y, in_place=False):
        r
        return cho_solve(self._factor, y, overwrite_b=in_place)

r"""
Apply the inverse of the covariance matrix to the input by solving

.. math::

K\,x = y

Args:
y (ndarray[nsamples] or ndadrray[nsamples, nrhs]): The vector or
matrix :math:`y`.
in_place (Optional[bool]): Should the data in ``y`` be overwritten
with the result :math:`x`? (default: ``False``)


def to_csv(self, filename: str, latexify_names: bool=False):
    elements = set()
    for entry in self.entries:
        elements.update(entry.composition.elements)
    elements = sorted(list(elements), key=(lambda a: a.X))
    writer = csv.writer(open(filename, 'w'), delimiter=unicode2str(','), quotechar=unicode2str('"'), quoting=csv.QUOTE_MINIMAL)
    writer.writerow(((['Name'] + elements) + ['Energy']))
    for entry in self.entries:
        row = [(entry.name if (not latexify_names) else re.sub('([0-9]+)', '_{\\1}', entry.name))]
        row.extend([entry.composition[el] for el in elements])
        row.append(entry.energy)
        writer.writerow(row)

Exports PDEntries to a csv

Args:
filename: Filename to write to.
entries: PDEntries to export.
latexify_names: Format entry names to be LaTex compatible,
e.g., Li_{2}O


def default(self, obj):
    if isinstance(obj, decimal.Decimal):
        obj = format(obj, 'f')
        str_digit = text_type(obj)
        return (str_digit.rstrip('0').rstrip('.') if ('.' in str_digit) else str_digit)
    elif isinstance(obj, phonenumbers.PhoneNumber):
        return phonenumbers.format_number(obj, phonenumbers.PhoneNumberFormat.E164)
    elif isinstance(obj, pendulum.Pendulum):
        return text_type(obj)
    elif isinstance(obj, arrow.Arrow):
        return text_type(obj)
    elif isinstance(obj, (datetime.datetime, datetime.date)):
        return obj.isoformat()
    try:
        return list(iter(obj))
    except TypeError:
        pass
    return super(FleakerJSONEncoder, self).default(obj)

Encode individual objects into their JSON representation.

This method is used by :class:`flask.json.JSONEncoder` to encode
individual items in the JSON object.

Args:
obj (object): Any Python object we wish to convert to JSON.

Returns:
str: The stringified, valid JSON representation of our provided
object.


def index(self, entries):
    if (not self.is_empty()):
        raise ValueError('Cannot call index again on a non-empty index')
    if (not isinstance(entries, list)):
        queue = deque([])
        for (key, minhash, size) in entries:
            if (size <= 0):
                raise ValueError('Set size must be positive')
            queue.append((key, minhash, size))
        entries = list(queue)
    if (len(entries) == 0):
        raise ValueError('entries is empty')
    (sizes, counts) = np.array(sorted(Counter((e[2] for e in entries)).most_common())).T
    partitions = optimal_partitions(sizes, counts, len(self.indexes))
    for (i, (lower, upper)) in enumerate(partitions):
        (self.lowers[i], self.uppers[i]) = (lower, upper)
    entries.sort(key=(lambda e: e[2]))
    curr_part = 0
    for (key, minhash, size) in entries:
        if (size > self.uppers[curr_part]):
            curr_part += 1
        for r in self.indexes[curr_part]:
            self.indexes[curr_part][r].insert(key, minhash)

Index all sets given their keys, MinHashes, and sizes.
It can be called only once after the index is created.

Args:
entries (`iterable` of `tuple`): An iterable of tuples, each must be
in the form of `(key, minhash, size)`, where `key` is the unique
identifier of a set, `minhash` is the MinHash of the set,
and `size` is the size or number of unique items in the set.

Note:
`size` must be positive.


def _parse_block_ref(cls, block_ref, deprecated=False):
    if (deprecated and (block_ref is None)):
        return None
    if isinstance(block_ref, LocalId):
        return block_ref
    is_valid_deprecated = (deprecated and cls.DEPRECATED_ALLOWED_ID_RE.match(block_ref))
    is_valid = cls.ALLOWED_ID_RE.match(block_ref)
    if (is_valid or is_valid_deprecated):
        return block_ref
    else:
        raise InvalidKeyError(cls, block_ref)

Given `block_ref`, tries to parse it into a valid block reference.

Returns `block_ref` if it is valid.

Raises:
InvalidKeyError: if `block_ref` is invalid.


def set_card_simple(self, title, content):

        self.response.card.type = 'Simple'
        self.response.card.title = title
        self.response.card.content = content

Set response card as simple type.

title and content cannot exceed 8,000 characters.

Args:
title: str. Title of Simple or Standard type card.
content: str. Content of Simple type card.


def control(controllee: Union[('cirq.Gate', op_tree.OP_TREE)], control_qubits: Sequence['cirq.Qid']=None, default: Any=RaiseTypeErrorIfNotProvided) -> Any:
    if (control_qubits is None):
        control_qubits = []
    controller = getattr(controllee, 'controlled_by', None)
    result = (NotImplemented if (controller is None) else controller(*control_qubits))
    if (result is not NotImplemented):
        return result
    if isinstance(controllee, collections.Iterable):
        return op_tree.transform_op_tree(controllee, op_transformation=(lambda op: control(op, control_qubits)))
    if (default is not RaiseTypeErrorIfNotProvided):
        return default
    if (controller is None):
        raise TypeError("object of type '{}' has no controlled_by method.".format(type(controllee)))
    raise TypeError("object of type '{}' does have a controlled_by method, but it returned NotImplemented.".format(type(controllee)))

Returns a Controlled version of the given value, if defined.

Controllees define how to be controlled by defining a method
controlled_by(self, control_qubits). Note that the method may return
NotImplemented to indicate a particular controlling can't be done.

Args:
controllee: The gate, operation or iterable of operations to control.
control_qubits: A list of Qids that would control this controllee.
default: Determines the fallback behavior when `controllee` doesn't
have a controlling defined. If `default` is not set and the
fallback occurs, a TypeError is raised instead.

Returns:
If `controllee` has a controlled_by method that returns something
besides NotImplemented, that result is returned. For an OP_TREE,
transformation is applied at the leaf. Otherwise, if a default value
was specified, the default value is returned.

Raises:
TypeError: `controllee` doesn't have a controlled_by method (or that
method returned NotImplemented) and no `default` was specified.


def validate_composite_type_param(type_param, error_msg_prefix):
    possible_classes = [type, TypeConstraint]
    is_not_type_constraint = not is_typing_generic(type_param) and (not isinstance(type_param, tuple(possible_classes))) and (type_param is not None) and (getattr(type_param, '__module__', None) != 'typing')
    if sys.version_info.major == 3 and sys.version_info.minor >= 10:
        if isinstance(type_param, types.UnionType):
            is_not_type_constraint = False
    if is_not_type_constraint:
        raise TypeError('%s must be a non-sequence, a type, or a TypeConstraint. %s is an instance of %s.' % (error_msg_prefix, type_param, type_param.__class__.__name__))

Determines if an object is a valid type parameter to a
:class:`CompositeTypeHint`.

Implements sanity checking to disallow things like::

List[1, 2, 3] or Dict[5].

Args:
type_param: An object instance.
error_msg_prefix (:class:`str`): A string prefix used to format an error
message in the case of an exception.

Raises:
TypeError: If the passed **type_param** is not a valid type
parameter for a :class:`CompositeTypeHint`.


def Get(self, name, default=utils.NotAValue, context=None):
    if (not self.initialized):
        if (name not in self.constants):
            raise RuntimeError(("Error while retrieving %s: Configuration hasn't been initialized yet." % name))
    if context:
        if (isinstance(context, string_types) or (not isinstance(context, collections.Iterable))):
            raise ValueError(('context should be a list, got %r' % context))
    calc_context = context
    cache_key = (name, tuple((context or ())))
    if ((default is utils.NotAValue) and (cache_key in self.cache)):
        return self.cache[cache_key]
    if (context is None):
        calc_context = self.context
    type_info_obj = self.FindTypeInfo(name)
    (_, return_value) = self._GetValue(name, context=calc_context, default=default)
    if (return_value is default):
        return default
    try:
        return_value = self.InterpolateValue(return_value, default_section=name.split('.')[0], type_info_obj=type_info_obj, context=calc_context)
    except (lexer.ParseError, ValueError) as e:
        if (default is not utils.NotAValue):
            return default
        raise ConfigFormatError(('While parsing %s: %s' % (name, e)))
    try:
        new_value = type_info_obj.Validate(return_value)
        if (new_value is not None):
            return_value = new_value
    except ValueError:
        if (default is not utils.NotAValue):
            return default
        raise
    if (default is utils.NotAValue):
        self.cache[cache_key] = return_value
    return return_value

Get the value contained  by the named parameter.

This method applies interpolation/escaping of the named parameter and
retrieves the interpolated value.

Args:
name: The name of the parameter to retrieve. This should be in the format
of "Section.name"
default: If retrieving the value results in an error, return this default.
context: A list of context strings to resolve the configuration. This is a
set of roles the caller is current executing with. For example (client,
windows). If not specified we take the context from the current thread's
TLS stack.

Returns:
The value of the parameter.
Raises:
ConfigFormatError: if verify=True and the config doesn't validate.
RuntimeError: if a value is retrieved before the config is initialized.
ValueError: if a bad context is passed.


def utterances_from_dir(eaf_dir: Path, tier_prefixes: Tuple[(str, ...)]) -> List[Utterance]:
    logger.info('EAF from directory: {}, searching with tier_prefixes {}'.format(eaf_dir, tier_prefixes))
    utterances = []
    for eaf_path in eaf_dir.glob('**/*.eaf'):
        eaf_utterances = utterances_from_eaf(eaf_path, tier_prefixes)
        utterances.extend(eaf_utterances)
    return utterances

Returns the utterances found in ELAN files in a directory.

Recursively explores the directory, gathering ELAN files and extracting
utterances from them for tiers that start with the specified prefixes.

Args:
eaf_dir: A path to the directory to be searched
tier_prefixes: Stings matching the start of ELAN tier names that are to
be extracted. For example, if you want to extract from tiers "xv-Jane"
and "xv-Mark", then tier_prefixes = ["xv"] would do the job.

Returns:
A list of Utterance objects.


def loads(s, single=False, version=_default_version,
          strict=False, errors='warn'):

    ms = deserialize(s, version=version, strict=strict, errors=errors)
    if single:
        return next(ms)
    else:
        return ms

Deserialize SimpleMRS string representations

Args:
s (str): a SimpleMRS string
single (bool): if `True`, only return the first Xmrs object
Returns:
a generator of Xmrs objects (unless *single* is `True`)


def select_with_index(self, selector=IndexedElement, transform=identity):
    if self.closed():
        raise ValueError('Attempt to call select_with_index() on a closed Queryable.')
    if (not is_callable(selector)):
        raise TypeError('select_with_index() parameter selector={0} is not callable'.format(repr(selector)))
    if (not is_callable(transform)):
        raise TypeError('select_with_index() parameter item_selector={0} is not callable'.format(repr(selector)))
    return self._create(itertools.starmap(selector, enumerate(imap(transform, iter(self)))))

Transforms each element of a sequence into a new form, incorporating
the index of the element.

Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.

Note: This method uses deferred execution.

Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().

Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence

Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.


def _ParseMFTAttribute(self, parser_mediator, mft_entry, mft_attribute):

    if mft_entry.is_empty() or mft_entry.base_record_file_reference != 0:
      return

    if mft_attribute.attribute_type in [
        self._MFT_ATTRIBUTE_STANDARD_INFORMATION,
        self._MFT_ATTRIBUTE_FILE_NAME]:

      file_attribute_flags = getattr(
          mft_attribute, 'file_attribute_flags', None)
      name = getattr(mft_attribute, 'name', None)
      parent_file_reference = getattr(
          mft_attribute, 'parent_file_reference', None)

      event_data = NTFSFileStatEventData()
      event_data.attribute_type = mft_attribute.attribute_type
      event_data.file_attribute_flags = file_attribute_flags
      event_data.file_reference = mft_entry.file_reference
      event_data.is_allocated = mft_entry.is_allocated()
      event_data.name = name
      event_data.parent_file_reference = parent_file_reference

      try:
        creation_time = mft_attribute.get_creation_time_as_integer()
      except OverflowError as exception:
        parser_mediator.ProduceExtractionWarning((
            'unable to read the creation timestamp from MFT attribute: '
            '0x{0:08x} with error: {1!s}').format(
                mft_attribute.attribute_type, exception))
        creation_time = None

      if creation_time is not None:
        date_time = self._GetDateTime(creation_time)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_CREATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)

      try:
        modification_time = mft_attribute.get_modification_time_as_integer()
      except OverflowError as exception:
        parser_mediator.ProduceExtractionWarning((
            'unable to read the modification timestamp from MFT attribute: '
            '0x{0:08x} with error: {1!s}').format(
                mft_attribute.attribute_type, exception))
        modification_time = None

      if modification_time is not None:
        date_time = self._GetDateTime(modification_time)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_MODIFICATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)

      try:
        access_time = mft_attribute.get_access_time_as_integer()
      except OverflowError as exception:
        parser_mediator.ProduceExtractionWarning((
            'unable to read the access timestamp from MFT attribute: '
            '0x{0:08x} with error: {1!s}').format(
                exception, mft_attribute.attribute_type))
        access_time = None

      if access_time is not None:
        date_time = self._GetDateTime(access_time)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_LAST_ACCESS)
        parser_mediator.ProduceEventWithEventData(event, event_data)

      try:
        entry_modification_time = (
            mft_attribute.get_entry_modification_time_as_integer())
      except OverflowError as exception:
        parser_mediator.ProduceExtractionWarning((
            'unable to read the entry modification timestamp from MFT '
            'attribute: 0x{0:08x} with error: {1!s}').format(
                mft_attribute.attribute_type, exception))
        entry_modification_time = None

      if entry_modification_time is not None:
        date_time = self._GetDateTime(entry_modification_time)
        event = time_events.DateTimeValuesEvent(
            date_time, definitions.TIME_DESCRIPTION_ENTRY_MODIFICATION)
        parser_mediator.ProduceEventWithEventData(event, event_data)

    elif mft_attribute.attribute_type == self._MFT_ATTRIBUTE_OBJECT_ID:
      display_name = '$MFT: {0:d}-{1:d}'.format(
          mft_entry.file_reference & 0xffffffffffff,
          mft_entry.file_reference >> 48)

      if mft_attribute.droid_file_identifier:
        try:
          self._ParseDistributedTrackingIdentifier(
              parser_mediator, mft_attribute.droid_file_identifier,
              display_name)

        except (TypeError, ValueError) as exception:
          parser_mediator.ProduceExtractionWarning((
              'unable to read droid file identifier from attribute: 0x{0:08x} '
              'with error: {1!s}').format(
                  mft_attribute.attribute_type, exception))

      if mft_attribute.birth_droid_file_identifier:
        try:
          self._ParseDistributedTrackingIdentifier(
              parser_mediator, mft_attribute.droid_file_identifier,
              display_name)

        except (TypeError, ValueError) as exception:
          parser_mediator.ProduceExtractionWarning((
              'unable to read birth droid file identifier from attribute: '
              '0x{0:08x} with error: {1!s}').format(
                  mft_attribute.attribute_type, exception))

Extract data from a NFTS $MFT attribute.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
mft_entry (pyfsntfs.file_entry): MFT entry.
mft_attribute (pyfsntfs.attribute): MFT attribute.


def _ParseSourcePathOption(self, options):

    self._source_path = self.ParseStringOption(options, self._SOURCE_OPTION)
    if not self._source_path:
      raise errors.BadConfigOption('Missing source path.')

    self._source_path = os.path.abspath(self._source_path)

Parses the source path option.

Args:
options (argparse.Namespace): command line arguments.

Raises:
BadConfigOption: if the options are invalid.


def add_outbound_connection(self, uri):

        LOGGER.debug("Adding connection to %s", uri)
        conn = OutboundConnection(
            connections=self._connections,
            endpoint=uri,
            dispatcher=self._dispatcher,
            zmq_identity=self._zmq_identity,
            secured=self._secured,
            server_public_key=self._server_public_key,
            server_private_key=self._server_private_key,
            future_callback_threadpool=self._future_callback_threadpool,
            heartbeat=True,
            connection_timeout=self._connection_timeout)

        self.outbound_connections[uri] = conn
        conn.start()

        self._add_connection(conn, uri)

        connect_message = ConnectionRequest(endpoint=self._public_endpoint)
        conn.send(
            validator_pb2.Message.NETWORK_CONNECT,
            connect_message.SerializeToString(),
            callback=partial(
                self._connect_callback,
                connection=conn,
            ))

        return conn

Adds an outbound connection to the network.

Args:
uri (str): The zmq-style (e.g. tcp://hostname:port) uri
to attempt to connect to.


def __eq__(self, other):

        res = False
        if len(self) == len(other):
            if np.all(self._z == other.z) and np.all(self._x == other.x):
                res = True
        return res

Return True if all Pauli terms are equal.

Args:
other (Pauli): other pauli

Returns:
bool: are self and other equal.


def imresize(img, size, return_scale=False, interpolation='bilinear'):
    (h, w) = img.shape[:2]
    resized_img = cv2.resize(img, size, interpolation=interp_codes[interpolation])
    if (not return_scale):
        return resized_img
    else:
        w_scale = (size[0] / w)
        h_scale = (size[1] / h)
        return (resized_img, w_scale, h_scale)

Resize image to a given size.

Args:
img (ndarray): The input image.
size (tuple): Target (w, h).
return_scale (bool): Whether to return `w_scale` and `h_scale`.
interpolation (str): Interpolation method, accepted values are
"nearest", "bilinear", "bicubic", "area", "lanczos".

Returns:
tuple or ndarray: (`resized_img`, `w_scale`, `h_scale`) or
`resized_img`.


def scan_meta_graph_def(meta_graph_def, op_denylist):
    ops_in_metagraph = set(meta_graph_lib.ops_used_by_graph_def(meta_graph_def.graph_def))
    denylisted_ops = op_denylist & ops_in_metagraph
    if denylisted_ops:
        print('MetaGraph with tag set %s contains the following denylisted ops:' % meta_graph_def.meta_info_def.tags, denylisted_ops)
    else:
        print('MetaGraph with tag set %s does not contain the default denylisted ops:' % meta_graph_def.meta_info_def.tags, op_denylist)

Scans meta_graph_def and reports if there are ops on denylist.

Print ops if they are on denylist, or print success if no denylisted ops
found.

Args:
meta_graph_def: MetaGraphDef protocol buffer.
op_denylist: set of ops to scan for.


def report_error(self, read_tuple_name, error_name, wrong='', message='', warning=False):
    if ((not self.report_only_first) or (error_name not in self.reported_errors)):
        print('\t'.join([('error' if (warning == False) else 'warning'), read_tuple_name, error_name, wrong, message]))
    self.reported_errors.add(error_name)
    if warning:
        self.warning_has_been_reported = True
    else:
        self.error_has_been_reported = True

Report an error.

Args:
read_tuple_name (): Name of the read tuple.
error_name (): Name of the error.
wrong (str): What is wrong.
message (str): Additional msessage to be printed.
warning (bool): Warning (not an error).


def assign_device(cls, core):
    return Sharding(proto=xla_data_pb2.OpSharding(type=xla_data_pb2.OpSharding.MAXIMAL, tile_assignment_dimensions=[1], tile_assignment_devices=[core]))

Returns an AssignDevice sharding attribute.

This causes an op to be computed in its entirety only on one core in
the XLA device.
Args:
core: The core to assign this Op to.


def get_url_distribution(self, params=None):

        params = params or {}
        all_responses = {}
        api_name = 'virustotal-url-distribution'

        response_chunks = self._request_reports(list(params.keys()), list(params.values()), 'url/distribution')
        self._extract_response_chunks(all_responses, response_chunks, api_name)

        return all_responses

Retrieves a live feed with the latest URLs submitted to VT.

Args:
resources: a dictionary with name and value for optional arguments
Returns:
A dict with the VT report.


def func_load(code, defaults=None, closure=None, globs=None):
    if isinstance(code, (tuple, list)):
        code, defaults, closure = code
        if isinstance(defaults, list):
            defaults = tuple(defaults)

    def ensure_value_to_cell(value):

        def dummy_fn():
            value
        cell_value = dummy_fn.__closure__[0]
        if not isinstance(value, type(cell_value)):
            return cell_value
        return value
    if closure is not None:
        closure = tuple((ensure_value_to_cell(_) for _ in closure))
    try:
        raw_code = codecs.decode(code.encode('ascii'), 'base64')
    except (UnicodeEncodeError, binascii.Error):
        raw_code = code.encode('raw_unicode_escape')
    code = marshal.loads(raw_code)
    if globs is None:
        globs = globals()
    return python_types.FunctionType(code, globs, name=code.co_name, argdefs=defaults, closure=closure)

Deserializes a user defined function.

Args:
code: bytecode of the function.
defaults: defaults of the function.
closure: closure of the function.
globs: dictionary of global objects.

Returns:
A function object.


def restore(self, state):

        self._clear()
        self._parseUserInfo({'labels': state['labels']})
        self._parseNodes(state['nodes'])
        self._keep_version = state['keep_version']

Unserialize saved note data.

Args:
state (dict): Serialized state to load.


def get_or_create_hosted_zone(client, zone_name):
    zone_id = get_hosted_zone_by_name(client, zone_name)
    if zone_id:
        return zone_id
    logger.debug('Zone %s does not exist, creating.', zone_name)
    reference = uuid.uuid4().hex
    response = client.create_hosted_zone(Name=zone_name, CallerReference=reference)
    return parse_zone_id(response['HostedZone']['Id'])

Get the Id of an existing zone, or create it.

Args:
client (:class:`botocore.client.Route53`): The connection used to
interact with Route53's API.
zone_name (string): The name of the DNS hosted zone to create.

Returns:
string: The Id of the Hosted Zone.


def get_end(pos, alt, category, snvend=None, svend=None, svlen=None):
    end = pos
    if (category in ('snv', 'indel', 'cancer')):
        end = snvend
    elif (category == 'sv'):
        end = svend
        if (svend == pos):
            if svlen:
                end = (pos + svlen)
        if (':' in alt):
            match = BND_ALT_PATTERN.match(alt)
            if match:
                end = int(match.group(2))
    return end

Return the end coordinate for a variant

Args:
pos(int)
alt(str)
category(str)
snvend(str)
svend(int)
svlen(int)

Returns:
end(int)


def __eq__(self, other):
    return isinstance(other, ArgumentPlaceholder)

Tests for equality of two placeholder objects.

Args:
other: Another placeholder object to compare to.

This method is used only for test code. All placeholder objects are
equal to each other.


def __init__(self, endpoint_name, sagemaker_session=None):

        super(ChainerPredictor, self).__init__(endpoint_name, sagemaker_session, npy_serializer, numpy_deserializer)

Initialize an ``ChainerPredictor``.

Args:
endpoint_name (str): The name of the endpoint to perform inference on.
sagemaker_session (sagemaker.session.Session): Session object which manages interactions with
Amazon SageMaker APIs and any other AWS services needed. If not specified, the estimator creates one
using the default AWS configuration chain.


def GetStorageMediaImageTypeIndicators(cls, path_spec, resolver_context=None):
    if ((cls._storage_media_image_remainder_list is None) or (cls._storage_media_image_store is None)):
        (specification_store, remainder_list) = cls._GetSpecificationStore(definitions.FORMAT_CATEGORY_STORAGE_MEDIA_IMAGE)
        cls._storage_media_image_remainder_list = remainder_list
        cls._storage_media_image_store = specification_store
    if (cls._storage_media_image_scanner is None):
        cls._storage_media_image_scanner = cls._GetSignatureScanner(cls._storage_media_image_store)
    return cls._GetTypeIndicators(cls._storage_media_image_scanner, cls._storage_media_image_store, cls._storage_media_image_remainder_list, path_spec, resolver_context=resolver_context)

Determines if a file contains a supported storage media image types.

Args:
path_spec (PathSpec): path specification.
resolver_context (Optional[Context]): resolver context, where None
represents the built-in context which is not multi process safe.

Returns:
list[str]: supported format type indicators.


def offset(self, num_to_skip):

        return self.__class__(
            self._parent,
            projection=self._projection,
            field_filters=self._field_filters,
            orders=self._orders,
            limit=self._limit,
            offset=num_to_skip,
            start_at=self._start_at,
            end_at=self._end_at,
        )

Skip to an offset in a query.

If the current query already has specified an offset, this will
overwrite it.

Args:
num_to_skip (int): The number of results to skip at the beginning
of query results. (Must be non-negative.)

Returns:
~.firestore_v1beta1.query.Query: An offset query. Acts as a
copy of the current query, modified with the newly added
"offset" field.


def _ParseRecord(self, parser_mediator, text_file_object):

    try:
      title = text_file_object.readline()
    except UnicodeDecodeError:
      parser_mediator.ProduceExtractionWarning(
          'unable to read and decode title')
      return False

    if not title:
      return False

    try:
      url = text_file_object.readline()
    except UnicodeDecodeError:
      parser_mediator.ProduceExtractionWarning(
          'unable to read and decode url')
      return False

    try:
      timestamp = text_file_object.readline()
    except UnicodeDecodeError:
      parser_mediator.ProduceExtractionWarning(
          'unable to read and decode timestamp')
      return False

    try:
      popularity_index = text_file_object.readline()
    except UnicodeDecodeError:
      parser_mediator.ProduceExtractionWarning(
          'unable to read and decode popularity index')
      return False

    event_data = OperaGlobalHistoryEventData()

    event_data.url = url.strip()

    title = title.strip()
    if title != event_data.url:
      event_data.title = title

    popularity_index = popularity_index.strip()
    try:
      event_data.popularity_index = int(popularity_index, 10)
    except ValueError:
      parser_mediator.ProduceExtractionWarning(
          'unable to convert popularity index: {0:s}'.format(popularity_index))

    if event_data.popularity_index < 0:
      event_data.description = 'First and Only Visit'
    else:
      event_data.description = 'Last Visit'

    timestamp = timestamp.strip()
    try:
      timestamp = int(timestamp, 10)
    except ValueError:
      parser_mediator.ProduceExtractionWarning(
          'unable to convert timestamp: {0:s}'.format(timestamp))
      timestamp = None

    if timestamp is None:
      date_time = dfdatetime_semantic_time.SemanticTime('Invalid')
    else:
      date_time = dfdatetime_posix_time.PosixTime(timestamp=timestamp)

    event = time_events.DateTimeValuesEvent(
        date_time, definitions.TIME_DESCRIPTION_LAST_VISITED)
    parser_mediator.ProduceEventWithEventData(event, event_data)

    return True

Parses an Opera global history record.

Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
text_file_object (dfvfs.TextFile): text file.

Returns:
bool: True if the record was successfully parsed.


def create_lb_with_nat_pool(access_token, subscription_id, resource_group, lb_name, public_ip_id, fe_start_port, fe_end_port, backend_port, location):
    endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/loadBalancers/', lb_name, '?api-version=', NETWORK_API])
    lb_body = {'location': location}
    frontendipcconfig = {'name': 'LoadBalancerFrontEnd'}
    fipc_properties = {'publicIPAddress': {'id': public_ip_id}}
    frontendipcconfig['properties'] = fipc_properties
    properties = {'frontendIPConfigurations': [frontendipcconfig]}
    properties['backendAddressPools'] = [{'name': 'bepool'}]
    inbound_natpool = {'name': 'natpool'}
    lbfe_id = (((((('/subscriptions/' + subscription_id) + '/resourceGroups/') + resource_group) + '/providers/Microsoft.Network/loadBalancers/') + lb_name) + '/frontendIPConfigurations/LoadBalancerFrontEnd')
    ibnp_properties = {'frontendIPConfiguration': {'id': lbfe_id}}
    ibnp_properties['protocol'] = 'tcp'
    ibnp_properties['frontendPortRangeStart'] = fe_start_port
    ibnp_properties['frontendPortRangeEnd'] = fe_end_port
    ibnp_properties['backendPort'] = backend_port
    inbound_natpool['properties'] = ibnp_properties
    properties['inboundNatPools'] = [inbound_natpool]
    lb_body['properties'] = properties
    body = json.dumps(lb_body)
    return do_put(endpoint, body, access_token)

Create a load balancer with inbound NAT pools.

Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource group name.
lb_name (str): Name of the new load balancer.
public_ip_id (str): Public IP address resource id.
fe_start_port (int): Start of front-end port range.
fe_end_port (int): End of front-end port range.
backend_port (int): Back end port for VMs.
location (str): Azure data center location. E.g. westus.

Returns:
HTTP response. Load Balancer JSON body.


Called at the end of training.

Subclasses should override for any actions to run.

Args:
logs: Dict. Currently the output of the last call to `on_epoch_end()`
is passed to this argument for this method but that may change in
the future.


def get_nondebug_quantized_model(self) -> bytes:
    return self._get_quantized_model(is_debug=False)

Returns a non-instrumented quantized model.

Convert the quantized model with the initialized converter and
return bytes for nondebug model. The model will not be instrumented with
numeric verification operations.

Returns:
Model bytes corresponding to the model.
Raises:
ValueError: if converter is not passed to the debugger.


def __format__(self, format_spec=None):

        if not format_spec:
            return str(self)
        elif format_spec == 'url':
            return self.to_url()
        elif format_spec.startswith('url:'):
            parts = format_spec.split(':')[1:]
            site = parts[0]
            if len(parts) > 1:
                country = parts[1]
            else:
                country = 'us'
            return self.to_url(site, country)
        elif format_spec == 'urn':
            return self.to_urn()
        else:
            raise ValueError('Unknown format_spec %r' % format_spec)

Extended pretty printing for ISBN strings.

Args:
format_spec (str): Extended format to use

Returns:
``str``: Human readable string representation of ``Isbn`` object

Raises:
ValueError: Unknown value for ``format_spec``


def CreateSitelinkFeedItem(feed_items, feed_item_id):
    site_link_from_feed = feed_items[feed_item_id]
    site_link_feed_item = {'sitelinkText': site_link_from_feed['text'], 'sitelinkLine2': site_link_from_feed['line2'], 'sitelinkLine3': site_link_from_feed['line3']}
    if (('finalUrls' in site_link_from_feed) and site_link_from_feed['finalUrls']):
        site_link_feed_item['sitelinkFinalUrls'] = {'urls': site_link_from_feed['finalUrls']}
        if ('finalMobileUrls' in site_link_from_feed):
            site_link_feed_item['sitelinkFinalMobileUrls'] = {'urls': site_link_from_feed['finalMobileUrls']}
        site_link_feed_item['sitelinkTrackingUrlTemplate'] = site_link_from_feed['trackingUrlTemplate']
    else:
        site_link_feed_item['sitelinkUrl'] = site_link_from_feed['url']
    return site_link_feed_item

Creates a Sitelink Feed Item.

Args:
feed_items: a list of all Feed Items.
feed_item_id: the Id of a specific Feed Item for which a Sitelink Feed Item
should be created.

Returns:
The new Sitelink Feed Item.


async def is_try_or_pull_request(self):
    tasks = [asyncio.ensure_future(link.is_try_or_pull_request()) for link in self.links]
    tasks.insert(0, asyncio.ensure_future(is_try_or_pull_request(self.context, self.task)))
    conditions = (await raise_future_exceptions(tasks))
    return any(conditions)

Determine if any task in the chain is a try task.

Returns:
bool: True if a task is a try task.


def memory_write8(self, addr, data, zone=None):

        return self.memory_write(addr, data, zone, 8)

Writes bytes to memory of a target system.

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

Returns:
Number of bytes written to target.

Raises:
JLinkException: on memory access error.


def resize(self, image: np.ndarray, size: Dict[str, int], anti_aliasing: bool=True, anti_aliasing_sigma=None, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray:
    requires_backends(self, 'scipy')
    output_shape = (size['height'], size['width'])
    image = to_channel_dimension_format(image, ChannelDimension.LAST)
    image, output_shape = _preprocess_resize_output_shape(image, output_shape)
    input_shape = image.shape
    factors = np.divide(input_shape, output_shape)
    ndi_mode = 'mirror'
    cval = 0
    order = 1
    if anti_aliasing:
        if anti_aliasing_sigma is None:
            anti_aliasing_sigma = np.maximum(0, (factors - 1) / 2)
        else:
            anti_aliasing_sigma = np.atleast_1d(anti_aliasing_sigma) * np.ones_like(factors)
            if np.any(anti_aliasing_sigma < 0):
                raise ValueError('Anti-aliasing standard deviation must be greater than or equal to zero')
            elif np.any((anti_aliasing_sigma > 0) & (factors <= 1)):
                warnings.warn('Anti-aliasing standard deviation greater than zero but not down-sampling along all axes')
        filtered = ndi.gaussian_filter(image, anti_aliasing_sigma, cval=cval, mode=ndi_mode)
    else:
        filtered = image
    zoom_factors = [1 / f for f in factors]
    out = ndi.zoom(filtered, zoom_factors, order=order, mode=ndi_mode, cval=cval, grid_mode=True)
    image = _clip_warp_output(image, out)
    image = to_channel_dimension_format(image, input_data_format, ChannelDimension.LAST)
    image = to_channel_dimension_format(image, data_format, input_data_format) if data_format is not None else image
    return image

Resize an image as per the original implementation.

Args:
image (`np.ndarray`):
Image to resize.
size (`Dict[str, int]`):
Dictionary containing the height and width to resize the image to.
anti_aliasing (`bool`, *optional*, defaults to `True`):
Whether to apply anti-aliasing when downsampling the image.
anti_aliasing_sigma (`float`, *optional*, defaults to `None`):
Standard deviation for Gaussian kernel when downsampling the image. If `None`, it will be calculated
automatically.
data_format (`str` or `ChannelDimension`, *optional*):
The channel dimension format of the image. If not provided, it will be the same as the input image.
input_data_format (`ChannelDimension` or `str`, *optional*):
The channel dimension format of the input image. If not provided, it will be inferred from the input
image.


def _detect(self):
    results = []
    for c in self.slither.contracts_derived:
        ret = self.detect_uninitialized(c)
        for (variable, functions) in ret:
            info = '{}.{} ({}) is never initialized. It is used in:\n'
            info = info.format(variable.contract.name, variable.name, variable.source_mapping_str)
            for f in functions:
                info += '\t- {} ({})\n'.format(f.name, f.source_mapping_str)
            source = [variable.source_mapping]
            source += [f.source_mapping for f in functions]
            json = self.generate_json_result(info)
            self.add_variable_to_json(variable, json)
            self.add_functions_to_json(functions, json)
            results.append(json)
    return results

Detect uninitialized state variables

Recursively visit the calls
Returns:
dict: [contract name] = set(state variable uninitialized)


def add_children(self, children):

        self._children += [c for c in children if c not in self._children]

Adds new children nodes after filtering for duplicates

Args:
children (list): list of OmniTree nodes to add as children


def fail_steamid(channel):
    gui = ui_embed.UI(channel, "That SteamID doesn't exist.", 'You can get your SteamID by going to your profile page and looking at the url, or you can set a custom ID by going to edit profile on your profile page.', modulename=modulename, colour=35071)
    return gui

Creates an embed UI for invalid SteamIDs

Args:
channel (discord.Channel): The Discord channel to bind the embed to

Returns:
ui (ui_embed.UI): The embed UI object


def __init__(self,
               power=0.,
               validate_args=False,
               name="power_transform"):

    self._graph_parents = []
    self._name = name
    self._validate_args = validate_args
    with self._name_scope("init"):
      power = tf.get_static_value(
          tf.convert_to_tensor(value=power, name="power"))
    if power is None or power < 0:
      raise ValueError("`power` must be a non-negative TF constant.")
    self._power = power
    super(PowerTransform, self).__init__(
        forward_min_event_ndims=0,
        validate_args=validate_args,
        name=name)

Instantiates the `PowerTransform` bijector.

Args:
power: Python `float` scalar indicating the transform power, i.e.,
`Y = g(X) = (1 + X * c)**(1 / c)` where `c` is the `power`.
validate_args: Python `bool` indicating whether arguments should be
checked for correctness.
name: Python `str` name given to ops managed by this object.

Raises:
ValueError: if `power < 0` or is not known statically.


def unkown_field(self, value=None):
    if (value is not None):
        try:
            value = str(value)
        except ValueError:
            raise ValueError('value {} need to be of type str for field `unkown_field`'.format(value))
        if (',' in value):
            raise ValueError('value should not contain a comma for field `unkown_field`')
    self._unkown_field = value

Corresponds to IDD Field `unkown_field` Empty field in data.

Args:
value (str): value for IDD Field `unkown_field`
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 sysmeta_add_preferred(sysmeta_pyxb, node_urn):
    if (not has_replication_policy(sysmeta_pyxb)):
        sysmeta_set_default_rp(sysmeta_pyxb)
    rp_pyxb = sysmeta_pyxb.replicationPolicy
    _add_node(rp_pyxb, 'pref', node_urn)
    _remove_node(rp_pyxb, 'block', node_urn)

Add a remote Member Node to the list of preferred replication targets to this
System Metadata object.

Also remove the target MN from the list of blocked Member Nodes if present.

If the target MN is already in the preferred list and not in the blocked list, this
function is a no-op.

Args:
sysmeta_pyxb : SystemMetadata PyXB object.
System Metadata in which to add the preferred replication target.

If the System Metadata does not already have a Replication Policy, a default
replication policy which enables replication is added and populated with the
preferred replication target.

node_urn : str
Node URN of the remote MN that will be added. On the form
``urn:node:MyMemberNode``.


def _SetYaraRules(self, yara_rules_string):
    if (not yara_rules_string):
        return
    analyzer_object = analyzers_manager.AnalyzersManager.GetAnalyzerInstance('yara')
    analyzer_object.SetRules(yara_rules_string)
    self._analyzers.append(analyzer_object)

Sets the Yara rules.

Args:
yara_rules_string (str): unparsed Yara rule definitions.


def get_cn_dict(self, structure, n, use_weights=False):
    siw = self.get_nn_info(structure, n)
    cn_dict = {}
    for i in siw:
        site_element = i['site'].species_string
        if (site_element not in cn_dict):
            if use_weights:
                cn_dict[site_element] = i['weight']
            else:
                cn_dict[site_element] = 1
        elif use_weights:
            cn_dict[site_element] += i['weight']
        else:
            cn_dict[site_element] += 1
    return cn_dict

Get coordination number, CN, of each element bonded to site with index n in structure

Args:
structure (Structure): input structure
n (integer): index of site for which to determine CN.
use_weights (boolean): flag indicating whether (True)
to use weights for computing the coordination number
or not (False, default: each coordinated site has equal
weight).

Returns:
cn (dict): dictionary of CN of each element bonded to site


def _get_dependent_variables(input_ops, output_ops):
    output_ops = nest.map_structure(gen_array_ops.identity, output_ops)
    inbetween_ops = op_selector.get_backward_walk_ops(seed_ops=output_ops, stop_at_ts=input_ops, inclusive=False, only_differentiable=True)
    var_ops = (op for op in inbetween_ops if op.type in VAR_OP_TYPES)
    var_names = (op.name for op in var_ops)
    tf_vars = (get_variable_by_name(var_name) for var_name in var_names)
    tf_vars = [v for v in tf_vars if v is not None]
    return tf_vars

Finds variables involved in the subgraph between input_ops and output_ops.

Args:
input_ops: Flattened list of input ops
output_ops: Flattened list of output ops

Returns:
A list of variables


def parse_GDS(filepath):

    dataset_lines = []
    subsets = {}
    database = None
    dataset_name = None
    with utils.smart_open(filepath) as soft:
        groupper = groupby(soft, lambda x: x.startswith("^"))
        for is_new_entry, group in groupper:
            if is_new_entry:
                entry_type, entry_name = __parse_entry(next(group))
                logger.debug("%s: %s" % (entry_type.upper(), entry_name))
                if entry_type == "SUBSET":
                    is_data, data_group = next(groupper)
                    message = ("The key is not False, probably there is an "
                               "error in the SOFT file")
                    assert not is_data, message
                    subset_metadata = parse_metadata(data_group)
                    subsets[entry_name] = GDSSubset(name=entry_name,
                                                    metadata=subset_metadata)
                elif entry_type == "DATABASE":

                    is_data, data_group = next(groupper)
                    message = ("The key is not False, probably there is an "
                               "error in the SOFT file")
                    assert not is_data, message
                    database_metadata = parse_metadata(data_group)
                    database = GEODatabase(name=entry_name,
                                           metadata=database_metadata)
                elif entry_type == "DATASET":
                    is_data, data_group = next(groupper)
                    dataset_name = entry_name
                    for line in data_group:
                        dataset_lines.append(line.rstrip())
                else:
                    logger.error("Cannot recognize type %s" % entry_type)

    metadata = parse_metadata(dataset_lines)
    columns = parse_GDS_columns(dataset_lines, subsets)
    table = parse_table_data(dataset_lines)
    return GDS(name=dataset_name, metadata=metadata, columns=columns,
               table=table, subsets=subsets, database=database)

Parse GDS SOFT file.

Args:
filepath (:obj:`str`): Path to GDS SOFT file.

Returns:
:obj:`GEOparse.GDS`: A GDS object.


def convert_squeeze(params, w_name, scope_name, inputs, layers, weights, names):
    print('Converting squeeze ...')
    if (len(params['axes']) > 1):
        raise AssertionError('Cannot convert squeeze by multiple dimensions')

    def target_layer(x, axis=int(params['axes'][0])):
        import tensorflow as tf
        return tf.squeeze(x, axis=axis)
    lambda_layer = keras.layers.Lambda(target_layer)
    layers[scope_name] = lambda_layer(layers[inputs[0]])

Convert squeeze operation.

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


def script_dir(pyobject, follow_symlinks=True):

    if getattr(sys, 'frozen', False):
        path = abspath(sys.executable)
    else:
        path = inspect.getabsfile(pyobject)
    if follow_symlinks:
        path = realpath(path)
    return dirname(path)

Get current script's directory

Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.

Returns:
str: Current script's directory


def __init__(self, expr, weld_type, df=None, column_name=None, index_type=None, index_name=None):

        self.expr = expr
        self.weld_type = weld_type
        self.dim = 1
        self.df = df
        self.column_name = column_name
        self.index_type = index_type
        self.index_name = index_name

Summary

TODO: Implement an actual Index Object like how Pandas does
Args:
expr (TYPE): Description
weld_type (TYPE): Description
df (None, optional): Description
column_name (None, optional): Description


def visualize_decision(features, labels, true_w_b, candidate_w_bs, fname):
    fig = figure.Figure(figsize=(6, 6))
    canvas = backend_agg.FigureCanvasAgg(fig)
    ax = fig.add_subplot(1, 1, 1)
    ax.scatter(features[(:, 0)], features[(:, 1)], c=np.float32(labels[(:, 0)]), cmap=cm.get_cmap('binary'), edgecolors='k')

    def plot_weights(w, b, **kwargs):
        (w1, w2) = w
        x1s = np.linspace((- 1), 1, 100)
        x2s = ((- ((w1 * x1s) + b)) / w2)
        ax.plot(x1s, x2s, **kwargs)
    for (w, b) in candidate_w_bs:
        plot_weights(w, b, alpha=(1.0 / np.sqrt(len(candidate_w_bs))), lw=1, color='blue')
    if (true_w_b is not None):
        plot_weights(*true_w_b, lw=4, color='green', label='true separator')
    ax.set_xlim([(- 1.5), 1.5])
    ax.set_ylim([(- 1.5), 1.5])
    ax.legend()
    canvas.print_figure(fname, format='png')
    print('saved {}'.format(fname))

Utility method to visualize decision boundaries in R^2.

Args:
features: Input points, as a Numpy `array` of shape `[num_examples, 2]`.
labels: Numpy `float`-like array of shape `[num_examples, 1]` giving a
label for each point.
true_w_b: A `tuple` `(w, b)` where `w` is a Numpy array of
shape `[2]` and `b` is a scalar `float`, interpreted as a
decision rule of the form `dot(features, w) + b > 0`.
candidate_w_bs: Python `iterable` containing tuples of the same form as
true_w_b.
fname: The filename to save the plot as a PNG image (Python `str`).


def get_percentile_to_value_dict(self, percentile_list):
    result = {}
    total = 0
    percentile_list_index = 0
    count_at_percentile = 0
    percentile_list = list(set(percentile_list))
    percentile_list.sort()
    for index in range(self.counts_len):
        total += self.get_count_at_index(index)
        while True:
            if (not count_at_percentile):
                if (percentile_list_index == len(percentile_list)):
                    return result
                percentile = percentile_list[percentile_list_index]
                percentile_list_index += 1
                if (percentile > 100):
                    return result
                count_at_percentile = self.get_target_count_at_percentile(percentile)
            if (total >= count_at_percentile):
                value_at_index = self.get_value_from_index(index)
                if percentile:
                    result[percentile] = self.get_highest_equivalent_value(value_at_index)
                else:
                    result[percentile] = self.get_lowest_equivalent_value(value_at_index)
                count_at_percentile = 0
            else:
                break
    return result

A faster alternative to query values for a list of percentiles.

Args:
percentile_list: a list of percentiles in any order, dups will be ignored
each element in the list must be a float value in [0.0 .. 100.0]
Returns:
a dict of percentile values indexed by the percentile


def find_clients(self, hosts):
    clients = []
    for host in hosts:
        clients.append(self._get_client_by_hostname(host))
    return [client for client in clients if (client is not None)]

Finds GRR clients given a list of hosts.

Args:
hosts: List of hostname FQDNs

Returns:
List of GRR client objects.


def crud_handler(Model, name=None, **kwds):

    from nautilus.network.events import combine_action_handlers
    from . import update_handler, create_handler, delete_handler, read_handler

    return combine_action_handlers(
        create_handler(Model, name=name),
        read_handler(Model, name=name),
        update_handler(Model, name=name),
        delete_handler(Model, name=name),
    )

This action handler factory reaturns an action handler that
responds to actions with CRUD types (following nautilus conventions)
and performs the necessary mutation on the model's database.

Args:
Model (nautilus.BaseModel): The model to delete when the action
received.

Returns:
function(type, payload): The action handler for this model


def _AssertGrayscaleImage(image):
    return control_flow_ops.with_dependencies(_CheckGrayscaleImage(image, require_static=False), image)

Assert that we are working with a properly shaped grayscale image.

Performs the check statically if possible (i.e. if the shape
is statically known). Otherwise adds a control dependency
to an assert op that checks the dynamic shape.

Args:
image: >= 2-D Tensor of size [*, 1]

Raises:
ValueError: if image.shape is not a [>= 2] vector or if
last dimension is not size 1.

Returns:
If the shape of `image` could be verified statically, `image` is
returned unchanged, otherwise there will be a control dependency
added that asserts the correct dynamic shape.


def format_diff_pyxb(a_pyxb, b_pyxb):

    return '\n'.join(
        difflib.ndiff(
            serialize_to_xml_str(a_pyxb).splitlines(),
            serialize_to_xml_str(b_pyxb).splitlines(),
        )
    )

Create a diff between two PyXB objects.

Args:
a_pyxb: PyXB object
b_pyxb: PyXB object

Returns:
str : `Differ`-style delta


def __init__(self, source_geo_def, target_geo_def):

        self.source_geo_def = source_geo_def
        self.target_geo_def = target_geo_def

Initialize resampler with geolocation information.

Args:
source_geo_def (SwathDefinition, AreaDefinition):
Geolocation definition for the data to be resampled
target_geo_def (CoordinateDefinition, AreaDefinition):
Geolocation definition for the area to resample data to.


def delay_response(delay):

    delay = min(float(delay), 10)

    time.sleep(delay)

    return jsonify(
        get_dict("url", "args", "form", "data", "origin", "headers", "files")
    )

Returns a delayed response (max of 10 seconds).
---
tags:
- Dynamic data
parameters:
- in: path
name: delay
type: int
produces:
- application/json
responses:
200:
description: A delayed response.


Create an accumulator based on 'output'.

This method creates a new accumulator with identical internal state to the
one used to create the data in 'output'. This means that if you do

output_data = combiner.extract(accumulator_1)
accumulator_2 = combiner.restore(output_data)

then accumulator_1 and accumulator_2 will have identical internal state, and
computations using either of them will be equivalent.

Args:
output: The data output from a previous computation. Should be in the same
form as provided by 'extract_output'.

Returns:
A new accumulator.


def _GetAuthCookie(self, auth_token):

		continue_location = "http:
		args = {"continue": continue_location, "auth": auth_token}
		req = self._CreateRequest("https:
		try:
			response = self.opener.open(req)
		except urllib2.HTTPError, e:
			response = e
		if (response.code != 302 or
				response.info()["location"] != continue_location):
			raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp)
		self.authenticated = True

Fetches authentication cookies for an authentication token.

Args:
auth_token: The authentication token returned by ClientLogin.

Raises:
HTTPError: If there was an error fetching the authentication cookies.


def __init__(self, fetches):
    if isinstance(fetches, wrapt.ObjectProxy):
        self._fetch_type = type(fetches.__wrapped__)
    else:
        self._fetch_type = type(fetches)
    self._mappers = [_FetchMapper.for_fetch(fetch) for fetch in fetches]
    self._unique_fetches, self._value_indices = _uniquify_fetches(self._mappers)

Creates a _ListFetchMapper.

Args:
fetches: List, tuple, or namedtuple of fetches.


def mpim_close(self, *, channel: str, **kwargs) -> SlackResponse:

        kwargs.update({"channel": channel})
        return self.api_call("mpim.close", json=kwargs)

Closes a multiparty direct message channel.

Args:
channel (str): Multiparty Direct message channel to close. e.g. 'G1234567890'


def __eq__(self, other):

        if not isinstance(other, LocationDescriptor):
            return False

        nbr_of_sub_locations = self.nbr_of_sub_locations()

        if nbr_of_sub_locations != other.nbr_of_sub_locations():
            return False

        for i in range(nbr_of_sub_locations):
            if self._locations_list[i] != other._locations_list[i]:
                return False

        return True

Detect if another object is equal to this :class:`LocationDescriptor` object.

Args:
other: object to test.


def get_by_resource(self, resource_uri):
    uri = (((self.URI + self.RESOURCES_PATH) + '/') + resource_uri)
    return self._client.get(id_or_uri=uri)

Gets all the labels for the specified resource

Args:
resource_uri: The resource URI

Returns:
dict: Resource Labels


def find(self, collection, query):

        obj = getattr(self.db, collection)
        result = obj.find(query)
        return result

Search a collection for the query provided. Just a raw interface to
mongo to do any query you want.

Args:
collection: The db collection. See main class documentation.
query: A mongo find query.
Returns:
pymongo Cursor object with the results.


def process(self, batch, *args, **kwargs):

        if self.postprocessing is not None:
            batch = self.postprocessing(batch)
        return batch

Process a list of examples to create a batch.

Postprocess the batch with user-provided Pipeline.

Args:
batch (list(object)): A list of object from a batch of examples.
Returns:
object: Processed object given the input and custom
postprocessing Pipeline.


def Shell(device, *command):
    if command:
        return device.StreamingShell(' '.join(command))
    else:
        terminal_prompt = device.InteractiveShell()
        print(terminal_prompt.decode('utf-8'))
        while True:
            cmd = input('> ')
            if (not cmd):
                continue
            elif (cmd == 'exit'):
                break
            else:
                stdout = device.InteractiveShell(cmd, strip_cmd=True, delim=terminal_prompt, strip_delim=True)
                if stdout:
                    if isinstance(stdout, bytes):
                        stdout = stdout.decode('utf-8')
                        print(stdout)
        device.Close()

Runs a command on the device and prints the stdout.

Args:
command: Command to run on the target.


def _summary_iterator(test_dir):
    event_paths = sorted(glob.glob(os.path.join(test_dir, 'event*')))
    return summary_iterator.summary_iterator(event_paths[-1])

Reads events from test_dir/events.

Args:
test_dir: Name of the test directory.

Returns:
A summary_iterator


def __init__(self, details, _class):

		if not isinstance(details, dict):
			raise ValueError('details in ' + self.__class__.__name__ + '.' + sys._getframe().f_code.co_name + ' must be a dict')

		self.validation_failures = {}

		self._class = _class

		self._optional = False

		if '__optional__' in details:

			if isinstance(details['__optional__'], bool):
				self._optional = details['__optional__']

			else:
				sys.stderr.write('"' + str(details['__optional__']) + '" is not a valid value for __optional__, assuming false')

			del details['__optional__']

		self._special = {}

		for k in (tuple(details.keys())):

			oMatch = _specialKey.match(k)
			if oMatch:

				self._special[oMatch.group(1)] = details[k]
				del details[k]

Constructor

Initialises the instance

Arguments:
details {dict} -- Details describing the type of values allowed for
the node
_class {str} -- The class of the child

Raises:
ValueError

Returns:
_BaseNode


def _ScheduleTask(self, task):
    if self._processing_profiler:
        self._processing_profiler.StartTiming('schedule_task')
    try:
        self._task_queue.PushItem(task, block=False)
        is_scheduled = True
    except errors.QueueFull:
        is_scheduled = False
    if self._processing_profiler:
        self._processing_profiler.StopTiming('schedule_task')
    return is_scheduled

Schedules a task.

Args:
task (Task): task.

Returns:
bool: True if the task was scheduled.


def read_into(self, buffer, viewport=None, components=3, *, attachment=0, alignment=1, dtype='f1', write_offset=0) -> None:
    if (type(buffer) is Buffer):
        buffer = buffer.mglo
    return self.mglo.read_into(buffer, viewport, components, attachment, alignment, dtype, write_offset)

Read the content of the framebuffer into a buffer.

Args:
buffer (bytearray): The buffer that will receive the pixels.
viewport (tuple): The viewport.
components (int): The number of components to read.

Keyword Args:
attachment (int): The color attachment.
alignment (int): The byte alignment of the pixels.
dtype (str): Data type.
write_offset (int): The write offset.


def get_graph(self, run_key, device_name, debug=False):

    return self.get_graphs(run_key, debug=debug).get(device_name, None)

Get the runtime GraphDef proto associated with a run key and a device.

Args:
run_key: A Session.run kay.
device_name: Name of the device in question.
debug: Whether the debugger-decoratedgraph is to be retrieved.

Returns:
A `GraphDef` proto.


def check_plugin(self, plugin):

        vcf_section = self[plugin]

        try:
            vcf_field = vcf_section['field']
            if not  vcf_field in self.vcf_columns:
                raise ValidateError(
                        "field has to be in {0}\n"
                        "Wrong field name in plugin: {1}".format(
                        self.vcf_columns, plugin
                    ))
            if vcf_field == 'INFO':
                try:
                    info_key = vcf_section['info_key']

                    if info_key == 'CSQ':
                        try:
                            csq_key = vcf_section['csq_key']
                        except KeyError:
                            raise ValidateError(
                        "CSQ entrys has to refer to an csq field.\n"
                        "Refer with keyword 'csq_key'\n"
                        "csq_key is missing in section: {0}".format(
                            plugin
                            )
                        )

                except KeyError:
                    raise ValidateError(
                        "INFO entrys has to refer to an INFO field.\n"
                        "Refer with keyword 'info_key'\n"
                        "info_key is missing in section: {0}".format(
                            plugin
                            )
                        )
        except KeyError:
            raise ValidateError(
                "Vcf entrys have to refer to a field in the VCF with keyword"
                " 'field'.\nMissing keyword 'field' in plugin: {0}".format(
                  plugin
                ))

        try:
            data_type = vcf_section['data_type']
            if not data_type in self.data_types:
                raise ValidateError(
                    "data_type has to be in {0}\n"
                    "Wrong data_type in plugin: {1}".format(
                        self.data_types, plugin)
                    )
        except KeyError:
            raise ValidateError(
                "Vcf entrys have to refer to a data type in the VCF with "
                "keyword 'data_type'.\n"
                "Missing data_type in plugin: {0}".format(plugin)
                )

        separators = vcf_section.get('separators', None)
        if separators:
            if len(separators) == 1:
                self[plugin]['separators'] = list(separators)
        else:
            if data_type != 'flag':
                raise ValidateError(
                    "If data_type != flag the separators have to be defined"
                    "Missing separators in plugin: {0}".format(plugin)
                    )

        record_rule = vcf_section.get('record_rule', None)

        if record_rule:
            if not record_rule in ['min', 'max']:
                raise ValidateError(
                    "Record rules have to be in {0}\n"
                    "Wrong record_rule in plugin: {1}".format(
                        ['min', 'max'], plugin)
                )
        else:
            self.logger.info("Setting record rule to default: 'max'")

        return True

Check if the section is in the proper format vcf format.

Args:
vcf_section (dict): The information from a vcf section

Returns:
True is it is in the proper format


def _emit_tensor_snapshot(self, tensor: _TensorTracker, timestamp: int, pid: int, tid: int, value: step_stats_pb2.NodeOutput) -> None:
    desc = str(value.tensor_description).replace('"', '')
    snapshot = {'tensor_description': desc}
    self._chrome_trace.emit_obj_snapshot('Tensor', tensor.name, timestamp, pid, tid, tensor.object_id, snapshot)

Generate Chrome Trace snapshot event for a computed Tensor.

Args:
tensor: A 'TensorTracker' object.
timestamp:  The timestamp of this snapshot as a long integer.
pid: The pid assigned for showing the device where this op ran.
tid: The tid of the thread computing the tensor snapshot.
value: A JSON-compliant snapshot of the object.


def sysprep(disk, distro, loader=None, backend='direct', **kwargs):
    if (loader is None):
        loader = PackageLoader('lago', 'templates')
    sysprep_file = _render_template(distro, loader=loader, **kwargs)
    cmd = ['virt-sysprep', '-a', disk]
    cmd.extend(['--commands-from-file', sysprep_file])
    env = os.environ.copy()
    if ('LIBGUESTFS_BACKEND' not in env):
        env['LIBGUESTFS_BACKEND'] = backend
    ret = utils.run_command(cmd, env=env)
    if ret:
        raise RuntimeError(('Failed to bootstrap %s\ncommand:%s\nstdout:%s\nstderr:%s' % (disk, ' '.join((('"%s"' % elem) for elem in cmd)), ret.out, ret.err)))

Run virt-sysprep on the ``disk``, commands are built from the distro
specific template and arguments passed in ``kwargs``. If no template is
available it will default to ``sysprep-base.j2``.

Args:
disk(str): path to disk
distro(str): distro to render template for
loader(jinja2.BaseLoader): Jinja2 template loader, if not passed,
will search Lago's package.
backend(str): libguestfs backend to use
**kwargs(dict): environment variables for Jinja2 template

Returns:
None

Raises:
RuntimeError: On virt-sysprep none 0 exit code.


def save_output(results, output_directory="output"):

    aggregate_reports = results["aggregate_reports"]
    forensic_reports = results["forensic_reports"]

    if os.path.exists(output_directory):
        if not os.path.isdir(output_directory):
            raise ValueError("{0} is not a directory".format(output_directory))
    else:
        os.makedirs(output_directory)

    with open("{0}".format(os.path.join(output_directory, "aggregate.json")),
              "w", newline="\n", encoding="utf-8") as agg_json:
        agg_json.write(json.dumps(aggregate_reports, ensure_ascii=False,
                                  indent=2))

    with open("{0}".format(os.path.join(output_directory, "aggregate.csv")),
              "w", newline="\n", encoding="utf-8") as agg_csv:
        csv = parsed_aggregate_reports_to_csv(aggregate_reports)
        agg_csv.write(csv)

    with open("{0}".format(os.path.join(output_directory, "forensic.json")),
              "w", newline="\n", encoding="utf-8") as for_json:
        for_json.write(json.dumps(forensic_reports, ensure_ascii=False,
                                  indent=2))

    with open("{0}".format(os.path.join(output_directory, "forensic.csv")),
              "w", newline="\n", encoding="utf-8") as for_csv:
        csv = parsed_forensic_reports_to_csv(forensic_reports)
        for_csv.write(csv)

    samples_directory = os.path.join(output_directory, "samples")
    if not os.path.exists(samples_directory):
        os.makedirs(samples_directory)

    sample_filenames = []
    for forensic_report in forensic_reports:
        sample = forensic_report["sample"]
        message_count = 0
        parsed_sample = forensic_report["parsed_sample"]
        subject = parsed_sample["filename_safe_subject"]
        filename = subject

        while filename in sample_filenames:
            message_count += 1
            filename = "{0} ({1})".format(subject, message_count)

        sample_filenames.append(filename)

        filename = "{0}.eml".format(filename)
        path = os.path.join(samples_directory, filename)
        with open(path, "w", newline="\n", encoding="utf-8") as sample_file:
            sample_file.write(sample)

Save report data in the given directory

Args:
results (OrderedDict): Parsing results
output_directory: The patch to the directory to save in


def _ReadEventDataIntoEvent(self, event):

    if self._storage_type != definitions.STORAGE_TYPE_SESSION:
      return

    event_data_identifier = event.GetEventDataIdentifier()
    if event_data_identifier:
      lookup_key = event_data_identifier.CopyToString()
      event_data = self._event_data[lookup_key]

      for attribute_name, attribute_value in event_data.GetAttributes():
        setattr(event, attribute_name, attribute_value)

Reads the data into the event.

This function is intended to offer backwards compatible event behavior.

Args:
event (EventObject): event.


def report(self, verbose=1):
    lines = []
    if (verbose >= 2):
        lines.append(self._status_line(tense='past'))
        if (verbose >= 3):
            (unit, mag) = _choose_unit(self.total_time, self.unit, self._asciimode)
            lines.append('    body took: {total:.{pr}{t}} {unit}'.format(total=(self.total_time / mag), t=self._precision_type, pr=self._precision, unit=unit))
        lines.append('    time per loop: {}'.format(self._seconds_str()))
    else:
        line = ('Timed ' + self._seconds_str())
        if self.label:
            line += (' for ' + self.label)
        lines.append(line)
    text = '\n'.join(lines)
    return text

Creates a human readable report

Args:
verbose (int): verbosity level. Either 1, 2, or 3.

Returns:
str: the report

SeeAlso:
timerit.Timerit.print

Example:
>>> import math
>>> ti = Timerit(num=1).call(math.factorial, 5)
>>> print(ti.report(verbose=1))
Timed best=...s, mean=...s


def GetSortedEvents(self, time_range=None):

    filter_expression = None
    if time_range:
      filter_expression = []

      if time_range.start_timestamp:
        filter_expression.append(
            '_timestamp >= {0:d}'.format(time_range.start_timestamp))

      if time_range.end_timestamp:
        filter_expression.append(
            '_timestamp <= {0:d}'.format(time_range.end_timestamp))

      filter_expression = ' AND '.join(filter_expression)

    event_generator = self._GetAttributeContainers(
        self._CONTAINER_TYPE_EVENT, filter_expression=filter_expression,
        order_by='_timestamp')

    for event in event_generator:
      if hasattr(event, 'event_data_row_identifier'):
        event_data_identifier = identifiers.SQLTableIdentifier(
            'event_data', event.event_data_row_identifier)
        event.SetEventDataIdentifier(event_data_identifier)

        del event.event_data_row_identifier

      yield event

Retrieves the events in increasing chronological order.

Args:
time_range (Optional[TimeRange]): time range used to filter events
that fall in a specific period.

Yield:
EventObject: event.


class RandomNormal(RandomInitializer):

    def __init__(self, mean=0.0, stddev=0.05, seed=None):
        self.mean = mean
        self.stddev = stddev
        super().__init__(seed=seed)

    def __call__(self, shape, dtype=None):
        return random.normal(shape=shape, mean=self.mean, stddev=self.stddev, seed=self.seed, dtype=dtype)

    def get_config(self):
        base_config = super().get_config()
        config = {'mean': self.mean, 'stddev': self.stddev}
        return {**base_config, **config}

Random normal initializer.

Draws samples from a normal distribution for given parameters.

Examples:

>>> # Standalone usage:
>>> initializer = RandomNormal(mean=0.0, stddev=1.0)
>>> values = initializer(shape=(2, 2))

>>> # Usage in a Keras layer:
>>> initializer = RandomNormal(mean=0.0, stddev=1.0)
>>> layer = Dense(3, kernel_initializer=initializer)

Args:
mean: A python scalar or a scalar keras tensor. Mean of the random
values to generate.
stddev: A python scalar or a scalar keras tensor. Standard deviation of
the random values to generate.
seed: A Python integer or instance of
`keras.backend.SeedGenerator`.
Used to make the behavior of the initializer
deterministic. Note that an initializer seeded with an integer
or `None` (unseeded) will produce the same random values
across multiple calls. To get different random values
across multiple calls, use as seed an instance
of `keras.backend.SeedGenerator`.


def __init__(self, data_type, unit=None,
                 analysis_period=None, metadata=None):

        assert hasattr(data_type, 'isDataType'), \
            'data_type must be a Ladybug DataType. Got {}'.format(type(data_type))
        if unit is None:
            unit = data_type.units[0]
        else:
            data_type.is_unit_acceptable(unit)
        if analysis_period is not None:
            assert hasattr(analysis_period, 'isAnalysisPeriod'), \
                'analysis_period must be a Ladybug AnalysisPeriod. Got {}'.format(
                    type(analysis_period))
        if metadata is not None:
            assert isinstance(metadata, dict), \
                'metadata must be a dictionary. Got {}'.format(type(metadata))

        self._data_type = data_type
        self._unit = unit
        self._analysis_period = analysis_period
        self._metadata = metadata or {}

Initiate Ladybug header for lists.

Args:
data_type: A DataType object. (e.g. Temperature)
unit: data_type unit (Default: None)
analysis_period: A Ladybug analysis period (Defualt: None)
metadata: Optional dictionary of additional metadata,
containing information such as 'source', 'city', or 'zone'.


def JoinPath(self, path_segments):

    first_path_segment = None

    if path_segments and platform.system() == 'Windows':

      first_path_segment = path_segments[0]
      first_path_segment_length = len(first_path_segment)
      first_path_segment_prefix = None

      if (first_path_segment_length >= 7 and
          first_path_segment.startswith('\\\\.\\') and
          first_path_segment[5:7] == ':\\'):
        first_path_segment_prefix = first_path_segment[4:6]
        first_path_segment = first_path_segment[7:]

      elif (first_path_segment_length >= 4 and
            first_path_segment[:4] in ['\\\\.\\', '\\\\?\\']):
        first_path_segment_prefix = first_path_segment[:4]
        first_path_segment = first_path_segment[4:]

      elif first_path_segment_length >= 2 and first_path_segment[1] == ':':
        first_path_segment_prefix = first_path_segment[:2]
        first_path_segment = first_path_segment[2:]

      elif first_path_segment.startswith('\\\\'):
        prefix, _, remainder = first_path_segment[2:].partition(
            self.PATH_SEPARATOR)

        first_path_segment_prefix = '\\\\{0:s}'.format(prefix)
        first_path_segment = '\\{0:s}'.format(remainder)

      if first_path_segment_prefix:
        first_path_segment, _, remainder = first_path_segment.partition(
            self.PATH_SEPARATOR)

        if not remainder:
          _ = path_segments.pop(0)
        else:
          path_segments[0] = remainder

        first_path_segment = ''.join([
            first_path_segment_prefix, first_path_segment])

      else:
        first_path_segment = None

    path_segments = [
        segment.split(self.PATH_SEPARATOR) for segment in path_segments]

    path_segments = [
        element for sublist in path_segments for element in sublist]

    path_segments = list(filter(None, path_segments))

    if first_path_segment is None:
      path = '{0:s}{1:s}'.format(
          self.PATH_SEPARATOR, self.PATH_SEPARATOR.join(path_segments))
    else:
      path = first_path_segment
      if path_segments:
        path = '{0:s}{1:s}{2:s}'.format(
            path, self.PATH_SEPARATOR, self.PATH_SEPARATOR.join(path_segments))

    return path

Joins the path segments into a path.

Args:
path_segments (list[str]): path segments.

Returns:
str: joined path segments prefixed with the path separator.


def write(self, output_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
    local_stream = utils.BytearrayStream()
    if self._unique_identifier:
        self._unique_identifier.write(local_stream, kmip_version=kmip_version)
    self.length = local_stream.length()
    super(ArchiveResponsePayload, self).write(output_stream, kmip_version=kmip_version)
    output_stream.write(local_stream.buffer)

Write the data encoding the Archive response payload to a stream.

Args:
output_stream (stream): A data stream in which to encode object
data, supporting a write 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 data attribute is not defined.


def from_config(cls, config):
    config.pop('dtype', None)
    return cls(**config)

Instantiates an initializer from a configuration dictionary.

Example:

```python
initializer = RandomUniform(-1, 1)
config = initializer.get_config()
initializer = RandomUniform.from_config(config)
```

Args:
config: A Python dictionary.
It will typically be the output of `get_config`.

Returns:
An Initializer instance.


def UploadFilePath(self, filepath, offset=0, amount=None):

    return self._UploadChunkStream(
        self._streamer.StreamFilePath(filepath, offset=offset, amount=amount))

Uploads chunks of a file on a given path to the transfer store flow.

Args:
filepath: A path to the file to upload.
offset: An integer offset at which the file upload should start on.
amount: An upper bound on number of bytes to stream. If it is `None` then
the whole file is uploaded.

Returns:
A `BlobImageDescriptor` object.


def delete_folder(self, folder):
    if (not is_valid_uuid(folder)):
        raise StorageArgumentException('Invalid UUID for folder: {0}'.format(folder))
    self._authenticated_request.to_endpoint('folder/{}/'.format(folder)).delete()

Delete a folder. It will recursively delete all the content.

Args:
folder_id (str): The UUID of the folder to be deleted.

Returns:
None

Raises:
StorageArgumentException: Invalid arguments
StorageForbiddenException: 403
StorageNotFoundException: 404
HTTPError: other non-20x error codes


def Deserialize(self, reader: BinaryReader):

        self.Type = StateType(reader.ReadByte())

        self.Key = reader.ReadVarBytes(max=100)
        self.Field = reader.ReadVarString(max=32).decode('utf-8')
        self.Value = reader.ReadVarBytes(max=65535)

        if self.Type == StateType.Account:
            self.CheckAccountState()
        elif self.Type == StateType.Validator:
            self.CheckValidatorState()

Deserialize full object.

Args:
reader (neocore.IO.BinaryReader):


def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0):
    mask = input_ids.ne(padding_idx).int()
    incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask
    return incremental_indices.long() + padding_idx

Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
are ignored. This is modified from fairseq's *utils.make_positions*.

Args:
input_ids (`torch.LongTensor`):
Indices of input sequence tokens in the vocabulary.

Returns: torch.Tensor


async def fetch(self, method, url, params=None, headers=None, data=None):
    logger.debug('Sending request %s %s:\n%r', method, url, data)
    for retry_num in range(MAX_RETRIES):
        try:
            async with self.fetch_raw(method, url, params=params, headers=headers, data=data) as res:
                async with async_timeout.timeout(REQUEST_TIMEOUT):
                    body = (await res.read())
            logger.debug('Received response %d %s:\n%r', res.status, res.reason, body)
        except asyncio.TimeoutError:
            error_msg = 'Request timed out'
        except aiohttp.ServerDisconnectedError as err:
            error_msg = 'Server disconnected error: {}'.format(err)
        except (aiohttp.ClientError, ValueError) as err:
            error_msg = 'Request connection error: {}'.format(err)
        else:
            break
        logger.info('Request attempt %d failed: %s', retry_num, error_msg)
    else:
        logger.info('Request failed after %d attempts', MAX_RETRIES)
        raise exceptions.NetworkError(error_msg)
    if (res.status != 200):
        logger.info('Request returned unexpected status: %d %s', res.status, res.reason)
        raise exceptions.NetworkError('Request return unexpected status: {}: {}'.format(res.status, res.reason))
    return FetchResponse(res.status, body)

Make an HTTP request.

Automatically uses configured HTTP proxy, and adds Google authorization
header and cookies.

Failures will be retried MAX_RETRIES times before raising NetworkError.

Args:
method (str): Request method.
url (str): Request URL.
params (dict): (optional) Request query string parameters.
headers (dict): (optional) Request headers.
data: (str): (optional) Request body data.

Returns:
FetchResponse: Response data.

Raises:
NetworkError: If the request fails.


def can_create(self):
    if (self.data.get('key_name') and self.data.get('value_name') and self.data.get('value_type')):
        return True
    return False

If the key_name, value_name, and value_type has been provided returns that the
Registry Key can be created, otherwise returns that the Registry Key cannot be created.

Returns:


def strace(device, trace_address, breakpoint_address):
    jlink = pylink.JLink()
    jlink.open()
    jlink.power_on()
    jlink.set_tif(pylink.JLinkInterfaces.SWD)
    jlink.connect(device)
    jlink.reset()
    jlink.breakpoint_clear_all()
    op = pylink.JLinkStraceOperation.TRACE_START
    jlink.strace_clear_all()
    jlink.strace_start()
    bphandle = jlink.breakpoint_set(breakpoint_address, thumb=True)
    trhandle = jlink.strace_code_fetch_event(op, address=trace_address)
    jlink.restart()
    time.sleep(1)
    while True:
        if jlink.halted():
            break
    while True:
        instructions = jlink.strace_read(1)
        if (len(instructions) == 0):
            break
        instruction = instructions[0]
        print(jlink.disassemble_instruction(instruction))
    jlink.power_off()
    jlink.close()

Implements simple trace using the STrace API.

Args:
device (str): the device to connect to
trace_address (int): address to begin tracing from
breakpoint_address (int): address to breakpoint at

Returns:
``None``


def resolve_class(classref):
    if (classref is None):
        return None
    elif isinstance(classref, six.class_types):
        return classref
    elif isinstance(classref, six.string_types):
        return import_class(classref)
    else:
        raise ValueError(("Unable to resolve class for '%s'" % classref))

Attempt to return a Python class for the input class reference.

If `classref` is a class or None, return it. If `classref` is a
python classpath (e.g., "foo.bar.MyClass") import the class and return
it.

Args:
classref: A fully-qualified Python path to class, or a Python class.

Returns:
A class.


def load_test_config_file(test_config_path, tb_filters=None):
    configs = _load_config_file(test_config_path)
    if tb_filters:
        tbs = []
        for tb in configs[keys.Config.key_testbed.value]:
            if tb[keys.Config.key_testbed_name.value] in tb_filters:
                tbs.append(tb)
        if len(tbs) != len(tb_filters):
            raise MoblyConfigError('Expect to find %d test bed configs, found %d. Check if you have the correct test bed names.' % (len(tb_filters), len(tbs)))
        configs[keys.Config.key_testbed.value] = tbs
    mobly_params = configs.get(keys.Config.key_mobly_params.value, {})
    log_path = mobly_params.get(keys.Config.key_log_path.value, _DEFAULT_LOG_PATH)
    if ENV_MOBLY_LOGPATH in os.environ:
        log_path = os.environ[ENV_MOBLY_LOGPATH]
    log_path = utils.abs_path(log_path)
    _validate_test_config(configs)
    _validate_testbed_configs(configs[keys.Config.key_testbed.value])
    test_configs = []
    for original_bed_config in configs[keys.Config.key_testbed.value]:
        test_run_config = TestRunConfig()
        test_run_config.testbed_name = original_bed_config[keys.Config.key_testbed_name.value]
        test_run_config.test_bed_name = test_run_config.testbed_name
        test_run_config.log_path = log_path
        test_run_config.controller_configs = original_bed_config.get(keys.Config.key_testbed_controllers.value, {})
        test_run_config.user_params = original_bed_config.get(keys.Config.key_testbed_test_params.value, {})
        test_configs.append(test_run_config)
    return test_configs

Processes the test configuration file provied by user.

Loads the configuration file into a dict, unpacks each testbed
config into its own dict, and validate the configuration in the
process.

Args:
test_config_path: Path to the test configuration file.
tb_filters: A subset of test bed names to be pulled from the config
file. If None, then all test beds will be selected.

Returns:
A list of test configuration dicts to be passed to
test_runner.TestRunner.


def add_figure(self, key, url, **kwargs):

        figure = self._check_metadata_for_file(key=key, url=url, **kwargs)

        for dict_key in (
            'caption',
            'label',
            'material',
            'filename',
            'url',
            'original_url',
        ):
            if kwargs.get(dict_key) is not None:
                figure[dict_key] = kwargs[dict_key]

        if key_already_there(figure, self.record.get('figures', ())):
            raise ValueError(
                'There\'s already a figure with the key %s.'
                % figure['key']
            )

        self._append_to('figures', figure)
        self.add_document

Add a figure.

Args:
key (string): document key
url (string): document url
Keyword Args:
caption (string): simple description
label (string):
material (string):
original_url (string): original url
filename (string): current url

Returns: None


def get_permissions(self):
    user_role = (self.last_login_role() if self.last_login_role_key else self.role_set[0].role)
    return user_role.get_permissions()

Permissions of the user.

Returns:
List of Permission objects.


def _prepare_init_params_from_job_description(cls, job_details):

        init_params = dict()

        init_params['model_name'] = job_details['ModelName']
        init_params['instance_count'] = job_details['TransformResources']['InstanceCount']
        init_params['instance_type'] = job_details['TransformResources']['InstanceType']
        init_params['volume_kms_key'] = job_details['TransformResources'].get('VolumeKmsKeyId')
        init_params['strategy'] = job_details.get('BatchStrategy')
        init_params['assemble_with'] = job_details['TransformOutput'].get('AssembleWith')
        init_params['output_path'] = job_details['TransformOutput']['S3OutputPath']
        init_params['output_kms_key'] = job_details['TransformOutput'].get('KmsKeyId')
        init_params['accept'] = job_details['TransformOutput'].get('Accept')
        init_params['max_concurrent_transforms'] = job_details.get('MaxConcurrentTransforms')
        init_params['max_payload'] = job_details.get('MaxPayloadInMB')
        init_params['base_transform_job_name'] = job_details['TransformJobName']

        return init_params

Convert the transform job description to init params that can be handled by the class constructor

Args:
job_details (dict): the returned job details from a describe_transform_job API call.

Returns:
dict: The transformed init_params


def run(main, argv=None, flags_parser=parse_flags_with_usage):
    try:
        args = _run_init((sys.argv if (argv is None) else argv), flags_parser)
        while _init_callbacks:
            callback = _init_callbacks.popleft()
            callback()
        try:
            _run_main(main, args)
        except UsageError as error:
            usage(shorthelp=True, detailed_error=error, exitcode=error.exitcode)
        except:
            if FLAGS.pdb_post_mortem:
                traceback.print_exc()
                pdb.post_mortem()
            raise
    except Exception as e:
        _call_exception_handlers(e)
        raise

Begins executing the program.

Args:
main: The main function to execute. It takes an single argument "argv",
which is a list of command line arguments with parsed flags removed.
If it returns an integer, it is used as the process's exit code.
argv: A non-empty list of the command line arguments including program name,
sys.argv is used if None.
flags_parser: Callable[[List[Text]], Any], the function used to parse flags.
The return value of this function is passed to `main` untouched.
It must guarantee FLAGS is parsed after this function is called.
- Parses command line flags with the flag module.
- If there are any errors, prints usage().
- Calls main() with the remaining arguments.
- If main() raises a UsageError, prints usage and the error message.


def convert_variable_to_constant(self, incoming_edge, tensor_data):
    raise NotImplementedError

Converts a variable in this Convertible and its dependencies.

This method should make sure that a converted copy of itself is present in
the converted graph, and that all Convertibles depending on this one also go
through the same process.

Args:
incoming_edge: The graph edge into this Convertible that is being
converted to a constant.
tensor_data: The tensor representing the constant.


def _get_original_composition_ratio(self, reaction):

        if self.c1_original == self.c2_original:
            return 1
        c1_coeff = reaction.get_coeff(self.c1_original) \
            if self.c1_original in reaction.reactants else 0
        c2_coeff = reaction.get_coeff(self.c2_original) \
            if self.c2_original in reaction.reactants else 0
        return c1_coeff * 1.0 / (c1_coeff + c2_coeff)

Returns the molar mixing ratio between the reactants with ORIGINAL (
instead of processed) compositions for a reaction.

Args:
reaction (Reaction): Reaction object that contains the original
reactant compositions.

Returns:
The molar mixing ratio between the original reactant
compositions for a reaction.


def getEstTraitCovar(self,term_i=None):

        assert self.P>1, 'Trait covars not defined for single trait analysis'

        if term_i==None:
            RV=SP.zeros((self.P,self.P))
            for term_i in range(self.n_terms): RV+=self.vd.getTerm(term_i).getTraitCovar().K()
        else:
            assert term_i<self.n_terms, 'Term index non valid'
            RV = self.vd.getTerm(term_i).getTraitCovar().K()
        return RV

Returns explicitly the estimated trait covariance matrix

Args:
term_i:     index of the term we are interested in